use crate::data::entity_manager::EntityManager; use crate::data::service::ServiceID; use crate::utils::err::Res; pub type UserID = String; #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct User { pub uid: UserID, pub first_name: String, pub last_last: String, pub username: String, pub email: String, pub password: String, pub need_reset_password: bool, pub enabled: bool, pub admin: bool, /// None = all services /// Some([]) = no service pub authorized_services: Option>, } impl PartialEq for User { fn eq(&self, other: &Self) -> bool { self.uid.eq(&other.uid) } } impl Eq for User {} impl Default for User { fn default() -> Self { Self { uid: uuid::Uuid::new_v4().to_string(), first_name: "".to_string(), last_last: "".to_string(), username: "".to_string(), email: "".to_string(), password: "".to_string(), need_reset_password: false, enabled: true, admin: false, authorized_services: None, } } } pub fn hash_password>(pwd: P) -> Res { Ok(bcrypt::hash(pwd, bcrypt::DEFAULT_COST)?) } pub fn verify_password>(pwd: P, hash: &str) -> bool { match bcrypt::verify(pwd, hash) { Ok(r) => r, Err(e) => { log::warn!("Failed to verify password! {:?}", e); false } } } impl EntityManager { pub fn find_by_username_or_email(&self, u: &str) -> Option { for entry in self.iter() { if entry.username.eq(u) || entry.email.eq(u) { return Some(entry.clone()); } } None } pub fn find_by_user_id(&self, id: &UserID) -> Option { for entry in self.iter() { if entry.uid.eq(id) { return Some(entry.clone()); } } None } /// Update user information fn update_user(&mut self, id: &UserID, update: F) -> bool where F: FnOnce(User) -> User { let user = match self.find_by_user_id(id) { None => return false, Some(user) => user }; if let Err(e) = self.replace_entries(|u| u.uid.eq(id), &update(user)) { log::error!("Failed to update user information! {:?}", e); return false; } true } pub fn change_user_password(&mut self, id: &UserID, password: &str, temporary: bool) -> bool { let new_hash = match hash_password(password) { Ok(h) => { h } Err(e) => { log::error!("Failed to hash user password! {}", e); return false; } }; self.update_user(id, |mut user| { user.password = new_hash; user.need_reset_password = temporary; user }) } }