34 lines
1.3 KiB
Rust
34 lines
1.3 KiB
Rust
|
use crate::{storages::traits::AdministratorRepository, models::administrator::Administrator};
|
||
|
use nanoid::nanoid;
|
||
|
use sha2::Sha256;
|
||
|
use std::cell::RefCell;
|
||
|
|
||
|
pub struct AuthService {
|
||
|
authed: RefCell<Vec::<(String, i32)>>
|
||
|
}
|
||
|
|
||
|
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<String, String> {
|
||
|
let administrator = storage.find_by_username(&username).await?;
|
||
|
if pbkdf2::pbkdf2_hmac_array::<Sha256, 32>(password.as_bytes(), dotenv_codegen::dotenv!("SALT").as_bytes(), 4096).iter().map(|x| format!("{:x}", x)).collect::<String>() != 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<Administrator, String> {
|
||
|
let id = self.authed.borrow().iter().find(|&x| x.0.starts_with(token)).ok_or("Invalid token")?.1;
|
||
|
storage.read(id).await
|
||
|
}
|
||
|
}
|