ouisync/repository/
credentials.rs

1use super::metadata;
2use crate::{
3    access_control::{AccessMode, AccessSecrets},
4    crypto::sign,
5    error::{Error, Result},
6};
7use bincode::Options;
8use serde::{Deserialize, Serialize};
9
10/// Credentials for accessing a repository.
11#[derive(Clone, Serialize, Deserialize)]
12pub struct Credentials {
13    pub(super) secrets: AccessSecrets,
14    pub(super) writer_id: sign::PublicKey,
15}
16
17impl Credentials {
18    pub fn with_random_writer_id(secrets: AccessSecrets) -> Self {
19        Self {
20            secrets,
21            writer_id: metadata::generate_writer_id(),
22        }
23    }
24
25    pub fn with_mode(self, access_mode: AccessMode) -> Self {
26        Self {
27            secrets: self.secrets.with_mode(access_mode),
28            ..self
29        }
30    }
31
32    pub fn encode(&self) -> Vec<u8> {
33        // unwrap is ok because serialization into a vector can't fail unless we have a bug in the
34        // code.
35        bincode::options().serialize(self).unwrap()
36    }
37
38    pub fn decode(input: &[u8]) -> Result<Self> {
39        bincode::options()
40            .deserialize(input)
41            .map_err(|_| Error::MalformedData)
42    }
43}