aboutsummaryrefslogtreecommitdiff
path: root/lockchain-core/src/users/keystore.rs
blob: 7da77ec9606fc93c0860ab1406c52c2ddf0bef96 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! A keystore is a specific implementation of a metadata store
//! 
//! At it's core it provides three simple functions
//! 
//! - Adding keys for a user
//! - Removing keys
//! - Retrieving keys
//! 
//! **This module is meant to be used by lockchain-library implementations**

#![deprecated(since="0.10.0", note="Use the `userstore::UserStore` structure instead")]

use traits::{AutoEncoder, Base64AutoEncoder};
use {crypto::Key, meta::MetaDomain};

use std::collections::HashMap;

/// A utility wrapper around a Username -> Key collection
#[derive(Serialize, Deserialize)]
pub struct KeyStore {
    keys: HashMap<String, Key>,
}

impl KeyStore {
    pub fn add_key(&mut self, user: &str, key: Key) {
        self.keys.insert(user.into(), key);
    }

    pub fn revoke_key(&mut self, user: &str) {
        self.keys.remove(user);
    }
}

impl AutoEncoder for KeyStore {}

impl From<MetaDomain> for KeyStore {
    fn from(d: MetaDomain) -> Self {
        Self {
            keys: d
                .all()
                .iter()
                .map(|(k, v)| {
                    (
                        k.clone(),
                        match v {
                            ::Payload::Text(s) => Key::decode(&String::from_base64(s)).unwrap(),
                            _ => unreachable!(),
                        },
                    )
                })
                .collect(),
        }
    }
}

impl From<KeyStore> for MetaDomain {
    fn from(ks: KeyStore) -> Self {
        MetaDomain::new("keystore").fill(
            ks.keys
                .iter()
                .map(|(name, key)| {
                    (
                        name.clone(),
                        ::Payload::Text(key.encode().unwrap().to_base64()),
                    )
                })
                .collect(),
        )
    }
}