use super::*;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
impl AuthenticationManager {
pub fn new(jwt_secret: &[u8]) -> Self {
Self {
password_hasher: PasswordHasher::new(),
jwt_manager: JwtManager::new(jwt_secret),
users: Arc::new(RwLock::new(HashMap::new())),
}
}
pub fn with_config(jwt_secret: &[u8], access_expiration_secs: u64, refresh_expiration_secs: u64) -> Self {
Self {
password_hasher: PasswordHasher::new(),
jwt_manager: JwtManager::with_expiration(jwt_secret, access_expiration_secs, refresh_expiration_secs),
users: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn add_user(&self, user: User) -> AuthResult<()> {
let mut users = self.users.write().await;
users.insert(user.username.clone(), user);
Ok(())
}
pub async fn register_user(&self, username: &str, password: &str, role: &str) -> AuthResult<()> {
self.password_hasher.validate_strength(password)?;
let password_hash = self.password_hasher.hash(password)?;
let user = User {
id: username.to_string(),
username: username.to_string(),
password_hash,
role: role.to_string(),
email: None,
created_at: None,
};
let mut users = self.users.write().await;
users.insert(username.to_string(), user);
Ok(())
}
pub async fn authenticate(&self, credentials: AuthCredentials) -> AuthResult<String> {
let users = self.users.read().await;
let user = users.get(&credentials.username).ok_or(AuthError::InvalidCredentials)?;
self.password_hasher
.verify(&credentials.password, &user.password_hash)?;
let token = self
.jwt_manager
.generate_token(&user.id, &user.username, &user.role, TokenType::Access)?;
Ok(token)
}
pub fn verify_token(&self, token: &str) -> AuthResult<JwtClaims> {
self.jwt_manager.verify_token(token)
}
pub fn refresh_token(&self, refresh_token: &str) -> AuthResult<String> {
self.jwt_manager.refresh_access_token(refresh_token)
}
pub async fn get_user(&self, username: &str) -> AuthResult<User> {
let users = self.users.read().await;
users
.get(username)
.cloned()
.ok_or_else(|| AuthError::UserNotFound(username.to_string()))
}
pub async fn remove_user(&self, username: &str) -> AuthResult<()> {
let mut users = self.users.write().await;
users
.remove(username)
.map(|_| ())
.ok_or_else(|| AuthError::UserNotFound(username.to_string()))
}
}