refactor: migrate to clean architecture with trait-based DI (v0.2.0)
Complete architectural overhaul across all 12 crates: - Replace validator crate with zod-rs for all DTO validation - Replace manual pagination with paginator-rs/paginator-sea-orm - Migrate all modules (iam, cms, gacha, dimentorin) to clean architecture: domain → application → infrastructure layers - Introduce trait-based DI (Arc<dyn Trait>) at every layer for repositories and services - Delete all v1/ legacy SurrealDB-era code across every crate - Replace opaque response helpers with typed IntoResponse structs (ApiSuccess, ApiCreated, ApiPaginated, ApiMessage) - Remove dual_mode_repository, migration_validation_errors, validator.rs dead code - Zero cargo clippy warnings; release build clean Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
1b3366d735
commit
e432a1a743
@@ -0,0 +1,2 @@
|
||||
pub mod user_service;
|
||||
pub use user_service::UserServiceImpl;
|
||||
@@ -0,0 +1,95 @@
|
||||
use std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_libs::{hash_password, verify_password};
|
||||
use crate::users::domain::{UserEntity, UserListItem, UserRepository, UserService};
|
||||
|
||||
pub struct UserServiceImpl {
|
||||
repo: Arc<dyn UserRepository>,
|
||||
}
|
||||
|
||||
impl UserServiceImpl {
|
||||
pub fn new(repo: Arc<dyn UserRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UserService for UserServiceImpl {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<UserListItem>, AppError> {
|
||||
self.repo.find_all(params).await
|
||||
}
|
||||
|
||||
async fn get(&self, id: String) -> Result<UserEntity, AppError> {
|
||||
self.repo.find_by_id(&id).await
|
||||
}
|
||||
|
||||
async fn get_me(&self, user_id: String) -> Result<UserEntity, AppError> {
|
||||
self.repo.find_by_id(&user_id).await
|
||||
}
|
||||
|
||||
async fn get_by_email(&self, email: String) -> Result<UserEntity, AppError> {
|
||||
self.repo.find_by_email(email).await
|
||||
}
|
||||
|
||||
async fn create(&self, entity: UserEntity) -> Result<UserEntity, AppError> {
|
||||
// Check for email conflict
|
||||
match self.repo.find_by_email(entity.email.clone()).await {
|
||||
Ok(_) => return Err(AppError::ConflictError("User already exists".into())),
|
||||
Err(AppError::NotFoundError(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
let email = entity.email.clone();
|
||||
self.repo.create(entity).await?;
|
||||
self.repo.find_by_email(email).await
|
||||
}
|
||||
|
||||
async fn update(&self, entity: UserEntity) -> Result<String, AppError> {
|
||||
let existing = self.repo.find_by_id(&entity.id).await?;
|
||||
if existing.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
self.repo.update(entity).await
|
||||
}
|
||||
|
||||
async fn delete(&self, id: String) -> Result<String, AppError> {
|
||||
let user = self.repo.find_by_id(&id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
|
||||
async fn set_active_status(&self, id: String, is_active: bool) -> Result<String, AppError> {
|
||||
let mut user = self.repo.find_by_id(&id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
user.is_active = is_active;
|
||||
self.repo.update(user).await
|
||||
}
|
||||
|
||||
async fn update_password(&self, email: String, old_password: String, new_password: String) -> Result<String, AppError> {
|
||||
let user = self.repo.find_by_email(email.clone()).await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".into()))?;
|
||||
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
|
||||
let is_valid = verify_password(&old_password, &user.password)
|
||||
.map_err(|_| AppError::BadRequestError("Password verification failed".into()))?;
|
||||
if !is_valid {
|
||||
return Err(AppError::BadRequestError("Old password is incorrect".into()));
|
||||
}
|
||||
|
||||
let new_hash = hash_password(&new_password)
|
||||
.map_err(|_| AppError::InternalServerError("Failed to hash password".into()))?;
|
||||
|
||||
let mut updated = user;
|
||||
updated.password = new_hash;
|
||||
self.repo.update(updated).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod user;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
|
||||
pub use user::UserEntity;
|
||||
pub use repository::{UserRepository, UserListItem};
|
||||
pub use service::UserService;
|
||||
@@ -0,0 +1,28 @@
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_utils::AppError;
|
||||
use super::user::UserEntity;
|
||||
|
||||
/// Lightweight list item returned by list queries
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UserListItem {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserRepository: Send + Sync {
|
||||
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<UserListItem>, AppError>;
|
||||
async fn find_by_id(&self, id: &str) -> Result<UserEntity, AppError>;
|
||||
async fn find_by_email(&self, email: String) -> Result<UserEntity, AppError>;
|
||||
async fn create(&self, entity: UserEntity) -> Result<String, AppError>;
|
||||
async fn update(&self, entity: UserEntity) -> Result<String, AppError>;
|
||||
async fn delete(&self, id: String) -> Result<String, AppError>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_utils::AppError;
|
||||
use super::user::UserEntity;
|
||||
use super::repository::UserListItem;
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserService: Send + Sync {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<UserListItem>, AppError>;
|
||||
async fn get(&self, id: String) -> Result<UserEntity, AppError>;
|
||||
async fn get_me(&self, user_id: String) -> Result<UserEntity, AppError>;
|
||||
async fn get_by_email(&self, email: String) -> Result<UserEntity, AppError>;
|
||||
async fn create(&self, entity: UserEntity) -> Result<UserEntity, AppError>;
|
||||
async fn update(&self, entity: UserEntity) -> Result<String, AppError>;
|
||||
async fn delete(&self, id: String) -> Result<String, AppError>;
|
||||
async fn set_active_status(&self, id: String, is_active: bool) -> Result<String, AppError>;
|
||||
async fn update_password(&self, email: String, old_password: String, new_password: String) -> Result<String, AppError>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use imphnen_entities::{RolesDetailQueryDto, users::UserProfileExtensionDto};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct UserEntity {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
pub fullname: String,
|
||||
pub legal_name: Option<String>,
|
||||
pub password: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub role: RolesDetailQueryDto,
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub mentor_id: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
use imphnen_entities::{RolesDetailItemDto, UsersDetailQueryDto, users::UserProfileExtensionDto};
|
||||
use imphnen_libs::ZodValidate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use zod_rs::prelude::*;
|
||||
use crate::users::domain::{UserEntity, UserListItem};
|
||||
|
||||
#[derive(Serialize, Deserialize, ToSchema)]
|
||||
#[schema(description = "File upload form data for multipart/form-data")]
|
||||
pub struct FileUploadSchema {
|
||||
#[schema(format = "binary")]
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersActiveInactiveRequestDto {
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersSetNewPasswordRequestDto {
|
||||
pub password: String,
|
||||
pub old_password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
|
||||
pub struct UsersCreateRequestDto {
|
||||
#[zod(email, min_length(1))]
|
||||
pub email: String,
|
||||
#[zod(min_length(8), regex(pattern = "^[A-Za-z\\d@$!%*?&]{8,}$"))]
|
||||
pub password: String,
|
||||
#[zod(min_length(2))]
|
||||
pub fullname: String,
|
||||
pub is_active: bool,
|
||||
pub role_id: String,
|
||||
pub avatar: Option<String>,
|
||||
}
|
||||
|
||||
impl ZodValidate for UsersCreateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
Self::validate_and_parse(value).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersUpdateRequestDto {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub email: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub password: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fullname: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_active: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub role_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
}
|
||||
|
||||
impl ZodValidate for UsersUpdateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct UsersDetailItemDto {
|
||||
pub id: String,
|
||||
pub role: RolesDetailItemDto,
|
||||
pub fullname: String,
|
||||
pub legal_name: Option<String>,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl From<UserEntity> for UsersDetailItemDto {
|
||||
fn from(e: UserEntity) -> Self {
|
||||
Self {
|
||||
id: e.id,
|
||||
role: RolesDetailItemDto::from(&e.role),
|
||||
fullname: e.fullname,
|
||||
legal_name: e.legal_name,
|
||||
email: e.email,
|
||||
avatar: e.avatar,
|
||||
is_active: e.is_active,
|
||||
profile_extension: e.profile_extension,
|
||||
created_at: e.created_at,
|
||||
updated_at: e.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersListItemDto {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl From<&UsersDetailQueryDto> for UsersDetailItemDto {
|
||||
fn from(dto: &UsersDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.clone(),
|
||||
role: RolesDetailItemDto::from(&dto.role),
|
||||
fullname: dto.fullname.clone(),
|
||||
legal_name: dto.legal_name.clone(),
|
||||
email: dto.email.clone(),
|
||||
avatar: dto.avatar.clone(),
|
||||
is_active: dto.is_active,
|
||||
profile_extension: dto.profile_extension.clone(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<UserListItem> for UsersListItemDto {
|
||||
fn from(item: UserListItem) -> Self {
|
||||
Self {
|
||||
id: item.id,
|
||||
role: item.role,
|
||||
fullname: item.fullname,
|
||||
email: item.email,
|
||||
avatar: item.avatar,
|
||||
is_active: item.is_active,
|
||||
created_at: item.created_at,
|
||||
updated_at: item.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
use crate::require_permissions;
|
||||
use std::sync::Arc;
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Multipart},
|
||||
http::HeaderMap,
|
||||
response::IntoResponse,
|
||||
};
|
||||
use paginator_axum::PaginationQuery;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_libs::{AppState, MinioConfig, FileType, decode_base64_file, extract_content_type_from_data_url, create_minio_service_from_config};
|
||||
use imphnen_utils::{ApiSuccess, ApiCreated, ApiPaginated, ApiMessage};
|
||||
use imphnen_entities::{ResponseSuccessDto, ResponseListSuccessDto, PermissionsEnum, RolesDetailQueryDto};
|
||||
use imphnen_utils::AppError;
|
||||
use crate::users::domain::{UserEntity, UserService};
|
||||
use super::dto::{
|
||||
FileUploadSchema, UsersActiveInactiveRequestDto, UsersCreateRequestDto, UsersDetailItemDto,
|
||||
UsersListItemDto, UsersUpdateRequestDto,
|
||||
};
|
||||
use imphnen_libs::hash_password;
|
||||
use serde_json::json;
|
||||
use tracing::error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/users",
|
||||
security(("Bearer" = [])),
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user list", body = ResponseListSuccessDto<Vec<UsersListItemDto>>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
PaginationQuery(params): PaginationQuery,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::ReadListUsers], {
|
||||
let result = service.list(params).await?;
|
||||
let mapped = PaginatorResponse {
|
||||
data: result.data.into_iter().map(UsersListItemDto::from).collect::<Vec<_>>(),
|
||||
meta: result.meta,
|
||||
};
|
||||
Ok(ApiPaginated(mapped))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/users/detail/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::ReadDetailUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let user = service.get(id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".to_string()));
|
||||
}
|
||||
Ok(ApiSuccess(UsersDetailItemDto::from(user)))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/users/me",
|
||||
security(("Bearer" = [])),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Get current user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let (claims, _) = crate::permissions_guard(headers, axum::extract::Extension(state.clone()), vec![]).await?;
|
||||
let user = service.get_me(claims.user_id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".to_string()));
|
||||
}
|
||||
Ok(ApiSuccess(UsersDetailItemDto::from(user)))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/users/create",
|
||||
security(("Bearer" = [])),
|
||||
request_body = UsersCreateRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "[ADMIN] Create new user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn post_create_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Json(payload): Json<UsersCreateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::CreateUsers], {
|
||||
let password_hash = hash_password(&payload.password)
|
||||
.map_err(|_| AppError::InternalServerError("Failed to hash password".to_string()))?;
|
||||
let role_id = payload.role_id.clone();
|
||||
let entity = UserEntity {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
email: payload.email,
|
||||
fullname: payload.fullname,
|
||||
password: password_hash,
|
||||
is_active: payload.is_active,
|
||||
avatar: payload.avatar,
|
||||
role: RolesDetailQueryDto {
|
||||
id: role_id,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let user = service.create(entity).await?;
|
||||
Ok(ApiCreated(UsersDetailItemDto::from(user)))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/users/update/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Update user")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::UpdateUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let current = service.get(id.clone()).await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
|
||||
let password = if let Some(ref pw) = payload.password {
|
||||
hash_password(pw).unwrap_or_else(|_| current.password.clone())
|
||||
} else {
|
||||
current.password.clone()
|
||||
};
|
||||
|
||||
let role_id = payload.role_id.clone().unwrap_or(current.role.id.clone());
|
||||
let entity = UserEntity {
|
||||
id: id.clone(),
|
||||
email: payload.email.unwrap_or(current.email),
|
||||
fullname: payload.fullname.unwrap_or(current.fullname),
|
||||
legal_name: payload.legal_name.or(current.legal_name),
|
||||
password,
|
||||
avatar: payload.avatar.or(current.avatar),
|
||||
is_active: payload.is_active.unwrap_or(current.is_active),
|
||||
is_deleted: current.is_deleted,
|
||||
role: RolesDetailQueryDto { id: role_id, ..current.role },
|
||||
profile_extension: payload.profile_extension.or(current.profile_extension),
|
||||
created_at: current.created_at,
|
||||
updated_at: current.updated_at,
|
||||
mentor_id: current.mentor_id,
|
||||
};
|
||||
let msg = service.update(entity).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/users/update/me",
|
||||
security(("Bearer" = [])),
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[USER] Update current user")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let (claims, _) = crate::permissions_guard(headers, axum::extract::Extension(state.clone()), vec![]).await?;
|
||||
let user_id = claims.user_id.clone();
|
||||
|
||||
let current = service.get_me(user_id).await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
|
||||
let password = if let Some(ref pw) = payload.password {
|
||||
hash_password(pw).unwrap_or_else(|_| current.password.clone())
|
||||
} else {
|
||||
current.password.clone()
|
||||
};
|
||||
|
||||
let role_id = payload.role_id.clone().unwrap_or(current.role.id.clone());
|
||||
let entity = UserEntity {
|
||||
id: current.id.clone(),
|
||||
email: payload.email.unwrap_or(current.email),
|
||||
fullname: payload.fullname.unwrap_or(current.fullname),
|
||||
legal_name: payload.legal_name.or(current.legal_name),
|
||||
password,
|
||||
avatar: payload.avatar.or(current.avatar),
|
||||
is_active: payload.is_active.unwrap_or(current.is_active),
|
||||
is_deleted: current.is_deleted,
|
||||
role: RolesDetailQueryDto { id: role_id, ..current.role },
|
||||
profile_extension: payload.profile_extension.or(current.profile_extension),
|
||||
created_at: current.created_at,
|
||||
updated_at: current.updated_at,
|
||||
mentor_id: current.mentor_id,
|
||||
};
|
||||
let msg = service.update(entity).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/users/activate/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
request_body = UsersActiveInactiveRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Set user active status")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn patch_user_active_status(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersActiveInactiveRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::ActivateUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let msg = service.set_active_status(id, payload.is_active).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/v1/users/delete/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Soft delete user")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn delete_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::DeleteUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let msg = service.delete(id).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/users/upload",
|
||||
security(("Bearer" = [])),
|
||||
request_body(
|
||||
content = FileUploadSchema,
|
||||
description = "Upload file with multipart form data",
|
||||
content_type = "multipart/form-data"
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Upload file successfully", body = ResponseSuccessDto<serde_json::Value>),
|
||||
(status = 400, description = "[USER] Bad request"),
|
||||
(status = 401, description = "[USER] Unauthorized"),
|
||||
(status = 500, description = "[USER] Internal server error")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn upload_file(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let (claims, _) = crate::permissions_guard(headers, axum::extract::Extension(state.clone()), vec![]).await?;
|
||||
let user_id = claims.user_id.clone();
|
||||
|
||||
let minio_config = MinioConfig::from_env()
|
||||
.map_err(|e| {
|
||||
error!("Failed to load MinIO config: {}", e);
|
||||
AppError::InternalServerError("MinIO configuration error".to_string())
|
||||
})?;
|
||||
let bucket_name = minio_config.bucket_name.clone();
|
||||
let minio_service = create_minio_service_from_config(minio_config).await
|
||||
.map_err(|e| {
|
||||
error!("Failed to initialize MinIO service: {}", e);
|
||||
AppError::InternalServerError("MinIO service initialization error".to_string())
|
||||
})?;
|
||||
|
||||
let mut file_data: Option<Vec<u8>> = None;
|
||||
let mut filename: Option<String> = None;
|
||||
let mut content_type: Option<String> = None;
|
||||
|
||||
while let Some(field) = multipart.next_field().await.unwrap_or(None) {
|
||||
let name = field.name().unwrap_or("").to_string();
|
||||
match name.as_str() {
|
||||
"file" => {
|
||||
filename = field.file_name().map(|s| s.to_string());
|
||||
content_type = field.content_type().map(|s| s.to_string());
|
||||
match field.bytes().await {
|
||||
Ok(bytes) => file_data = Some(bytes.to_vec()),
|
||||
Err(e) => {
|
||||
error!("Failed to read file data: {}", e);
|
||||
return Err(AppError::BadRequestError("Failed to read file data".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
"base64_data" => {
|
||||
let base64_str = field.text().await.unwrap_or_default();
|
||||
if !base64_str.is_empty() {
|
||||
match decode_base64_file(&base64_str) {
|
||||
Ok(decoded) => {
|
||||
file_data = Some(decoded);
|
||||
if let Some(ct) = extract_content_type_from_data_url(&base64_str) {
|
||||
content_type = Some(ct);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to decode base64 data: {}", e);
|
||||
return Err(AppError::BadRequestError("Invalid base64 data".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"filename" => filename = Some(field.text().await.unwrap_or_default()),
|
||||
"content_type" => content_type = Some(field.text().await.unwrap_or_default()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let file_data = file_data
|
||||
.ok_or_else(|| AppError::BadRequestError("file data is required".to_string()))?;
|
||||
let filename = filename.unwrap_or_else(|| "unnamed_file".to_string());
|
||||
let content_type = content_type.unwrap_or_else(|| "application/octet-stream".to_string());
|
||||
|
||||
let file_type = {
|
||||
let ft = FileType::from_content_type(&content_type);
|
||||
if matches!(ft, FileType::Unknown) { FileType::from_filename(&filename) } else { ft }
|
||||
};
|
||||
if matches!(file_type, FileType::Unknown) {
|
||||
return Err(AppError::BadRequestError("Unsupported file type".to_string()));
|
||||
}
|
||||
if !file_type.allowed_types().contains(&content_type.as_str()) {
|
||||
return Err(AppError::BadRequestError(format!("File type does not match content type '{content_type}'")));
|
||||
}
|
||||
if file_data.len() > file_type.max_size() {
|
||||
return Err(AppError::BadRequestError(format!(
|
||||
"File too large. Maximum size for {:?} is {} bytes",
|
||||
file_type,
|
||||
file_type.max_size()
|
||||
)));
|
||||
}
|
||||
|
||||
let sanitized = user_id.replace('%', "").replace(':', "_").replace('@', "_at_").replace('.', "_");
|
||||
let folder = format!("{}/{sanitized}", file_type.as_folder());
|
||||
|
||||
let object_path = minio_service
|
||||
.upload_file_with_deduplication(&file_data, &content_type, &folder, &filename)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to upload file: {}", e);
|
||||
AppError::InternalServerError(format!("Upload failed: {e}"))
|
||||
})?;
|
||||
|
||||
let permanent_url = format!("https://cdn.asepharyana.tech/{}/{}", bucket_name, object_path);
|
||||
let response_data = json!({
|
||||
"filename": filename,
|
||||
"uploaded_path": object_path,
|
||||
"url": permanent_url,
|
||||
"size": file_data.len(),
|
||||
"content_type": content_type,
|
||||
"file_type": format!("{:?}", file_type).to_lowercase(),
|
||||
"user_id": user_id,
|
||||
});
|
||||
Ok(ApiSuccess(response_data))
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod dto;
|
||||
pub mod handlers;
|
||||
pub mod routes;
|
||||
|
||||
pub use routes::{users_public_routes, users_protected_routes};
|
||||
@@ -0,0 +1,37 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{Router, routing::{delete, get, post, put}, Extension};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use imphnen_libs::AppState;
|
||||
use crate::users::application::UserServiceImpl;
|
||||
use crate::users::domain::UserService;
|
||||
use crate::users::infrastructure::persistence::PostgresUserRepository;
|
||||
use super::handlers::{
|
||||
get_user_list, get_user_by_id, get_user_me, post_create_user,
|
||||
put_update_user, put_update_user_me, patch_user_active_status,
|
||||
delete_user, upload_file,
|
||||
};
|
||||
|
||||
fn build_service(db: DatabaseConnection) -> Arc<dyn UserService> {
|
||||
let repo = Arc::new(PostgresUserRepository::new(db));
|
||||
Arc::new(UserServiceImpl::new(repo))
|
||||
}
|
||||
|
||||
pub fn users_public_routes(_db: DatabaseConnection) -> Router {
|
||||
Router::new()
|
||||
}
|
||||
|
||||
pub fn users_protected_routes(db: DatabaseConnection, state: Arc<AppState>) -> Router {
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/users", get(get_user_list))
|
||||
.route("/users/detail/{id}", get(get_user_by_id))
|
||||
.route("/users/me", get(get_user_me))
|
||||
.route("/users/create", post(post_create_user))
|
||||
.route("/users/update/{id}", put(put_update_user))
|
||||
.route("/users/update/me", put(put_update_user_me))
|
||||
.route("/users/activate/{id}", put(patch_user_active_status))
|
||||
.route("/users/delete/{id}", delete(delete_user))
|
||||
.route("/users/upload", post(upload_file))
|
||||
.layer(Extension(service))
|
||||
.layer(Extension((*state).clone()))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod http;
|
||||
pub mod persistence;
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod postgres_user_repository;
|
||||
pub use postgres_user_repository::PostgresUserRepository;
|
||||
@@ -0,0 +1,306 @@
|
||||
#![allow(clippy::field_reassign_with_default)]
|
||||
use std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use sea_orm::prelude::*;
|
||||
use sea_orm::{ActiveValue, Order, QueryOrder, PaginatorTrait};
|
||||
use paginator_rs::{PaginationParams, SortDirection};
|
||||
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
|
||||
use uuid::Uuid;
|
||||
use chrono::Utc;
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_entities::{
|
||||
UsersDetailQueryDto, RolesDetailQueryDto, PermissionsQueryDto,
|
||||
seaorm::auth::users::{Entity as UsersEntity, ActiveModel as UserActiveModel, Column as UserColumn},
|
||||
seaorm::auth::roles::Entity as RolesEntity,
|
||||
};
|
||||
use crate::users::domain::{UserEntity, UserListItem, UserRepository};
|
||||
|
||||
fn user_detail_to_entity(dto: UsersDetailQueryDto) -> UserEntity {
|
||||
UserEntity {
|
||||
id: dto.id,
|
||||
email: dto.email,
|
||||
fullname: dto.fullname,
|
||||
legal_name: dto.legal_name,
|
||||
password: dto.password,
|
||||
avatar: dto.avatar,
|
||||
is_active: dto.is_active,
|
||||
is_deleted: dto.is_deleted,
|
||||
role: dto.role,
|
||||
profile_extension: dto.profile_extension,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
mentor_id: dto.mentor_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_role_dto(role: Option<imphnen_entities::seaorm::auth::roles::Model>) -> RolesDetailQueryDto {
|
||||
role.map_or_else(RolesDetailQueryDto::default, |r| RolesDetailQueryDto {
|
||||
id: r.id.to_string(),
|
||||
name: r.name,
|
||||
permissions: r.permissions.clone().and_then(|json| {
|
||||
serde_json::from_value::<Vec<String>>(json).ok().map(|list| {
|
||||
list.into_iter().map(|p| Some(PermissionsQueryDto {
|
||||
id: Some(p.clone()),
|
||||
name: Some(p),
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
})).collect()
|
||||
})
|
||||
}),
|
||||
is_deleted: r.deleted_at.is_some(),
|
||||
created_at: Some(r.created_at.to_rfc3339()),
|
||||
updated_at: Some(r.updated_at.to_rfc3339()),
|
||||
})
|
||||
}
|
||||
|
||||
pub struct PostgresUserRepository {
|
||||
db: Arc<DatabaseConnection>,
|
||||
}
|
||||
|
||||
impl PostgresUserRepository {
|
||||
pub fn new(db: DatabaseConnection) -> Self {
|
||||
Self { db: Arc::new(db) }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UserRepository for PostgresUserRepository {
|
||||
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<UserListItem>, AppError> {
|
||||
let page = params.page.max(1);
|
||||
let per_page = params.per_page.clamp(1, 100);
|
||||
|
||||
let mut query = UsersEntity::find()
|
||||
.filter(UserColumn::DeletedAt.is_null())
|
||||
.filter(UserColumn::IsActive.eq(true));
|
||||
|
||||
if let Some(ref search) = params.search {
|
||||
query = query.filter(
|
||||
UserColumn::Email.contains(&search.query)
|
||||
.or(UserColumn::FirstName.contains(&search.query))
|
||||
.or(UserColumn::LastName.contains(&search.query))
|
||||
);
|
||||
}
|
||||
|
||||
let order = match params.sort_direction {
|
||||
Some(SortDirection::Desc) => Order::Desc,
|
||||
_ => Order::Asc,
|
||||
};
|
||||
query = match params.sort_by.as_deref() {
|
||||
Some("email") => query.order_by(UserColumn::Email, order),
|
||||
_ => query.order_by(UserColumn::CreatedAt, order),
|
||||
};
|
||||
|
||||
let paginator = query.paginate(self.db.as_ref(), per_page as u64);
|
||||
let users = paginator.fetch_page((page - 1) as u64).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
let role_ids: Vec<Uuid> = users.iter().filter_map(|u| u.role_id).collect();
|
||||
let roles = if !role_ids.is_empty() {
|
||||
RolesEntity::find()
|
||||
.filter(imphnen_entities::seaorm::auth::roles::Column::Id.is_in(role_ids))
|
||||
.all(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.into_iter()
|
||||
.map(|r| (r.id, r.name))
|
||||
.collect::<std::collections::HashMap<_, _>>()
|
||||
} else {
|
||||
std::collections::HashMap::new()
|
||||
};
|
||||
|
||||
let data: Vec<UserListItem> = users.into_iter().map(|user| {
|
||||
let role_name = user.role_id.and_then(|rid| roles.get(&rid).cloned()).unwrap_or_default();
|
||||
UserListItem {
|
||||
id: user.id.to_string(),
|
||||
role: role_name,
|
||||
fullname: format!("{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
).trim().to_string(),
|
||||
email: user.email,
|
||||
avatar: user.avatar_url,
|
||||
is_active: user.is_active,
|
||||
created_at: user.created_at.to_rfc3339(),
|
||||
updated_at: user.updated_at.to_rfc3339(),
|
||||
}
|
||||
}).collect();
|
||||
|
||||
let total = paginator.num_items().await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
let meta = PaginatorResponseMeta::new(page, per_page, total as u32);
|
||||
Ok(PaginatorResponse { data, meta })
|
||||
}
|
||||
|
||||
async fn find_by_id(&self, id: &str) -> Result<UserEntity, AppError> {
|
||||
let user_id = Uuid::parse_str(id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid user ID".into()))?;
|
||||
|
||||
let (user, role) = UsersEntity::find_by_id(user_id)
|
||||
.filter(UserColumn::DeletedAt.is_null())
|
||||
.find_also_related(RolesEntity)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("User not found in database".into()))?;
|
||||
|
||||
let role_dto = build_role_dto(role);
|
||||
|
||||
let mut dto = UsersDetailQueryDto::default();
|
||||
dto.id = user.id.to_string();
|
||||
dto.fullname = format!("{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
).trim().to_string();
|
||||
dto.legal_name = None;
|
||||
dto.email = user.email;
|
||||
dto.avatar = user.avatar_url;
|
||||
dto.is_active = user.is_active;
|
||||
dto.is_deleted = user.deleted_at.is_some();
|
||||
dto.profile_extension = user.metadata.and_then(|m| serde_json::from_value(m).ok());
|
||||
dto.password = user.password_hash;
|
||||
dto.role = role_dto;
|
||||
dto.created_at = user.created_at.to_rfc3339();
|
||||
dto.updated_at = user.updated_at.to_rfc3339();
|
||||
dto.mentor_id = None;
|
||||
|
||||
Ok(user_detail_to_entity(dto.from_profile_extension()))
|
||||
}
|
||||
|
||||
async fn find_by_email(&self, email: String) -> Result<UserEntity, AppError> {
|
||||
let (user, role) = UsersEntity::find()
|
||||
.filter(UserColumn::Email.eq(&email))
|
||||
.filter(UserColumn::DeletedAt.is_null())
|
||||
.find_also_related(RolesEntity)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("User not found".into()))?;
|
||||
|
||||
let role_dto = build_role_dto(role);
|
||||
|
||||
let mut dto = UsersDetailQueryDto::default();
|
||||
dto.id = user.id.to_string();
|
||||
dto.fullname = format!("{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
).trim().to_string();
|
||||
dto.legal_name = None;
|
||||
dto.email = user.email;
|
||||
dto.avatar = user.avatar_url;
|
||||
dto.is_active = user.is_active;
|
||||
dto.is_deleted = user.deleted_at.is_some();
|
||||
dto.profile_extension = user.metadata.and_then(|m| serde_json::from_value(m).ok());
|
||||
dto.password = user.password_hash;
|
||||
dto.role = role_dto;
|
||||
dto.created_at = user.created_at.to_rfc3339();
|
||||
dto.updated_at = user.updated_at.to_rfc3339();
|
||||
dto.mentor_id = None;
|
||||
|
||||
Ok(user_detail_to_entity(dto.from_profile_extension()))
|
||||
}
|
||||
|
||||
async fn create(&self, entity: UserEntity) -> Result<String, AppError> {
|
||||
// Check for existing user
|
||||
let existing = UsersEntity::find()
|
||||
.filter(UserColumn::Email.eq(entity.email.clone()))
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
if existing.is_some() {
|
||||
return Err(AppError::ConflictError("User with this email already exists".into()));
|
||||
}
|
||||
|
||||
let full_name = entity.fullname.clone();
|
||||
let (first_name, last_name) = full_name.split_once(' ').unwrap_or((&full_name, ""));
|
||||
|
||||
let role_id = entity.role.id.parse::<Uuid>().ok()
|
||||
.or_else(|| entity.role.id.is_empty().then_some(Uuid::nil()));
|
||||
|
||||
let active_model = UserActiveModel {
|
||||
id: ActiveValue::Set(Uuid::new_v4()),
|
||||
email: ActiveValue::Set(entity.email.clone()),
|
||||
password_hash: ActiveValue::Set(entity.password),
|
||||
username: ActiveValue::Set(entity.email.clone()),
|
||||
first_name: ActiveValue::Set(Some(first_name.to_string())),
|
||||
last_name: ActiveValue::Set(Some(last_name.to_string())),
|
||||
avatar_url: ActiveValue::Set(entity.avatar),
|
||||
is_verified: ActiveValue::Set(false),
|
||||
is_active: ActiveValue::Set(entity.is_active),
|
||||
metadata: ActiveValue::Set(
|
||||
entity.profile_extension.map(|p| serde_json::to_value(p).unwrap_or_default())
|
||||
),
|
||||
created_at: ActiveValue::Set(Utc::now()),
|
||||
updated_at: ActiveValue::Set(Utc::now()),
|
||||
deleted_at: ActiveValue::Set(None),
|
||||
role_id: ActiveValue::Set(role_id.filter(|id| !id.is_nil())),
|
||||
};
|
||||
|
||||
UsersEntity::insert(active_model).exec(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok("Successfully created user".into())
|
||||
}
|
||||
|
||||
async fn update(&self, entity: UserEntity) -> Result<String, AppError> {
|
||||
let user_id = Uuid::parse_str(&entity.id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid user ID".into()))?;
|
||||
|
||||
let mut active_model: UserActiveModel = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("User not found".into()))?
|
||||
.into();
|
||||
|
||||
let full_name = entity.fullname.clone();
|
||||
let (first_name, last_name) = full_name.split_once(' ').unwrap_or((&full_name, ""));
|
||||
|
||||
active_model.email = ActiveValue::Set(entity.email);
|
||||
active_model.first_name = ActiveValue::Set(Some(first_name.to_string()));
|
||||
active_model.last_name = ActiveValue::Set(Some(last_name.to_string()));
|
||||
active_model.avatar_url = ActiveValue::Set(entity.avatar);
|
||||
active_model.is_active = ActiveValue::Set(entity.is_active);
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
if !entity.password.is_empty() {
|
||||
active_model.password_hash = ActiveValue::Set(entity.password);
|
||||
}
|
||||
|
||||
let role_id = entity.role.id.parse::<Uuid>().ok();
|
||||
if role_id.is_some() {
|
||||
active_model.role_id = ActiveValue::Set(role_id);
|
||||
}
|
||||
|
||||
if entity.profile_extension.is_some() {
|
||||
active_model.metadata = ActiveValue::Set(
|
||||
entity.profile_extension.map(|p| serde_json::to_value(p).unwrap_or_default())
|
||||
);
|
||||
}
|
||||
|
||||
active_model.update(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok("Success update user".into())
|
||||
}
|
||||
|
||||
async fn delete(&self, id: String) -> Result<String, AppError> {
|
||||
let user_id = Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid user ID".into()))?;
|
||||
|
||||
let mut active_model: UserActiveModel = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db.as_ref())
|
||||
.await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?
|
||||
.ok_or_else(|| AppError::NotFoundError("User not found".into()))?
|
||||
.into();
|
||||
|
||||
active_model.deleted_at = ActiveValue::Set(Some(Utc::now()));
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model.update(self.db.as_ref()).await
|
||||
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
|
||||
|
||||
Ok("Success delete user".into())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod domain;
|
||||
pub mod application;
|
||||
pub mod infrastructure;
|
||||
|
||||
pub use infrastructure::http::routes::{users_public_routes, users_protected_routes};
|
||||
Reference in New Issue
Block a user