use crate::{storages::traits::AdministratorRepository, models::administrator::Administrator}; use nanoid::nanoid; use sha2::Sha256; use std::cell::RefCell; pub struct AuthService { authed: RefCell> } impl AuthService { pub fn new() -> Self { AuthService { authed: RefCell::new(Vec::new()) } } pub async fn login(&self, storage: &dyn AdministratorRepository, username: &str, password: &str) -> Result { let administrator = storage.find_by_username(&username).await?; if pbkdf2::pbkdf2_hmac_array::(password.as_bytes(), dotenv_codegen::dotenv!("SALT").as_bytes(), 4096).iter().map(|x| format!("{:x}", x)).collect::() != administrator.password { Err("Invalid password or login!".to_owned()) } else { let token = nanoid!(32); self.authed.borrow_mut().push((token.clone(), administrator.id)); Ok(token) } } pub fn logout(&self, token: &str) { self.authed.borrow_mut().retain(|x| x.0 != token); } pub async fn administrator_by_token(&self, storage: &dyn AdministratorRepository, token: &str) -> Result { let id = self.authed.borrow().iter().find(|&x| x.0.starts_with(token)).ok_or("Invalid token")?.1; storage.read(id).await } }