use actix::{Actor, Context, Handler, Message, MessageResult}; use crate::data::entity_manager::EntityManager; use crate::data::user::{User, UserID, verify_password}; #[derive(Debug)] pub enum LoginResult { AccountNotFound, InvalidPassword, Success(User), } #[derive(Message)] #[rtype(LoginResult)] pub struct LoginRequest { pub login: String, pub password: String, } #[derive(Debug)] pub struct ChangePasswordResult(pub bool); #[derive(Message)] #[rtype(ChangePasswordResult)] pub struct ChangePasswordRequest { pub user_id: UserID, pub new_password: String, pub temporary: bool, } pub struct UsersActor { manager: EntityManager, } impl UsersActor { pub fn new(manager: EntityManager) -> Self { Self { manager } } } impl Actor for UsersActor { type Context = Context; } impl Handler for UsersActor { type Result = MessageResult; fn handle(&mut self, msg: LoginRequest, _ctx: &mut Self::Context) -> Self::Result { match self.manager.find_by_username_or_email(&msg.login) { None => MessageResult(LoginResult::AccountNotFound), Some(user) => { if !verify_password(msg.password, &user.password) { return MessageResult(LoginResult::InvalidPassword); } MessageResult(LoginResult::Success(user)) } } } } impl Handler for UsersActor { type Result = MessageResult; fn handle(&mut self, msg: ChangePasswordRequest, _ctx: &mut Self::Context) -> Self::Result { MessageResult(ChangePasswordResult( self.manager.change_user_password(&msg.user_id, &msg.new_password, msg.temporary))) } }