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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
use base64::prelude::{Engine as _, BASE64_STANDARD_NO_PAD};
use std::{cell::RefCell, future::Future, rc::Rc};
use web_sys::{wasm_bindgen::JsValue, CryptoKeyPair, Storage};

/// A key for storing the identity key pair.
pub const KEY_STORAGE_KEY: &str = "identity";
/// A key for storing the delegation chain.
pub const KEY_STORAGE_DELEGATION: &str = "delegation";
pub(crate) const KEY_VECTOR: &str = "iv";

const LOCAL_STORAGE_PREFIX: &str = "ic-";

/// Enum for storing different types of keys.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StoredKey {
    String(String),
    CryptoKeyPair(CryptoKeyPair),
}

impl StoredKey {
    pub fn decode(&self) -> Result<Vec<u8>, String> {
        match self {
            StoredKey::String(s) => BASE64_STANDARD_NO_PAD.decode(s).map_err(|e| e.to_string()),
            StoredKey::CryptoKeyPair(_) => Err("CryptoKeyPair cannot be decoded".to_string()),
        }
    }

    pub fn encode<T: AsRef<[u8]>>(data: T) -> String {
        BASE64_STANDARD_NO_PAD.encode(data.as_ref())
    }
}

impl From<String> for StoredKey {
    fn from(value: String) -> Self {
        StoredKey::String(value)
    }
}

/// Trait for persisting user authentication data.
pub trait AuthClientStorage {
    fn get<T: AsRef<str>>(&mut self, key: T) -> impl Future<Output = Option<StoredKey>>;

    fn set<S: AsRef<str>, T: AsRef<str>>(&mut self, key: S, value: T) -> impl Future<Output = ()>;

    fn remove<T: AsRef<str>>(&mut self, key: T) -> impl Future<Output = ()>;
}

/// Implementation of [`AuthClientStorage`].
#[derive(Debug, Default, Clone)]
pub struct LocalStorage {
    local_storage: Option<Storage>,
}

impl LocalStorage {
    pub fn new(local_storage: Option<Storage>) -> Self {
        LocalStorage { local_storage }
    }

    fn get_local_storage(&self) -> Result<Storage, JsValue> {
        if let Some(local_storage) = self.local_storage.clone() {
            return Ok(local_storage);
        }

        if let Some(window) = web_sys::window() {
            let local_storage = window.local_storage()?;
            local_storage.ok_or("Could not find local storage.".into())
        } else {
            Err("No window found".into())
        }
    }
}

impl AuthClientStorage for LocalStorage {
    async fn get<T: AsRef<str>>(&mut self, key: T) -> Option<StoredKey> {
        let local_storage = self.get_local_storage().unwrap();
        let key = format!("{}{}", LOCAL_STORAGE_PREFIX, key.as_ref());
        let value = local_storage.get_item(&key).unwrap();
        value.map(StoredKey::String)
    }

    async fn set<S: AsRef<str>, T: AsRef<str>>(&mut self, key: S, value: T) {
        let local_storage = self.get_local_storage().unwrap();
        let key = format!("{}{}", LOCAL_STORAGE_PREFIX, key.as_ref());
        local_storage.set_item(&key, value.as_ref()).unwrap();
    }

    async fn remove<T: AsRef<str>>(&mut self, key: T) {
        let local_storage = self.get_local_storage().unwrap();
        let key = format!("{}{}", LOCAL_STORAGE_PREFIX, key.as_ref());
        local_storage.remove_item(&key).unwrap();
    }
}

/*
/// IdbStorage is an interface for simple storage of string key-value pairs built on IdbKeyVal.
#[derive(Debug, Clone)]
pub struct IdbStorage {
    initialized_db: Rc<RefCell<Option<IdbKeyVal>>>,
    db_name: String,
    store_name: String,
    version: u32,
}

impl IdbStorage {
    pub fn new(db_name: String, store_name: String, version: u32) -> Self {
        IdbStorage {
            initialized_db: Rc::new(RefCell::new(None)),
            db_name,
            store_name,
            version,
        }
    }

    async fn init_db(&mut self) {
        if self.initialized_db.borrow().is_none() {
            let options = DbCreateOptions {
                db_name: Some(self.db_name.clone()),
                store_name: Some(self.store_name.clone()),
                version: Some(self.version),
            };
            let db = IdbKeyVal::new_with_options(options).await;
            self.initialized_db = Rc::new(RefCell::new(Some(db)));
        }
    }
}

impl AuthClientStorage for IdbStorage {
    async fn get<T: AsRef<str>>(&mut self, key: T) -> Option<StoredKey> {
        self.init_db().await;
        let db = self.initialized_db.as_ref().unwrap();
        let key = format!("{}{}", LOCAL_STORAGE_PREFIX, key.as_ref());
        let result = db.get(&key).await;
        match result {
            Ok(value) => match value {
                Some(value) => value
                    .as_str()
                    .map(|value| StoredKey::String(value.to_string())),
                None => None,
            },
            Err(_) => None,
        }
    }

    async fn set<T: AsRef<str>>(&mut self, key: T, value: T) {
        self.init_db().await;
        let db = self.initialized_db.as_ref().unwrap();
        let key = format!("{}{}", LOCAL_STORAGE_PREFIX, key.as_ref());
        db.set::<String, String>(key, value.as_ref().to_string())
            .await
            .unwrap();
    }

    async fn remove<T: AsRef<str>>(&mut self, key: T) {
        self.init_db().await;
        let db = self.initialized_db.as_ref().unwrap();
        let key = format!("{}{}", LOCAL_STORAGE_PREFIX, key.as_ref());
        db.remove(&key).await.unwrap();
    }
}
*/

/// Enum for selecting the type of storage to use for [`AuthClient`](super::AuthClient).
#[derive(Debug, Clone)]
pub enum AuthClientStorageType {
    LocalStorage(Rc<RefCell<LocalStorage>>),
}

impl Default for AuthClientStorageType {
    fn default() -> Self {
        AuthClientStorageType::LocalStorage(Rc::new(RefCell::new(LocalStorage::new(None))))
    }
}

impl AuthClientStorage for AuthClientStorageType {
    async fn get<T: AsRef<str>>(&mut self, key: T) -> Option<StoredKey> {
        match self {
            AuthClientStorageType::LocalStorage(storage) => {
                let mut storage = storage.borrow_mut().clone();
                storage.get(key).await
            }
        }
    }

    async fn set<S: AsRef<str>, T: AsRef<str>>(&mut self, key: S, value: T) {
        match self {
            AuthClientStorageType::LocalStorage(storage) => {
                let mut storage = storage.borrow_mut().clone();
                storage.set(key, value).await
            }
        }
    }

    async fn remove<T: AsRef<str>>(&mut self, key: T) {
        match self {
            AuthClientStorageType::LocalStorage(storage) => {
                let mut storage = storage.borrow_mut().clone();
                storage.remove(key).await
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wasm_bindgen_test::*;

    #[wasm_bindgen_test]
    async fn test_local_storage() {
        let mut storage = LocalStorage::default();
        storage.set("test", "value").await;
        let value = storage.get("test").await.unwrap();
        assert_eq!(value, StoredKey::String("value".to_string()));
        storage.remove("test").await;
        let value = storage.get("test").await;
        assert_eq!(value, None);
    }

    #[wasm_bindgen_test]
    async fn test_auth_client_storage_type() {
        let mut storage = AuthClientStorageType::LocalStorage(Rc::new(RefCell::new(LocalStorage::default())));
        storage.set("test", "value").await;
        let value = storage.get("test").await.unwrap();
        assert_eq!(value, StoredKey::String("value".to_string()));
        storage.remove("test").await;
        let value = storage.get("test").await;
        assert_eq!(value, None);
    }
}