This commit is contained in:
2026-05-10 03:16:13 +02:00
parent 5f05108132
commit 0b441b0759
77 changed files with 2100 additions and 71 deletions
+88
View File
@@ -0,0 +1,88 @@
use crate::models::user;
use crate::repositories::RepositoryContext;
use crate::utils::password;
use sea_orm::{
ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, IntoActiveModel, PaginatorTrait,
QueryFilter, Set,
};
use std::sync::Arc;
#[derive(Clone)]
pub struct UserRepository {
pub context: Arc<RepositoryContext>,
}
impl UserRepository {
pub async fn get_all(&self) -> Result<Vec<user::Model>, DbErr> {
user::Entity::find().all(&self.context.db).await
}
pub async fn count(&self) -> Result<u64, DbErr> {
user::Entity::find().count(&self.context.db).await
}
pub async fn get_by_id(&self, id: uuid::Uuid) -> Result<Option<user::Model>, DbErr> {
user::Entity::find_by_id(id).one(&self.context.db).await
}
pub async fn get_by_username(&self, username: String) -> Result<Option<user::Model>, DbErr> {
user::Entity::find()
.filter(user::Column::Username.eq(username))
.one(&self.context.db)
.await
}
pub async fn check_password(
&self,
username: String,
password: String,
) -> Result<user::Model, DbErr> {
let user = self.get_by_username(username).await?;
if let Some(user) = user {
let password_ok = password::verify_password(password.as_str(), user.password.as_str())
.map_err(|_| DbErr::Custom("Password hashing failed".to_string()))?;
if password_ok {
return Ok(user);
}
}
Err(DbErr::Custom("Invalid username or password".to_string()))
}
pub async fn update(&self, active: user::ActiveModel) -> Result<user::Model, DbErr> {
let user = active.update(&self.context.db).await?;
self.context.events.emit("user_updated", user.clone());
Ok(user)
}
pub async fn create(&self, active: user::ActiveModel) -> Result<user::Model, DbErr> {
let user = active.insert(&self.context.db).await?;
self.context.events.emit("user_created", user.clone());
Ok(user)
}
pub async fn set_password(&self, id: uuid::Uuid, password: String) -> Result<(), DbErr> {
let user = self
.get_by_id(id)
.await?
.ok_or_else(|| DbErr::Custom("User not found".to_string()))?;
let mut active = user.into_active_model();
let password = password::hash_password(&password)
.map_err(|_| DbErr::Custom("Password hashing failed".to_string()))?;
active.password = Set(password);
let user = self.update(active).await?;
self.context.events.emit("user_changed", user);
Ok(())
}
pub async fn delete(&self, id: uuid::Uuid) -> Result<(), DbErr> {
user::Entity::delete_by_id(id)
.exec(&self.context.db)
.await?;
self.context.events.emit("user_deleted", id);
Ok(())
}
}