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:
maulanasdqn
2026-04-02 13:39:52 +07:00
co-authored by Claude Sonnet 4.6
parent 1b3366d735
commit e432a1a743
379 changed files with 9013 additions and 30532 deletions
+47 -41
View File
@@ -1,41 +1,47 @@
[package]
name = "imphnen-iam"
version = "0.1.0"
edition = "2024"
[dependencies]
imphnen-libs.workspace = true
imphnen-utils.workspace = true
imphnen-entities.workspace = true
async-trait.workspace = true
axum.workspace = true
serde.workspace = true
serde_json = { workspace = true }
oauth2 = { workspace = true }
reqwest = { workspace = true, features = ["json"] }
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
validator.workspace = true
axum-test.workspace = true
sea-orm.workspace = true
rand.workspace = true
tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
strum.workspace = true
strum_macros.workspace = true
log.workspace = true
once_cell.workspace = true
tracing.workspace = true
uuid.workspace = true
axum-extra.workspace = true
[dev-dependencies]
dotenvy.workspace = true
tokio-test = { workspace = true }
mockall = { workspace = true }
http-body-util.workspace = true
[package]
name = "imphnen-iam"
version = "0.2.0"
edition = "2024"
[dependencies]
imphnen-libs.workspace = true
imphnen-utils.workspace = true
imphnen-entities.workspace = true
async-trait.workspace = true
axum.workspace = true
serde.workspace = true
serde_json = { workspace = true }
oauth2 = { workspace = true }
reqwest = { workspace = true, features = ["json"] }
utoipa.workspace = true
lazy_static.workspace = true
regex.workspace = true
zod-rs.workspace = true
zod-rs-util.workspace = true
axum-test.workspace = true
sea-orm.workspace = true
rand.workspace = true
tokio.workspace = true
chrono.workspace = true
anyhow.workspace = true
tower-http.workspace = true
utoipa-swagger-ui.workspace = true
strum.workspace = true
strum_macros.workspace = true
log.workspace = true
once_cell.workspace = true
tracing.workspace = true
uuid.workspace = true
axum-extra.workspace = true
paginator-rs.workspace = true
paginator-utils.workspace = true
paginator-sea-orm.workspace = true
paginator-axum.workspace = true
[dev-dependencies]
dotenvy.workspace = true
tokio-test = { workspace = true }
mockall = { workspace = true }
http-body-util.workspace = true
+167
View File
@@ -0,0 +1,167 @@
use std::sync::Arc;
use async_trait::async_trait;
use tracing::error;
use uuid::Uuid;
use imphnen_libs::{environment, encode_access_token, encode_refresh_token, encode_reset_password_token,
decode_access_token, decode_refresh_token, hash_password, send_email, verify_password};
use imphnen_utils::{AppError, get_iso_date};
use imphnen_utils::generate_otp::OtpManager;
use imphnen_entities::{RolesDetailQueryDto, users::UserProfileExtensionDto};
use crate::auth::domain::AuthService;
use crate::auth::infrastructure::http::dto::{
AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto,
AuthRefreshTokenRequestDto, AuthRegisterRequestDto, AuthResendOtpRequestDto,
AuthVerifyEmailRequestDto, TokenDto,
};
use crate::users::domain::{UserEntity, UserRepository};
use crate::users::infrastructure::http::dto::UsersDetailItemDto;
use crate::roles::domain::RoleRepository;
pub struct AuthServiceImpl {
user_repo: Arc<dyn UserRepository>,
role_repo: Arc<dyn RoleRepository>,
}
impl AuthServiceImpl {
pub fn new(user_repo: Arc<dyn UserRepository>, role_repo: Arc<dyn RoleRepository>) -> Self {
Self { user_repo, role_repo }
}
}
#[async_trait]
impl AuthService for AuthServiceImpl {
async fn login(&self, payload: AuthLoginRequestDto) -> Result<AuthLoginResponsetDto, AppError> {
let user = self.user_repo.find_by_email(payload.email.clone()).await
.map_err(|_| AppError::AuthenticationError("Email or password not correct".into()))?;
if !user.is_active {
return Err(AppError::AuthenticationError("Account not active, please verify your email".into()));
}
let valid = verify_password(&payload.password, &user.password)
.map_err(|_| AppError::InternalServerError("Password verification failed".into()))?;
if !valid {
return Err(AppError::AuthenticationError("Email or password not correct".into()));
}
let access_token = encode_access_token(payload.email.clone(), user.id.clone())
.map_err(|_| AppError::InternalServerError("Failed to generate access token".into()))?;
let refresh_token = encode_refresh_token(payload.email.clone(), user.id.clone())
.map_err(|_| AppError::InternalServerError("Failed to generate refresh token".into()))?;
Ok(AuthLoginResponsetDto {
user: UsersDetailItemDto::from(user),
token: TokenDto { access_token, refresh_token },
})
}
async fn login_mentor(&self, payload: AuthLoginRequestDto) -> Result<AuthLoginResponsetDto, AppError> {
let user = self.user_repo.find_by_email(payload.email.clone()).await
.map_err(|_| AppError::AuthenticationError("Email or password not correct".into()))?;
if !user.is_active {
return Err(AppError::AuthenticationError("Account not active, please verify your email".into()));
}
let valid = verify_password(&payload.password, &user.password)
.map_err(|_| AppError::InternalServerError("Password verification failed".into()))?;
if !valid {
return Err(AppError::AuthenticationError("Email or password not correct".into()));
}
if user.role.name != "Mentor" {
return Err(AppError::ForbiddenError("User does not have mentor privileges".into()));
}
let access_token = encode_access_token(payload.email.clone(), user.id.clone())
.map_err(|_| AppError::InternalServerError("Failed to generate access token".into()))?;
let refresh_token = encode_refresh_token(payload.email.clone(), user.id.clone())
.map_err(|_| AppError::InternalServerError("Failed to generate refresh token".into()))?;
Ok(AuthLoginResponsetDto {
user: UsersDetailItemDto::from(user),
token: TokenDto { access_token, refresh_token },
})
}
async fn register(&self, payload: AuthRegisterRequestDto) -> Result<(), AppError> {
let role = self.role_repo.find_by_name("User".into()).await
.map_err(|_| AppError::NotFoundError("Role not found".into()))?;
if self.user_repo.find_by_email(payload.email.clone()).await.is_ok() {
return Err(AppError::BadRequestError("User already exists".into()));
}
let hashed = hash_password(&payload.password)
.map_err(|e| { error!("Failed to hash password: {}", e); AppError::InternalServerError("Failed to hash password".into()) })?;
let otp = OtpManager::generate_otp();
send_email(&payload.email, "OTP Verification", &format!("your otp code is {}", otp.code))
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
self.user_repo.create(UserEntity {
id: Uuid::new_v4().to_string(),
email: payload.email.clone(),
fullname: payload.fullname.clone(),
password: hashed,
is_active: false,
is_deleted: false,
role: RolesDetailQueryDto { id: role.id.to_string(), name: role.name, ..Default::default() },
profile_extension: Some(UserProfileExtensionDto { phone_number: payload.phone_number, ..Default::default() }),
created_at: get_iso_date(),
updated_at: get_iso_date(),
..Default::default()
}).await?;
Ok(())
}
async fn resend_otp(&self, payload: AuthResendOtpRequestDto) -> Result<(), AppError> {
self.user_repo.find_by_email(payload.email.clone()).await
.map_err(|_| AppError::NotFoundError("User not found".into()))?;
let otp = OtpManager::generate_otp();
send_email(&payload.email, "OTP Verification", &format!("Your OTP code is {}", otp.code))
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
Ok(())
}
async fn refresh_token(&self, payload: AuthRefreshTokenRequestDto) -> Result<TokenDto, AppError> {
let email = decode_refresh_token(&payload.refresh_token)
.map_err(|_| AppError::AuthenticationError("Invalid refresh token".into()))?.claims.sub;
let user = self.user_repo.find_by_email(email.clone()).await
.map_err(|_| AppError::AuthenticationError("User not found".into()))?;
let access_token = encode_access_token(user.email.clone(), user.id.clone())
.map_err(|_| AppError::InternalServerError("Failed to generate access token".into()))?;
let refresh_token = encode_refresh_token(user.email.clone(), user.id.clone())
.map_err(|_| AppError::InternalServerError("Failed to generate refresh token".into()))?;
Ok(TokenDto { access_token, refresh_token })
}
async fn forgot_password(&self, payload: AuthResendOtpRequestDto) -> Result<(), AppError> {
let user_repo = Arc::clone(&self.user_repo);
tokio::spawn(async move {
if let Ok(user) = user_repo.find_by_email(payload.email.clone()).await {
match encode_reset_password_token(user.email.clone(), user.id.clone()) {
Ok(token) => {
let fe_url = environment::ENV.fe_url.clone();
let msg = format!(
"You have requested a password reset. Please click the link below: {fe_url}/auth/reset-password?token={token}"
);
if let Err(e) = send_email(&payload.email, "Reset Password Request", &msg) {
error!("Failed to send reset password email: {}", e);
}
}
Err(e) => error!("Failed to generate reset token: {:?}", e),
}
}
});
Ok(())
}
async fn verify_email(&self, payload: AuthVerifyEmailRequestDto) -> Result<(), AppError> {
let user = self.user_repo.find_by_email(payload.email.clone()).await
.map_err(|_| AppError::NotFoundError("User not found".into()))?;
if user.is_active {
return Err(AppError::BadRequestError("User already active".into()));
}
self.user_repo.update(UserEntity { is_active: true, ..user }).await?;
Ok(())
}
async fn new_password(&self, payload: AuthNewPasswordRequestDto) -> Result<(), AppError> {
let email = decode_access_token(&payload.token)
.map_err(|_| AppError::BadRequestError("Invalid or missing token".into()))?.claims.sub;
let user = self.user_repo.find_by_email(email).await
.map_err(|e| AppError::BadRequestError(e.to_string()))?;
let hashed = hash_password(&payload.password)
.map_err(|e| { error!("Failed to hash new password: {}", e); AppError::InternalServerError("Failed to hash password".into()) })?;
self.user_repo.update(UserEntity { password: hashed, ..user }).await?;
Ok(())
}
}
+19
View File
@@ -0,0 +1,19 @@
use async_trait::async_trait;
use imphnen_utils::AppError;
use crate::auth::infrastructure::http::dto::{
AuthLoginRequestDto, AuthLoginResponsetDto, AuthRegisterRequestDto,
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto, AuthNewPasswordRequestDto,
AuthRefreshTokenRequestDto, TokenDto,
};
#[async_trait]
pub trait AuthService: Send + Sync {
async fn login(&self, payload: AuthLoginRequestDto) -> Result<AuthLoginResponsetDto, AppError>;
async fn login_mentor(&self, payload: AuthLoginRequestDto) -> Result<AuthLoginResponsetDto, AppError>;
async fn register(&self, payload: AuthRegisterRequestDto) -> Result<(), AppError>;
async fn resend_otp(&self, payload: AuthResendOtpRequestDto) -> Result<(), AppError>;
async fn refresh_token(&self, payload: AuthRefreshTokenRequestDto) -> Result<TokenDto, AppError>;
async fn forgot_password(&self, payload: AuthResendOtpRequestDto) -> Result<(), AppError>;
async fn verify_email(&self, payload: AuthVerifyEmailRequestDto) -> Result<(), AppError>;
async fn new_password(&self, payload: AuthNewPasswordRequestDto) -> Result<(), AppError>;
}
@@ -0,0 +1,100 @@
use crate::users::infrastructure::http::dto::UsersDetailItemDto;
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use zod_rs::prelude::*;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
pub struct AuthLoginRequestDto {
#[zod(email, min_length(1))]
pub email: String,
#[zod(min_length(1))]
pub password: String,
}
impl ZodValidate for AuthLoginRequestDto {
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, Default)]
pub struct TokenDto {
pub access_token: String,
pub refresh_token: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthLoginResponsetDto {
pub token: TokenDto,
pub user: UsersDetailItemDto,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
pub struct AuthRegisterRequestDto {
#[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,
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<String>,
}
impl ZodValidate for AuthRegisterRequestDto {
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, ZodSchema)]
pub struct AuthVerifyEmailRequestDto {
#[zod(email, min_length(1))]
pub email: String,
pub otp: u32,
}
impl ZodValidate for AuthVerifyEmailRequestDto {
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, ZodSchema)]
pub struct AuthResendOtpRequestDto {
#[zod(email, min_length(1))]
pub email: String,
}
impl ZodValidate for AuthResendOtpRequestDto {
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, ZodSchema)]
pub struct AuthRefreshTokenRequestDto {
#[zod(min_length(1))]
pub refresh_token: String,
}
impl ZodValidate for AuthRefreshTokenRequestDto {
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, ZodSchema)]
pub struct AuthNewPasswordRequestDto {
#[zod(min_length(1))]
pub token: String,
#[zod(min_length(8), regex(pattern = "^[A-Za-z\\d@$!%*?&]{8,}$"))]
pub password: String,
}
impl ZodValidate for AuthNewPasswordRequestDto {
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
Self::validate_and_parse(value).map_err(|e| e.to_string())
}
}
@@ -0,0 +1,156 @@
use std::sync::Arc;
use axum::{Extension, response::IntoResponse};
use imphnen_libs::ValidatedJson;
use imphnen_utils::{ApiSuccess, ApiMessage, AppError};
use super::dto::{
AuthLoginRequestDto, AuthRegisterRequestDto, AuthResendOtpRequestDto,
AuthVerifyEmailRequestDto, AuthNewPasswordRequestDto, AuthRefreshTokenRequestDto,
};
use crate::auth::domain::AuthService;
#[utoipa::path(
post,
path = "/v1/auth/login",
request_body = AuthLoginRequestDto,
responses(
(status = 200, description = "[PUBLIC] Login successful"),
(status = 401, description = "[PUBLIC] Login failed")
),
tag = "Authentication"
)]
pub async fn post_login(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthLoginRequestDto>,
) -> Result<impl IntoResponse, AppError> {
let resp = service.login(payload).await?;
Ok(ApiSuccess(resp))
}
#[utoipa::path(
post,
path = "/v1/auth/login-mentor",
request_body = AuthLoginRequestDto,
responses(
(status = 200, description = "[PUBLIC] Mentor login successful"),
(status = 401, description = "[PUBLIC] Mentor login failed"),
(status = 403, description = "[PUBLIC] Forbidden - Not a mentor")
),
tag = "Authentication"
)]
pub async fn post_login_mentor(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthLoginRequestDto>,
) -> Result<impl IntoResponse, AppError> {
let resp = service.login_mentor(payload).await?;
Ok(ApiSuccess(resp))
}
#[utoipa::path(
post,
path = "/v1/auth/register",
request_body = AuthRegisterRequestDto,
responses(
(status = 201, description = "[PUBLIC] Register successful"),
(status = 400, description = "[PUBLIC] Register failed")
),
tag = "Authentication"
)]
pub async fn post_register(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthRegisterRequestDto>,
) -> Result<impl IntoResponse, AppError> {
service.register(payload).await?;
Ok(ApiMessage::created("Registration successful"))
}
#[utoipa::path(
post,
path = "/v1/auth/verify-email",
request_body = AuthVerifyEmailRequestDto,
responses(
(status = 200, description = "[PUBLIC] Verify email successful"),
(status = 400, description = "[PUBLIC] Verify email failed")
),
tag = "Authentication"
)]
pub async fn post_verify_email(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthVerifyEmailRequestDto>,
) -> Result<impl IntoResponse, AppError> {
service.verify_email(payload).await?;
Ok(ApiMessage::ok("Email verified successfully"))
}
#[utoipa::path(
post,
path = "/v1/auth/send-otp",
request_body = AuthResendOtpRequestDto,
responses(
(status = 200, description = "[PUBLIC] Resend OTP successful"),
(status = 400, description = "[PUBLIC] Resend OTP failed")
),
tag = "Authentication"
)]
pub async fn post_resend_otp(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthResendOtpRequestDto>,
) -> Result<impl IntoResponse, AppError> {
service.resend_otp(payload).await?;
Ok(ApiMessage::ok("OTP sent"))
}
#[utoipa::path(
post,
path = "/v1/auth/forgot",
request_body = AuthResendOtpRequestDto,
responses(
(status = 200, description = "[PUBLIC] Forgot password request successful")
),
tag = "Authentication"
)]
pub async fn post_forgot_password(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthResendOtpRequestDto>,
) -> Result<impl IntoResponse, AppError> {
service.forgot_password(payload).await?;
Ok(ApiMessage::ok(
"If your email is registered, you will receive a password reset link.",
))
}
#[utoipa::path(
post,
path = "/v1/auth/new-password",
request_body = AuthNewPasswordRequestDto,
responses(
(status = 200, description = "[PUBLIC] New password set successfully"),
(status = 400, description = "[PUBLIC] New password request failed")
),
tag = "Authentication"
)]
pub async fn post_new_password(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthNewPasswordRequestDto>,
) -> Result<impl IntoResponse, AppError> {
service.new_password(payload).await?;
Ok(ApiMessage::ok("Password updated successfully"))
}
#[utoipa::path(
post,
path = "/v1/auth/refresh",
request_body = AuthRefreshTokenRequestDto,
responses(
(status = 200, description = "[PUBLIC] Refresh token successful"),
(status = 401, description = "[PUBLIC] Invalid refresh token")
),
tag = "Authentication"
)]
pub async fn post_refresh_token(
Extension(service): Extension<Arc<dyn AuthService>>,
ValidatedJson(payload): ValidatedJson<AuthRefreshTokenRequestDto>,
) -> Result<impl IntoResponse, AppError> {
let resp = service.refresh_token(payload).await?;
Ok(ApiSuccess(resp))
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::auth_public_routes;
@@ -0,0 +1,29 @@
use std::sync::Arc;
use axum::{Router, routing::post, Extension};
use sea_orm::DatabaseConnection;
use imphnen_libs::AppState;
use crate::auth::domain::AuthService;
use crate::auth::application::AuthServiceImpl;
use crate::users::infrastructure::persistence::PostgresUserRepository;
use crate::roles::infrastructure::persistence::PostgresRoleRepository;
use super::handlers::{
post_login, post_login_mentor, post_register, post_verify_email,
post_resend_otp, post_forgot_password, post_new_password, post_refresh_token,
};
pub fn auth_public_routes(_db: DatabaseConnection, state: Arc<AppState>) -> Router {
let user_repo = Arc::new(PostgresUserRepository::new(state.postgres_connection.conn.clone()));
let role_repo = Arc::new(PostgresRoleRepository::new(state.postgres_connection.conn.clone()));
let auth_service: Arc<dyn AuthService> = Arc::new(AuthServiceImpl::new(user_repo, role_repo));
Router::new()
.route("/auth/login", post(post_login))
.route("/auth/login-mentor", post(post_login_mentor))
.route("/auth/register", post(post_register))
.route("/auth/verify-email", post(post_verify_email))
.route("/auth/send-otp", post(post_resend_otp))
.route("/auth/forgot", post(post_forgot_password))
.route("/auth/new-password", post(post_new_password))
.route("/auth/refresh", post(post_refresh_token))
.layer(Extension(auth_service))
.layer(Extension((*state).clone()))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1 @@
// Auth persistence - uses v1 AuthRepository directly
+7
View File
@@ -0,0 +1,7 @@
pub mod domain;
pub mod application;
pub mod infrastructure;
pub use domain::AuthService;
pub use application::AuthServiceImpl;
pub use infrastructure::http::routes::auth_public_routes;
+19 -41
View File
@@ -1,22 +1,24 @@
pub mod v1;
pub mod permission_macros;
pub mod permissions_guard;
pub mod permissions;
pub mod roles;
pub mod users;
pub mod auth;
pub use permissions::{permissions_public_routes, permissions_protected_routes};
pub use roles::{roles_public_routes, roles_protected_routes};
pub use users::{users_public_routes, users_protected_routes};
pub use auth::auth_public_routes;
// Re-export core entity types used throughout the IAM module
pub use imphnen_entities::{
MessageResponseDto,
MetaRequestDto,
MetaResponseDto,
ResponseSuccessDto,
ResponseListSuccessDto,
CountResult,
Error,
ExperienceDto,
EducationDto,
UsersDetailQueryDto,
PermissionsEnum,
PermissionsItemDto,
PermissionsQueryDto,
ResourceEnum, // Import ResourceEnum from imphnen_entities
};
// Explicitly export only the imphnen_libs types actually used in IAM
@@ -36,47 +38,23 @@ pub use imphnen_libs::{
jsonwebtoken::Claims,
};
// Explicitly export only the imphnen_utils types actually used in IAM
pub use imphnen_utils::{
response_format::success_response,
response_format::success_list_response,
response_format::common_response,
validator::validate_request,
response_format::ApiSuccess,
response_format::ApiCreated,
response_format::ApiPaginated,
response_format::ApiMessage,
csrf_token::generate_oauth_csrf_token,
csrf_token::validate_oauth_csrf_token,
csrf_token::validate_csrf_token,
extract_email::extract_email_async,
generate_otp::OtpManager,
errors::AppError,
response_format::error_response,
response_format::success_created_response,
generate_date::get_iso_date,
};
pub use paginator_axum::PaginationQuery;
pub use paginator_rs::PaginationParams;
pub use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
pub use imphnen_libs::AppStatePostgresExt;
// Export the main router functions and types from v1 module
pub use v1::{
iam_public_routes,
iam_protected_routes,
auth_router,
users_router,
roles_router,
permissions_router,
permissions_guard,
};
pub use permissions_guard::permissions_guard;
// Export permission macros (module not yet implemented)
// pub use permission_macros::*;
// Export IAM-specific types
pub use v1::auth::{
AuthOtpSchema,
AuthRepository,
AuthLoginRequestDto, AuthLoginResponsetDto, AuthRegisterRequestDto,
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
AuthNewPasswordRequestDto, AuthRefreshTokenRequestDto,
TokenDto,
};
pub use v1::permissions::{PermissionsRepository, PermissionsSchema};
pub use v1::roles::{RolesRepository, RolesSchema, RolesEnum, RolesDetailQueryDto, RolesRequestCreateDto, RolesRequestUpdateDto, RolesDetailItemDto};
pub use v1::users::{UsersRepository, UsersSchema, UsersDetailItemDto, UsersCreateRequestDto};
+53 -101
View File
@@ -1,101 +1,53 @@
//! Permission guard utilities and macros to reduce boilerplate
//!
//! This module provides utilities to simplify permission checking in handlers
use axum::{
extract::Extension,
http::HeaderMap,
response::Response,
};
use imphnen_entities::PermissionsEnum;
use crate::AppState;
use crate::permissions_guard;
use imphnen_libs::jsonwebtoken::Claims;
/// Result type for permission-guarded handlers
pub type PermissionGuardResult<T> = Result<(T, AppState), Response>;
/// Helper function to extract user and check permissions
///
/// This is a cleaner wrapper around the existing permissions_guard
pub async fn check_permissions(
headers: HeaderMap,
state: Extension<AppState>,
required_permissions: Vec<PermissionsEnum>,
) -> PermissionGuardResult<Claims> {
match permissions_guard(headers, state, required_permissions).await {
Ok((user, state)) => Ok((user, state)),
Err(response) => Err(response),
}
}
/// Helper function for endpoints that don't require specific permissions
/// but still need authentication
pub async fn check_authenticated(
headers: HeaderMap,
state: Extension<AppState>,
) -> PermissionGuardResult<Claims> {
check_permissions(headers, state, vec![]).await
}
/// Macro to reduce boilerplate in permission-guarded handlers
///
/// # Example
/// ```rust
/// use imphnen_iam::require_permissions;
/// use imphnen_entities::PermissionsEnum;
/// use axum::{extract::Query, http::HeaderMap, response::Response, Extension};
/// use imphnen_iam::AppState;
/// use imphnen_entities::MetaRequestDto;
/// use imphnen_iam::v1::users::users_service::{UsersService, UsersServiceTrait};
///
/// pub async fn get_user_list(
/// headers: HeaderMap,
/// Extension(state): Extension<AppState>,
/// Query(meta): Query<MetaRequestDto>,
/// ) -> Response {
/// require_permissions!(headers, state, [PermissionsEnum::ReadListUsers], {
/// UsersService::get_user_list(&state, meta).await
/// })
/// }
/// ```
#[macro_export]
macro_rules! require_permissions {
($headers:expr, $state:expr, [$($perm:expr),*], $body:block) => {
{
let state_clone = $state.clone();
match $crate::permissions_guard(
$headers,
axum::extract::Extension(state_clone),
vec![$($perm),*],
)
.await
{
Ok((_user, _state_inner)) => {
let state = &$state;
$body
}
Err(response) => response,
}
}
};
}
/// Macro for authenticated-only handlers (no specific permissions)
#[macro_export]
macro_rules! require_auth {
($headers:expr, $state:expr, $body:block) => {
{
let state_clone = $state.clone();
match $crate::permissions_guard($headers, axum::extract::Extension(state_clone), vec![]).await {
Ok((_user, _state_inner)) => {
let state = &$state;
$body
}
Err(response) => response,
}
}
};
}
use axum::{
extract::Extension,
http::HeaderMap,
};
use imphnen_entities::PermissionsEnum;
use crate::AppState;
use crate::permissions_guard;
use imphnen_libs::jsonwebtoken::Claims;
use imphnen_utils::AppError;
pub type PermissionGuardResult<T> = Result<(T, AppState), AppError>;
pub async fn check_permissions(
headers: HeaderMap,
state: Extension<AppState>,
required_permissions: Vec<PermissionsEnum>,
) -> PermissionGuardResult<Claims> {
permissions_guard(headers, state, required_permissions).await
}
pub async fn check_authenticated(
headers: HeaderMap,
state: Extension<AppState>,
) -> PermissionGuardResult<Claims> {
check_permissions(headers, state, vec![]).await
}
#[macro_export]
macro_rules! require_permissions {
($headers:expr, $state:expr, [$($perm:expr),*], $body:block) => {
{
let state_clone = $state.clone();
$crate::permissions_guard(
$headers,
axum::extract::Extension(state_clone),
vec![$($perm),*],
)
.await?;
$body
}
};
}
#[macro_export]
macro_rules! require_auth {
($headers:expr, $state:expr, $body:block) => {
{
let state_clone = $state.clone();
$crate::permissions_guard($headers, axum::extract::Extension(state_clone), vec![]).await?;
$body
}
};
}
@@ -0,0 +1,2 @@
pub mod permission_service;
pub use permission_service::PermissionServiceImpl;
@@ -0,0 +1,53 @@
use std::sync::Arc;
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::permissions::domain::{PermissionEntity, PermissionRepository, PermissionService};
pub struct PermissionServiceImpl {
repo: Arc<dyn PermissionRepository>,
}
impl PermissionServiceImpl {
pub fn new(repo: Arc<dyn PermissionRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl PermissionService for PermissionServiceImpl {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<PermissionEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: String) -> Result<PermissionEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(&self, name: String) -> Result<String, AppError> {
// Check for name conflict
match self.repo.find_by_name(name.clone()).await {
Ok(_) => return Err(AppError::ConflictError("Permission name already exists".into())),
Err(AppError::NotFoundError(_)) => {}
Err(e) => return Err(e),
}
let entity = PermissionEntity {
id: Uuid::new_v4(),
name,
is_deleted: false,
created_at: None,
updated_at: None,
};
self.repo.create(entity).await
}
async fn update(&self, entity: PermissionEntity) -> Result<String, AppError> {
self.repo.update(entity).await
}
async fn delete(&self, id: String) -> Result<String, AppError> {
self.repo.delete(id).await
}
}
@@ -0,0 +1,7 @@
pub mod permission;
pub mod repository;
pub mod service;
pub use permission::PermissionEntity;
pub use repository::PermissionRepository;
pub use service::PermissionService;
@@ -0,0 +1,10 @@
use uuid::Uuid;
#[derive(Clone, Debug)]
pub struct PermissionEntity {
pub id: Uuid,
pub name: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use imphnen_utils::AppError;
use super::permission::PermissionEntity;
#[async_trait]
pub trait PermissionRepository: Send + Sync {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<PermissionEntity>, AppError>;
async fn find_by_id(&self, id: String) -> Result<PermissionEntity, AppError>;
async fn find_by_name(&self, name: String) -> Result<PermissionEntity, AppError>;
async fn create(&self, entity: PermissionEntity) -> Result<String, AppError>;
async fn update(&self, entity: PermissionEntity) -> Result<String, AppError>;
async fn delete(&self, id: String) -> Result<String, AppError>;
}
@@ -0,0 +1,14 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use imphnen_utils::AppError;
use super::permission::PermissionEntity;
#[async_trait]
pub trait PermissionService: Send + Sync {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<PermissionEntity>, AppError>;
async fn get(&self, id: String) -> Result<PermissionEntity, AppError>;
async fn create(&self, name: String) -> Result<String, AppError>;
async fn update(&self, entity: PermissionEntity) -> Result<String, AppError>;
async fn delete(&self, id: String) -> Result<String, AppError>;
}
@@ -0,0 +1,59 @@
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use zod_rs::prelude::*;
use uuid::Uuid;
use crate::permissions::domain::PermissionEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
pub struct PermissionsCreateRequestDto {
#[zod(min_length(1))]
pub name: String,
}
impl ZodValidate for PermissionsCreateRequestDto {
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, ZodSchema)]
pub struct PermissionsUpdateRequestDto {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
impl ZodValidate for PermissionsUpdateRequestDto {
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 PermissionsItemDto {
pub id: String,
pub name: String,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<PermissionEntity> for PermissionsItemDto {
fn from(e: PermissionEntity) -> Self {
Self {
id: e.id.to_string(),
name: e.name,
created_at: e.created_at,
updated_at: e.updated_at,
}
}
}
impl PermissionsUpdateRequestDto {
pub fn apply_to(self, mut entity: PermissionEntity, id: String) -> PermissionEntity {
entity.id = Uuid::parse_str(&id).unwrap_or(entity.id);
if let Some(name) = self.name {
entity.name = name;
}
entity
}
}
@@ -0,0 +1,143 @@
use crate::require_permissions;
use std::sync::Arc;
use axum::{
Extension, Json,
extract::Path,
http::HeaderMap,
response::IntoResponse,
};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use imphnen_libs::AppState;
use imphnen_utils::{ApiSuccess, ApiPaginated, ApiMessage};
use imphnen_entities::{ResponseSuccessDto, ResponseListSuccessDto, PermissionsEnum};
use imphnen_utils::AppError;
use crate::permissions::domain::PermissionService;
use super::dto::{PermissionsCreateRequestDto, PermissionsItemDto, PermissionsUpdateRequestDto};
#[utoipa::path(
get,
path = "/v1/permissions",
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 = "Get permission list", body = ResponseListSuccessDto<Vec<PermissionsItemDto>>)
),
tag = "Permissions"
)]
pub async fn get_permission_list(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn PermissionService>>,
PaginationQuery(params): PaginationQuery,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadListPermissions], {
let result = service.list(params).await?;
let mapped = PaginatorResponse {
data: result.data.into_iter().map(PermissionsItemDto::from).collect::<Vec<_>>(),
meta: result.meta,
};
Ok(ApiPaginated(mapped))
})
}
#[utoipa::path(
get,
path = "/v1/permissions/detail/{id}",
security(("Bearer" = [])),
params(("id" = String, Path, description = "Permission ID")),
responses(
(status = 200, description = "Get permission by ID", body = ResponseSuccessDto<PermissionsItemDto>)
),
tag = "Permissions"
)]
pub async fn get_permission_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn PermissionService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadDetailPermissions], {
let perm = service.get(id).await?;
Ok(ApiSuccess(PermissionsItemDto::from(perm)))
})
}
#[utoipa::path(
post,
path = "/v1/permissions/create",
security(("Bearer" = [])),
request_body = PermissionsCreateRequestDto,
responses(
(status = 201, description = "Create new permission")
),
tag = "Permissions"
)]
pub async fn post_create_permission(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn PermissionService>>,
Json(payload): Json<PermissionsCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::CreatePermissions], {
let msg = service.create(payload.name).await?;
Ok(ApiMessage::created(&msg))
})
}
#[utoipa::path(
put,
path = "/v1/permissions/update/{id}",
security(("Bearer" = [])),
params(("id" = String, Path, description = "Permission ID")),
request_body = PermissionsUpdateRequestDto,
responses(
(status = 200, description = "Update permission")
),
tag = "Permissions"
)]
pub async fn put_update_permission(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn PermissionService>>,
Path(id): Path<String>,
Json(payload): Json<PermissionsUpdateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::UpdatePermissions], {
let current = service.get(id.clone()).await
.map_err(|_| AppError::NotFoundError("Permission not found".to_string()))?;
let updated = payload.apply_to(current, id);
let msg = service.update(updated).await?;
Ok(ApiMessage::ok(&msg))
})
}
#[utoipa::path(
delete,
path = "/v1/permissions/delete/{id}",
security(("Bearer" = [])),
params(("id" = String, Path, description = "Permission ID")),
responses(
(status = 200, description = "Delete permission")
),
tag = "Permissions"
)]
pub async fn delete_permission(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn PermissionService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::DeletePermissions], {
let msg = service.delete(id).await?;
Ok(ApiMessage::ok(&msg))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::{permissions_public_routes, permissions_protected_routes};
@@ -0,0 +1,32 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, post, put}, Extension};
use sea_orm::DatabaseConnection;
use imphnen_libs::AppState;
use crate::permissions::application::PermissionServiceImpl;
use crate::permissions::domain::PermissionService;
use crate::permissions::infrastructure::persistence::PostgresPermissionRepository;
use super::handlers::{
get_permission_list, get_permission_by_id, post_create_permission,
put_update_permission, delete_permission,
};
fn build_service(db: DatabaseConnection) -> Arc<dyn PermissionService> {
let repo = Arc::new(PostgresPermissionRepository::new(db));
Arc::new(PermissionServiceImpl::new(repo))
}
pub fn permissions_public_routes(_db: DatabaseConnection) -> Router {
Router::new()
}
pub fn permissions_protected_routes(db: DatabaseConnection, state: Arc<AppState>) -> Router {
let service = build_service(db);
Router::new()
.route("/permissions", get(get_permission_list))
.route("/permissions/detail/{id}", get(get_permission_by_id))
.route("/permissions/create", post(post_create_permission))
.route("/permissions/update/{id}", put(put_update_permission))
.route("/permissions/delete/{id}", delete(delete_permission))
.layer(Extension(service))
.layer(Extension((*state).clone()))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,2 @@
pub mod postgres_permission_repository;
pub use postgres_permission_repository::PostgresPermissionRepository;
@@ -0,0 +1,158 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, QueryOrder, QuerySelect, PaginatorTrait};
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::auth::permissions::{
Entity as PermissionsEntity, Column as PermissionsColumn,
ActiveModel as PermissionsActiveModel, Model as PermissionsModel,
};
use crate::permissions::domain::{PermissionEntity, PermissionRepository};
fn to_entity(model: PermissionsModel) -> PermissionEntity {
PermissionEntity {
id: model.id,
name: model.name,
is_deleted: model.is_deleted,
created_at: Some(model.created_at.to_rfc3339()),
updated_at: Some(model.updated_at.to_rfc3339()),
}
}
pub struct PostgresPermissionRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresPermissionRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl PermissionRepository for PostgresPermissionRepository {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<PermissionEntity>, AppError> {
let page = params.page.max(1);
let per_page = params.per_page.clamp(1, 100);
let mut query = PermissionsEntity::find()
.filter(PermissionsColumn::IsDeleted.eq(false));
if let Some(ref search) = params.search {
query = query.filter(PermissionsColumn::Name.contains(&search.query));
}
let order_column = match params.sort_by.as_deref() {
Some("name") => PermissionsColumn::Name,
_ => PermissionsColumn::CreatedAt,
};
query = match params.sort_direction {
Some(SortDirection::Desc) => query.order_by(order_column, Order::Desc),
_ => query.order_by(order_column, Order::Asc),
};
let total_count = query.clone().count(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let offset = ((page - 1) * per_page) as u64;
let permissions = query.offset(offset).limit(per_page as u64).all(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let data = permissions.into_iter().map(to_entity).collect();
let meta = PaginatorResponseMeta::new(page, per_page, total_count as u32);
Ok(PaginatorResponse { data, meta })
}
async fn find_by_id(&self, id: String) -> Result<PermissionEntity, AppError> {
let perm_id = Uuid::parse_str(&id)
.map_err(|_| AppError::BadRequestError("Invalid permission ID".into()))?;
let model = PermissionsEntity::find_by_id(perm_id)
.filter(PermissionsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Permission not found".into()))?;
Ok(to_entity(model))
}
async fn find_by_name(&self, name: String) -> Result<PermissionEntity, AppError> {
let model = PermissionsEntity::find()
.filter(PermissionsColumn::Name.eq(&name))
.filter(PermissionsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Permission not found".into()))?;
Ok(to_entity(model))
}
async fn create(&self, entity: PermissionEntity) -> Result<String, AppError> {
let active_model = PermissionsActiveModel {
id: ActiveValue::Set(entity.id),
name: ActiveValue::Set(entity.name),
is_deleted: ActiveValue::Set(false),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
};
let result = PermissionsEntity::insert(active_model)
.exec(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(format!("Success create permission with id: {}", result.last_insert_id))
}
async fn update(&self, entity: PermissionEntity) -> Result<String, AppError> {
let existing = PermissionsEntity::find_by_id(entity.id)
.filter(PermissionsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Permission not found".into()))?;
let active_model = PermissionsActiveModel {
id: ActiveValue::Set(entity.id),
name: ActiveValue::Set(entity.name),
is_deleted: ActiveValue::Set(entity.is_deleted),
created_at: ActiveValue::Unchanged(existing.created_at),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
};
let result = active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(format!("Success update permission with id: {}", result.id))
}
async fn delete(&self, id: String) -> Result<String, AppError> {
let perm_id = Uuid::parse_str(&id)
.map_err(|_| AppError::BadRequestError("Invalid permission ID".into()))?;
let _existing = PermissionsEntity::find_by_id(perm_id)
.filter(PermissionsColumn::IsDeleted.eq(false))
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Permission not found".into()))?;
let active_model = PermissionsActiveModel {
id: ActiveValue::Set(perm_id),
is_deleted: ActiveValue::Set(true),
deleted_at: ActiveValue::Set(Some(chrono::Utc::now())),
..Default::default()
};
let result = active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(format!("Success delete permission with id: {}", result.id))
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod domain;
pub mod application;
pub mod infrastructure;
pub use infrastructure::http::routes::{permissions_public_routes, permissions_protected_routes};
+69
View File
@@ -0,0 +1,69 @@
use imphnen_entities::PermissionsEnum;
use crate::{AppState, decode_access_token};
use axum::{
http::HeaderMap,
Extension,
};
use axum_extra::headers::{authorization::Bearer, Authorization, HeaderMapExt};
use imphnen_utils::AppError;
use uuid::Uuid;
pub async fn permissions_guard(
headers: HeaderMap,
Extension(state): Extension<AppState>,
required_permissions: Vec<PermissionsEnum>,
) -> Result<(imphnen_libs::jsonwebtoken::Claims, AppState), AppError> {
let auth_header = headers
.typed_get::<Authorization<Bearer>>()
.ok_or_else(|| AppError::AuthenticationError("Invalid or missing authorization token".to_string()))?;
let token = auth_header.token();
let claims = decode_access_token(token)
.map_err(|_| AppError::AuthenticationError("Invalid or expired token".to_string()))?
.claims;
let user_info = {
let by_email = state.user_lookup_service.get_user_by_email(&claims.sub, &state).await;
match by_email {
Ok(info) => info,
Err(_) => {
let user_id = Uuid::parse_str(&claims.sub)
.map_err(|_| AppError::AuthenticationError("Invalid user ID format".to_string()))?;
state.user_lookup_service.get_user_by_id(user_id, &state).await
.map_err(|_| AppError::AuthenticationError("User not found".to_string()))?
}
}
};
let user_permissions: Vec<String> = user_info.basic_info.role
.permissions
.as_ref()
.unwrap_or(&vec![])
.iter()
.filter_map(|p| p.as_ref())
.flat_map(|pp| {
let mut res: Vec<String> = Vec::new();
if let Some(name) = pp.name.clone() { res.push(name); }
if let Some(id) = pp.id.as_ref().map(|id| id.to_string()) { res.push(id); }
res
})
.collect();
let admin_name = PermissionsEnum::Administrator.to_string();
let admin_id = PermissionsEnum::Administrator.id();
if user_permissions.contains(&admin_name) || user_permissions.contains(&admin_id) {
return Ok((claims, state));
}
for required in &required_permissions {
let required_str = required.to_string();
let required_id = required.id();
if !user_permissions.contains(&required_str) && !user_permissions.contains(&required_id) {
return Err(AppError::ForbiddenError("You don't have the required permissions".to_string()));
}
}
Ok((claims, state))
}
+2
View File
@@ -0,0 +1,2 @@
pub mod role_service;
pub use role_service::RoleServiceImpl;
@@ -0,0 +1,69 @@
use std::sync::Arc;
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use uuid::Uuid;
use imphnen_utils::AppError;
use crate::roles::domain::{RoleEntity, RoleRepository, RoleService};
pub struct RoleServiceImpl {
repo: Arc<dyn RoleRepository>,
}
impl RoleServiceImpl {
pub fn new(repo: Arc<dyn RoleRepository>) -> Self {
Self { repo }
}
}
#[async_trait]
impl RoleService for RoleServiceImpl {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<RoleEntity>, AppError> {
self.repo.find_all(params).await
}
async fn get(&self, id: String) -> Result<RoleEntity, AppError> {
self.repo.find_by_id(id).await
}
async fn create(&self, name: String, permissions: Vec<String>) -> Result<RoleEntity, AppError> {
// Check for name conflict
match self.repo.find_by_name(name.clone()).await {
Ok(_) => return Err(AppError::ConflictError("Role name already exists".into())),
Err(AppError::NotFoundError(_)) => {}
Err(e) => return Err(e),
}
let entity = RoleEntity {
id: Uuid::new_v4(),
name,
permissions,
..Default::default()
};
self.repo.create(entity).await
}
async fn update(&self, id: String, name: Option<String>, permissions: Option<Vec<String>>) -> Result<String, AppError> {
// Validate the role exists
let existing = self.repo.find_by_id(id.clone()).await?;
// Check name uniqueness if name is being changed
if let Some(ref new_name) = name {
match self.repo.find_by_name(new_name.clone()).await {
Ok(found) if found.id != existing.id => {
return Err(AppError::ConflictError("Role name already exists".into()));
}
Ok(_) => {}
Err(AppError::NotFoundError(_)) => {}
Err(e) => return Err(e),
}
}
self.repo.update(id, name, permissions).await
}
async fn delete(&self, id: String) -> Result<String, AppError> {
// Validate the role exists
self.repo.find_by_id(id.clone()).await?;
self.repo.delete(id).await
}
}
+7
View File
@@ -0,0 +1,7 @@
pub mod role;
pub mod repository;
pub mod service;
pub use role::RoleEntity;
pub use repository::RoleRepository;
pub use service::RoleService;
@@ -0,0 +1,15 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use imphnen_utils::AppError;
use super::role::RoleEntity;
#[async_trait]
pub trait RoleRepository: Send + Sync {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<RoleEntity>, AppError>;
async fn find_by_id(&self, id: String) -> Result<RoleEntity, AppError>;
async fn find_by_name(&self, name: String) -> Result<RoleEntity, AppError>;
async fn create(&self, entity: RoleEntity) -> Result<RoleEntity, AppError>;
async fn update(&self, id: String, name: Option<String>, permissions: Option<Vec<String>>) -> Result<String, AppError>;
async fn delete(&self, id: String) -> Result<String, AppError>;
}
+14
View File
@@ -0,0 +1,14 @@
use uuid::Uuid;
#[derive(Clone, Debug, Default)]
pub struct RoleEntity {
pub id: Uuid,
pub name: String,
pub description: String,
pub is_system_role: bool,
pub is_default: bool,
pub permissions: Vec<String>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
pub deleted_at: Option<String>,
}
+14
View File
@@ -0,0 +1,14 @@
use async_trait::async_trait;
use paginator_rs::PaginationParams;
use paginator_utils::PaginatorResponse;
use imphnen_utils::AppError;
use super::role::RoleEntity;
#[async_trait]
pub trait RoleService: Send + Sync {
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<RoleEntity>, AppError>;
async fn get(&self, id: String) -> Result<RoleEntity, AppError>;
async fn create(&self, name: String, permissions: Vec<String>) -> Result<RoleEntity, AppError>;
async fn update(&self, id: String, name: Option<String>, permissions: Option<Vec<String>>) -> Result<String, AppError>;
async fn delete(&self, id: String) -> Result<String, AppError>;
}
@@ -0,0 +1,101 @@
use imphnen_entities::{PermissionsEnum, PermissionsItemDto};
use imphnen_libs::ZodValidate;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use utoipa::ToSchema;
use zod_rs::prelude::*;
use crate::roles::domain::RoleEntity;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
pub struct RolesCreateRequestDto {
#[zod(min_length(1))]
pub name: String,
pub permissions: Vec<String>,
}
impl ZodValidate for RolesCreateRequestDto {
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, ZodSchema)]
pub struct RolesUpdateRequestDto {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub permissions: Option<Vec<String>>,
}
impl ZodValidate for RolesUpdateRequestDto {
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 RolesListItemDto {
pub id: String,
pub name: String,
pub permissions_count: usize,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<RoleEntity> for RolesListItemDto {
fn from(e: RoleEntity) -> Self {
Self {
permissions_count: e.permissions.len(),
id: e.id.to_string(),
name: e.name,
created_at: e.created_at,
updated_at: e.updated_at,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
pub struct RolesDetailItemDto {
pub id: String,
pub name: String,
pub description: String,
pub is_system_role: bool,
pub is_default: bool,
pub permissions: Vec<PermissionsItemDto>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<RoleEntity> for RolesDetailItemDto {
fn from(e: RoleEntity) -> Self {
let permissions_dto = e.permissions.iter().map(|p_str| {
for enum_val in PermissionsEnum::iter() {
if enum_val.to_string() == *p_str {
return PermissionsItemDto {
id: enum_val.id(),
name: p_str.clone(),
created_at: None,
updated_at: None,
};
}
}
PermissionsItemDto {
id: String::new(),
name: p_str.clone(),
created_at: None,
updated_at: None,
}
}).collect();
Self {
id: e.id.to_string(),
name: e.name,
description: e.description,
is_system_role: e.is_system_role,
is_default: e.is_default,
permissions: permissions_dto,
created_at: e.created_at,
updated_at: e.updated_at,
}
}
}
@@ -0,0 +1,140 @@
use crate::require_permissions;
use std::sync::Arc;
use axum::{
Extension, Json,
extract::Path,
http::HeaderMap,
response::IntoResponse,
};
use paginator_axum::PaginationQuery;
use paginator_utils::PaginatorResponse;
use imphnen_libs::AppState;
use imphnen_utils::{ApiSuccess, ApiCreated, ApiPaginated, ApiMessage};
use imphnen_entities::{ResponseSuccessDto, ResponseListSuccessDto, PermissionsEnum};
use imphnen_utils::AppError;
use crate::roles::domain::RoleService;
use super::dto::{RolesCreateRequestDto, RolesDetailItemDto, RolesListItemDto, RolesUpdateRequestDto};
#[utoipa::path(
get,
path = "/v1/roles",
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 = "Get role list", body = ResponseListSuccessDto<Vec<RolesListItemDto>>)
),
tag = "Roles"
)]
pub async fn get_role_list(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoleService>>,
PaginationQuery(params): PaginationQuery,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadListRoles], {
let result = service.list(params).await?;
let mapped = PaginatorResponse {
data: result.data.into_iter().map(RolesListItemDto::from).collect::<Vec<_>>(),
meta: result.meta,
};
Ok(ApiPaginated(mapped))
})
}
#[utoipa::path(
get,
path = "/v1/roles/detail/{id}",
security(("Bearer" = [])),
params(("id" = String, Path, description = "Role ID")),
responses(
(status = 200, description = "Get role by ID", body = ResponseSuccessDto<RolesDetailItemDto>)
),
tag = "Roles"
)]
pub async fn get_role_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoleService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::ReadDetailRoles], {
let role = service.get(id).await?;
Ok(ApiSuccess(RolesDetailItemDto::from(role)))
})
}
#[utoipa::path(
post,
path = "/v1/roles/create",
security(("Bearer" = [])),
request_body = RolesCreateRequestDto,
responses(
(status = 201, description = "Create new role", body = ResponseSuccessDto<RolesDetailItemDto>)
),
tag = "Roles"
)]
pub async fn post_create_role(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoleService>>,
Json(payload): Json<RolesCreateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::CreateRoles], {
let role = service.create(payload.name, payload.permissions).await?;
Ok(ApiCreated(RolesDetailItemDto::from(role)))
})
}
#[utoipa::path(
put,
path = "/v1/roles/update/{id}",
security(("Bearer" = [])),
params(("id" = String, Path, description = "Role ID")),
request_body = RolesUpdateRequestDto,
responses(
(status = 200, description = "Update role")
),
tag = "Roles"
)]
pub async fn put_update_role(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoleService>>,
Path(id): Path<String>,
Json(payload): Json<RolesUpdateRequestDto>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::UpdateRoles], {
let msg = service.update(id, payload.name, payload.permissions).await?;
Ok(ApiMessage::ok(&msg))
})
}
#[utoipa::path(
delete,
path = "/v1/roles/delete/{id}",
security(("Bearer" = [])),
params(("id" = String, Path, description = "Role ID")),
responses(
(status = 200, description = "Delete role")
),
tag = "Roles"
)]
pub async fn delete_role(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Extension(service): Extension<Arc<dyn RoleService>>,
Path(id): Path<String>,
) -> Result<impl IntoResponse, AppError> {
require_permissions!(headers, state, [PermissionsEnum::DeleteRoles], {
let msg = service.delete(id).await?;
Ok(ApiMessage::ok(&msg))
})
}
@@ -0,0 +1,5 @@
pub mod dto;
pub mod handlers;
pub mod routes;
pub use routes::{roles_public_routes, roles_protected_routes};
@@ -0,0 +1,31 @@
use std::sync::Arc;
use axum::{Router, routing::{delete, get, post, put}, Extension};
use sea_orm::DatabaseConnection;
use imphnen_libs::AppState;
use crate::roles::application::RoleServiceImpl;
use crate::roles::domain::RoleService;
use crate::roles::infrastructure::persistence::PostgresRoleRepository;
use super::handlers::{
get_role_list, get_role_by_id, post_create_role, put_update_role, delete_role,
};
fn build_service(db: DatabaseConnection) -> Arc<dyn RoleService> {
let repo = Arc::new(PostgresRoleRepository::new(db));
Arc::new(RoleServiceImpl::new(repo))
}
pub fn roles_public_routes(_db: DatabaseConnection) -> Router {
Router::new()
}
pub fn roles_protected_routes(db: DatabaseConnection, state: Arc<AppState>) -> Router {
let service = build_service(db);
Router::new()
.route("/roles", get(get_role_list))
.route("/roles/detail/{id}", get(get_role_by_id))
.route("/roles/create", post(post_create_role))
.route("/roles/update/{id}", put(put_update_role))
.route("/roles/delete/{id}", delete(delete_role))
.layer(Extension(service))
.layer(Extension((*state).clone()))
}
@@ -0,0 +1,2 @@
pub mod http;
pub mod persistence;
@@ -0,0 +1,2 @@
pub mod postgres_role_repository;
pub use postgres_role_repository::PostgresRoleRepository;
@@ -0,0 +1,164 @@
use std::sync::Arc;
use async_trait::async_trait;
use sea_orm::prelude::*;
use sea_orm::{ActiveValue, Order, QueryOrder, QuerySelect, PaginatorTrait};
use paginator_rs::{PaginationParams, SortDirection};
use paginator_utils::{PaginatorResponse, PaginatorResponseMeta};
use uuid::Uuid;
use imphnen_utils::AppError;
use imphnen_entities::seaorm::auth::roles::{
Entity as RolesEntity, Column as RolesColumn,
ActiveModel as RolesActiveModel, Model as RolesModel,
};
use crate::roles::domain::{RoleEntity, RoleRepository};
fn to_entity(model: RolesModel) -> RoleEntity {
let permissions = model.permissions.as_ref()
.and_then(|p| serde_json::from_value::<Vec<String>>(p.clone()).ok())
.unwrap_or_default();
RoleEntity {
id: model.id,
name: model.name,
description: model.description,
is_system_role: model.is_system_role,
is_default: model.is_default,
permissions,
created_at: Some(model.created_at.to_rfc3339()),
updated_at: Some(model.updated_at.to_rfc3339()),
deleted_at: model.deleted_at.map(|d| d.to_rfc3339()),
}
}
pub struct PostgresRoleRepository {
db: Arc<DatabaseConnection>,
}
impl PostgresRoleRepository {
pub fn new(db: DatabaseConnection) -> Self {
Self { db: Arc::new(db) }
}
}
#[async_trait]
impl RoleRepository for PostgresRoleRepository {
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<RoleEntity>, AppError> {
let page = params.page.max(1);
let per_page = params.per_page.clamp(1, 100);
let mut query = RolesEntity::find()
.filter(RolesColumn::DeletedAt.is_null());
if let Some(ref search) = params.search {
query = query.filter(RolesColumn::Name.contains(&search.query));
}
let sort_column = match params.sort_by.as_deref() {
Some("name") => RolesColumn::Name,
_ => RolesColumn::CreatedAt,
};
query = match params.sort_direction {
Some(SortDirection::Desc) => query.order_by(sort_column, Order::Desc),
_ => query.order_by(sort_column, Order::Asc),
};
let total_count = query.clone().count(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let offset = ((page - 1) * per_page) as u64;
let roles = query.offset(offset).limit(per_page as u64).all(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
let data = roles.into_iter().map(to_entity).collect();
let meta = PaginatorResponseMeta::new(page, per_page, total_count as u32);
Ok(PaginatorResponse { data, meta })
}
async fn find_by_id(&self, id: String) -> Result<RoleEntity, AppError> {
let role_id = Uuid::parse_str(&id)
.map_err(|_| AppError::BadRequestError("Invalid role ID".into()))?;
let model = RolesEntity::find_by_id(role_id)
.filter(RolesColumn::DeletedAt.is_null())
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Role not found".into()))?;
Ok(to_entity(model))
}
async fn find_by_name(&self, name: String) -> Result<RoleEntity, AppError> {
let model = RolesEntity::find()
.filter(RolesColumn::Name.eq(&name))
.filter(RolesColumn::DeletedAt.is_null())
.one(self.db.as_ref())
.await
.map_err(|e| AppError::InternalServerError(e.to_string()))?
.ok_or_else(|| AppError::NotFoundError("Role not found".into()))?;
Ok(to_entity(model))
}
async fn create(&self, entity: RoleEntity) -> Result<RoleEntity, AppError> {
let permissions_json = serde_json::to_value(&entity.permissions)
.map_err(|e| AppError::InternalServerError(format!("Failed to serialize permissions: {e}")))?;
let active_model = RolesActiveModel {
id: ActiveValue::Set(entity.id),
name: ActiveValue::Set(entity.name),
description: ActiveValue::Set(entity.description),
is_system_role: ActiveValue::Set(entity.is_system_role),
is_default: ActiveValue::Set(entity.is_default),
permissions: ActiveValue::Set(Some(permissions_json)),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
};
let created = active_model.insert(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok(to_entity(created))
}
async fn update(&self, id: String, name: Option<String>, permissions: Option<Vec<String>>) -> Result<String, AppError> {
let role_id = Uuid::parse_str(&id)
.map_err(|_| AppError::BadRequestError("Invalid role ID".into()))?;
let mut active_model = RolesActiveModel {
id: ActiveValue::Unchanged(role_id),
..Default::default()
};
if let Some(n) = name {
active_model.name = ActiveValue::Set(n);
}
if let Some(perms) = permissions {
let permissions_json = serde_json::to_value(&perms)
.map_err(|e| AppError::InternalServerError(format!("Failed to serialize permissions: {e}")))?;
active_model.permissions = ActiveValue::Set(Some(permissions_json));
}
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok("Success update role".into())
}
async fn delete(&self, id: String) -> Result<String, AppError> {
let role_id = Uuid::parse_str(&id)
.map_err(|_| AppError::BadRequestError("Invalid role ID".into()))?;
let active_model = RolesActiveModel {
id: ActiveValue::Unchanged(role_id),
deleted_at: ActiveValue::Set(Some(chrono::Utc::now())),
..Default::default()
};
active_model.update(self.db.as_ref()).await
.map_err(|e| AppError::InternalServerError(e.to_string()))?;
Ok("Success delete role".into())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod domain;
pub mod application;
pub mod infrastructure;
pub use infrastructure::http::routes::{roles_public_routes, roles_protected_routes};
+2
View File
@@ -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
}
}
+7
View File
@@ -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>;
}
+19
View File
@@ -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>;
}
+18
View File
@@ -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())
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod domain;
pub mod application;
pub mod infrastructure;
pub use infrastructure::http::routes::{users_public_routes, users_protected_routes};
-146
View File
@@ -1,146 +0,0 @@
use super::{
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
};
use crate::{AppState, v1::auth::AuthLoginResponsetDto};
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
use axum::{Extension, Json, response::IntoResponse};
use crate::v1::auth::auth_service::AuthServiceTrait;
use crate::v1::auth::auth_service::AuthService;
#[utoipa::path(
post,
path = "/v1/auth/login",
request_body = AuthLoginRequestDto,
responses(
(status = 200, description = "[PUBLIC] Login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
(status = 401, description = "[PUBLIC] Login failed", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_login(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthLoginRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_login(payload, &state).await
}
#[utoipa::path(
post,
path = "/v1/auth/login-mentor",
request_body = AuthLoginRequestDto,
responses(
(status = 200, description = "[PUBLIC] Mentor login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
(status = 401, description = "[PUBLIC] Mentor login failed", body = MessageResponseDto),
(status = 403, description = "[PUBLIC] Forbidden - Not a mentor", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_login_mentor(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthLoginRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_mentor_login(payload, &state).await
}
#[utoipa::path(
post,
path = "/v1/auth/register",
request_body = AuthRegisterRequestDto,
responses(
(status = 200, description = "[PUBLIC] Register successful", body = MessageResponseDto),
(status = 401, description = "[PUBLIC] Register failed", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_register(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthRegisterRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_register(payload, &state).await
}
#[utoipa::path(
post,
path = "/v1/auth/verify-email",
request_body = AuthVerifyEmailRequestDto,
responses(
(status = 200, description = "[PUBLIC] Verify email successful", body = MessageResponseDto),
(status = 401, description = "[PUBLIC] Verify email failed", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_verify_email(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthVerifyEmailRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_verify_email(payload, &state).await
}
#[utoipa::path(
post,
path = "/v1/auth/send-otp",
request_body = AuthResendOtpRequestDto,
responses(
(status = 200, description = "[PUBLIC] Resend otp successful", body = MessageResponseDto),
(status = 401, description = "[PUBLIC] Resend otp failed", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_resend_otp(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthResendOtpRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_resend_otp(payload, &state).await
}
#[utoipa::path(
post,
path = "/v1/auth/forgot",
request_body = AuthResendOtpRequestDto,
responses(
(status = 200, description = "[PUBLIC] Forgot password request successful", body = MessageResponseDto),
(status = 401, description = "[PUBLIC] Forgot password request failed", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_forgot_password(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthResendOtpRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_forgot_password(payload, &state).await
}
#[utoipa::path(
post,
path = "/v1/auth/new-password",
request_body = AuthNewPasswordRequestDto,
responses(
(status = 200, description = "[PUBLIC] New password request successful", body = MessageResponseDto),
(status = 401, description = "[PUBLIC] New password request failed", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_new_password(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthNewPasswordRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_new_password(payload, &state).await
}
#[utoipa::path(
post,
path = "/v1/auth/refresh",
request_body = AuthRefreshTokenRequestDto,
responses(
(status = 200, description = "[PUBLIC] Refresh token request successful", body = MessageResponseDto),
(status = 401, description = "[PUBLIC] Refresh token request failed", body = MessageResponseDto)
),
tag = "Authentication"
)]
pub async fn post_refresh_token(
Extension(state): Extension<AppState>,
Json(payload): Json<AuthRefreshTokenRequestDto>,
) -> impl IntoResponse {
AuthService::mutation_refresh_token(payload, &state).await
}
-125
View File
@@ -1,125 +0,0 @@
use crate::UsersDetailItemDto;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::{Validate, ValidationError};
pub fn validate_password_complexity(password: &str) -> Result<(), ValidationError> {
let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
let has_digit = password.chars().any(|c| c.is_ascii_digit());
let has_special = password.chars().any(|c| "@$!%*?&".contains(c));
if has_uppercase && has_lowercase && has_digit && has_special {
Ok(())
} else {
Err(ValidationError::new("complexity"))
}
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthLoginRequestDto {
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
pub email: String,
#[validate(length(min = 1, message = "Password cannot be empty"))]
pub password: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct AuthLoginResponsetDto {
pub token: TokenDto,
pub user: UsersDetailItemDto,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
pub struct TokenDto {
pub access_token: String,
pub refresh_token: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthRegisterRequestDto {
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
pub email: String,
#[validate(length(
min = 8,
message = "Password must have at least 8 characters"
))]
#[validate(custom(
function = "validate_password_complexity",
message = "Password must include uppercase, lowercase, number, and special character"
))]
pub password: String,
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
pub fullname: String,
// Phone number is optional now
#[serde(skip_serializing_if = "Option::is_none")]
pub phone_number: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthVerifyEmailRequestDto {
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
pub email: String,
pub otp: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthResendOtpRequestDto {
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
pub email: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthRefreshTokenRequestDto {
#[validate(length(min = 1, message = "Refresh token cannot be empty"))]
pub refresh_token: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthNewPasswordRequestDto {
#[validate(length(min = 1, message = "Token cannot be empty"))]
pub token: String,
#[validate(length(
min = 8,
message = "Password must have at least 8 characters"
))]
#[validate(custom(
function = "validate_password_complexity",
message = "Password must include uppercase, lowercase, number, and special character"
))]
pub password: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct AuthSetNewPasswordRequestDto {
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
pub email: String,
#[validate(length(
min = 8,
message = "Password must have at least 8 characters"
))]
#[validate(custom(
function = "validate_password_complexity",
message = "Password must include uppercase, lowercase, number, and special character"
))]
pub password: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserCacheSchema {
pub email: String,
pub permissions: Vec<String>,
}
-196
View File
@@ -1,196 +0,0 @@
use imphnen_entities::seaorm::auth::users::Entity as UsersEntity;
use imphnen_entities::seaorm::auth::users::Model as UserModel;
use chrono::Utc;
use async_trait::async_trait;
use sea_orm::{DatabaseConnection, EntityTrait, QueryFilter, ColumnTrait, ActiveModelTrait, ActiveValue};
use imphnen_libs::{AuthRepositoryTrait, services::ServiceError, services::UserRegistrationData, AppState, AppStatePostgresExt};
use uuid::Uuid;
/// PostgreSQL-based authentication repository
///
/// This repository handles authentication-related database operations
/// using SeaORM for PostgreSQL integration.
pub struct AuthRepository<'a> {
pub db: &'a DatabaseConnection,
}
impl<'a> AuthRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { db: state.postgres_db() }
}
}
/// PostgreSQL-based implementation of authentication repository
///
/// This implementation completes the migration from SurrealDB to PostgreSQL using SeaORM.
/// All database operations now use native PostgreSQL queries through SeaORM's entity system.
#[async_trait]
impl AuthRepositoryTrait for AuthRepository<'_> {
async fn get_user_for_auth(&self, email: &str, _state: &AppState) -> Result<UserModel, ServiceError> {
UsersEntity::find()
.filter(imphnen_entities::seaorm::auth::users::Column::Email.eq(email))
.one(self.db)
.await
.map_err(ServiceError::DatabaseError)?
.ok_or_else(|| ServiceError::UserNotFound(format!("User with email {email} not found")))
}
async fn validate_credentials(&self, email: &str, password: &str, state: &AppState) -> Result<UserModel, ServiceError> {
use imphnen_libs::argon::verify_password;
let user = self.get_user_for_auth(email, state).await?;
if !user.is_active {
return Err(ServiceError::AuthenticationFailed("Account is deactivated".to_string()));
}
if !user.is_verified {
return Err(ServiceError::AuthenticationFailed("Account not verified".to_string()));
}
let is_valid = verify_password(password, &user.password_hash)
.map_err(|e| ServiceError::InternalError(format!("Password verification failed: {e}")))?;
if !is_valid {
return Err(ServiceError::AuthenticationFailed("Invalid password".to_string()));
}
Ok(user)
}
async fn update_last_login(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
let user = UsersEntity::find_by_id(user_id)
.one(self.db)
.await
.map_err(ServiceError::DatabaseError)?
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
active_model.updated_at = ActiveValue::Set(Utc::now());
active_model
.update(self.db)
.await
.map_err(ServiceError::DatabaseError)?;
Ok(())
}
async fn create_user(&self, user_data: UserRegistrationData, _state: &AppState) -> Result<UserModel, ServiceError> {
// Check if user already exists
if UsersEntity::find()
.filter(imphnen_entities::seaorm::auth::users::Column::Email.eq(&user_data.email))
.one(self.db)
.await
.map_err(ServiceError::DatabaseError)?
.is_some() {
return Err(ServiceError::ValidationError("User already exists".to_string()));
}
let first_name = user_data.first_name.unwrap_or_default();
let last_name = user_data.last_name.unwrap_or_default();
let active_model = imphnen_entities::seaorm::auth::users::ActiveModel {
id: ActiveValue::Set(Uuid::new_v4()),
email: ActiveValue::Set(user_data.email.clone()),
password_hash: ActiveValue::Set(user_data.password_hash),
username: ActiveValue::Set(user_data.email.clone()), // Use email as username for now
first_name: ActiveValue::Set(Some(first_name.to_string())),
last_name: ActiveValue::Set(Some(last_name.to_string())),
avatar_url: ActiveValue::Set(user_data.avatar_url),
is_verified: ActiveValue::Set(false),
is_active: ActiveValue::Set(true),
metadata: ActiveValue::Set(None),
created_at: ActiveValue::Set(Utc::now()),
updated_at: ActiveValue::Set(Utc::now()),
deleted_at: ActiveValue::Set(None),
role_id: ActiveValue::Set(user_data.role_id),
};
let user = UsersEntity::insert(active_model)
.exec(self.db)
.await
.map_err(ServiceError::DatabaseError)?;
// Get the created user
UsersEntity::find_by_id(user.last_insert_id)
.one(self.db)
.await
.map_err(ServiceError::DatabaseError)?
.ok_or_else(|| ServiceError::InternalError("Failed to retrieve created user".to_string()))
}
async fn update_password(&self, user_id: Uuid, new_password_hash: &str, _state: &AppState) -> Result<(), ServiceError> {
let user = UsersEntity::find_by_id(user_id)
.one(self.db)
.await
.map_err(ServiceError::DatabaseError)?
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {user_id} not found")))?;
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
active_model.password_hash = ActiveValue::Set(new_password_hash.to_string());
active_model.updated_at = ActiveValue::Set(Utc::now());
active_model
.update(self.db)
.await
.map_err(ServiceError::DatabaseError)?;
Ok(())
}
async fn deactivate_user(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
let user = UsersEntity::find_by_id(user_id)
.one(self.db)
.await
.map_err(ServiceError::DatabaseError)?
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
active_model.is_active = ActiveValue::Set(false);
active_model.updated_at = ActiveValue::Set(Utc::now());
active_model
.update(self.db)
.await
.map_err(ServiceError::DatabaseError)?;
Ok(())
}
async fn reactivate_user(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
let user = UsersEntity::find_by_id(user_id)
.one(self.db)
.await
.map_err(ServiceError::DatabaseError)?
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
active_model.is_active = ActiveValue::Set(true);
active_model.updated_at = ActiveValue::Set(Utc::now());
active_model
.update(self.db)
.await
.map_err(ServiceError::DatabaseError)?;
Ok(())
}
async fn get_user_permissions(&self, _user_id: Uuid, _state: &AppState) -> Result<Vec<String>, ServiceError> {
// This is a simplified implementation - in a real app you'd join with roles_permissions
// For now, return empty vec
Ok(vec![])
}
async fn has_permission(&self, _user_id: Uuid, _permission: &str, _state: &AppState) -> Result<bool, ServiceError> {
// This is a simplified implementation - in a real app you'd check roles_permissions
// For now, return false
Ok(false)
}
}
// Re-export the Postgres-backed auth repository implementation from imphnen-libs
// There is an existing generic implementation in imphnen-libs::services::PostgresAuthRepository
// Re-export it here so other crates can import a stable name `AuthRepoImpl` as expected.
pub use imphnen_libs::services::PostgresAuthRepository as AuthRepoImpl;
-9
View File
@@ -1,9 +0,0 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuthOtpSchema {
pub otp: u32,
pub hash: String,
pub expires_at: DateTime<Utc>,
}
-578
View File
@@ -1,578 +0,0 @@
use std::pin::Pin;
use std::future::Future;
use imphnen_libs::environment;
use imphnen_libs::AuthRepositoryTrait; // Added this import
use super::{
AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto,
AuthRefreshTokenRequestDto, AuthRegisterRequestDto, AuthRepository,
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto, TokenDto,
};
use crate::{
AppState, ResponseSuccessDto, RolesEnum, RolesRepository,
UsersDetailItemDto, UsersRepository, UsersSchema, common_response,
decode_refresh_token, decode_access_token, encode_access_token, encode_refresh_token,
encode_reset_password_token, get_iso_date,
hash_password, send_email, success_response, validate_request, OtpManager,
};
use imphnen_entities::users::UserProfileExtensionDto;
use axum::{http::StatusCode, response::Response};
use crate::{AppError, error_response};
use tracing::error;
use tokio;
use uuid::Uuid;
pub trait AuthServiceTrait: Send + Sync + 'static {
fn mutation_login(
payload: AuthLoginRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn mutation_mentor_login(
payload: AuthLoginRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn mutation_register(
payload: AuthRegisterRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn mutation_resend_otp(
payload: AuthResendOtpRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn mutation_refresh_token(
payload: AuthRefreshTokenRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn mutation_forgot_password(
payload: AuthResendOtpRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn mutation_verify_email(
payload: AuthVerifyEmailRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn mutation_new_password(
payload: AuthNewPasswordRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>>;
}
#[derive(Clone)] // Added Clone derive
pub struct AuthService;
impl AuthServiceTrait for AuthService {
fn mutation_login(
payload: AuthLoginRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let user_repo = UsersRepository::new(&state);
let auth_repo = AuthRepository::new(&state);
let email = &payload.email;
let password = &payload.password;
match auth_repo.validate_credentials(email, password, &state).await {
Ok(_) => {
// Credentials are valid, now fetch user details for the response (with Role)
match user_repo.query_user_by_email(email.to_string()).await {
Ok(user) => {
if !user.is_active {
return error_response(AppError::AuthenticationError("Account not active, please verify your email".into()));
}
let user_id = user.id.clone();
let access_token = match encode_access_token(email.to_string(), user_id.clone()) {
Ok(token) => token,
Err(_e) => {
error!(
"Failed to generate access token for {}: {}",
email, _e
);
return error_response(AppError::InternalServerError("Failed to generate access token".into()));
}
};
let refresh_token = match encode_refresh_token(email.to_string(), user_id) {
Ok(token) => token,
Err(_e) => {
error!(
"Failed to generate refresh token for {}: {}",
email, _e
);
return error_response(AppError::InternalServerError("Failed to generate refresh token".into()));
}
};
let response = ResponseSuccessDto {
data: AuthLoginResponsetDto {
user: UsersDetailItemDto::from(&user),
token: TokenDto {
access_token,
refresh_token,
},
},
};
// Only clone user if caching is required
// if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
// error!(
// "Failed to store user cache for {}: {}",
// user.email, err_store
// );
// return error_response(AppError::BadRequestError("User already login or failed to cache".into()));
// }
success_response(response)
},
Err(err_find) => {
error!("User found during validation but failed to fetch details: {}", err_find);
error_response(AppError::InternalServerError("Failed to fetch user details".into()))
}
}
},
Err(e) => {
error!("Login failed for {}: {}", email, e);
error_response(AppError::AuthenticationError("Email or password not correct".into()))
}
}
})
}
fn mutation_mentor_login(
payload: AuthLoginRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let user_repo = UsersRepository::new(&state);
let auth_repo = AuthRepository::new(&state);
match auth_repo.validate_credentials(&payload.email, &payload.password, &state).await {
Ok(_) => {
match user_repo.query_user_by_email(payload.email.clone()).await {
Ok(user) => {
if !user.is_active {
return common_response(
StatusCode::BAD_REQUEST,
"Account not active, please verify your email",
);
}
let user_detail = UsersDetailItemDto::from(&user);
if user_detail.role.name != RolesEnum::Mentor.to_string() {
return common_response(
StatusCode::FORBIDDEN,
"User does not have mentor privileges",
);
}
let access_token = match encode_access_token(payload.email.clone(), user.id.clone()) {
Ok(token) => token,
Err(_e) => {
error!(
"Failed to generate access token for {}: {}",
payload.email, _e
);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to generate access token",
);
}
};
let refresh_token = match encode_refresh_token(payload.email.clone(), user.id.clone()) {
Ok(token) => token,
Err(_e) => {
error!(
"Failed to generate refresh token for {}: {}",
payload.email, _e
);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to generate refresh token",
);
}
};
let response = ResponseSuccessDto {
data: AuthLoginResponsetDto {
user: UsersDetailItemDto::from(&user),
token: TokenDto {
access_token,
refresh_token,
},
},
};
// if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
// error!(
// "Failed to store user cache for {}: {}",
// user.email, err_store
// );
// return common_response(
// StatusCode::BAD_REQUEST,
// "User already login or failed to cache",
// );
// }
success_response(response)
},
Err(err_find) => {
common_response(StatusCode::UNAUTHORIZED, &err_find.to_string())
}
}
},
Err(e) => {
error!("Mentor login failed: {}", e);
common_response(StatusCode::BAD_REQUEST, "Email or password not correct")
}
}
})
}
fn mutation_register(
payload: AuthRegisterRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let user_repo = UsersRepository::new(&state);
let _auth_repo = AuthRepository::new(&state);
let role_repo = RolesRepository::new(&state);
let role = match role_repo
.query_role_by_name(RolesEnum::User.to_string())
.await
{
Ok(role) => role,
Err(_e) => {
error!("Failed to retrieve User role during registration: {}", _e);
return common_response(StatusCode::BAD_REQUEST, "Role Not Found");
}
};
if user_repo
.query_user_by_email(payload.email.clone())
.await
.is_ok()
{
return common_response(StatusCode::BAD_REQUEST, "User already exists");
}
let hashed_password = match hash_password(&payload.password) {
Ok(hash) => hash,
Err(_e) => {
error!(
"Failed to hash password during registration for {}: {}",
payload.email, _e
);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to hash password",
);
}
};
let new_user = AuthRegisterRequestDto {
email: payload.email.clone(),
password: hashed_password,
fullname: payload.fullname,
phone_number: payload.phone_number.clone(),
};
let otp = OtpManager::generate_otp();
// Store OTP (commented out for now)
// match auth_repo.query_store_otp(new_user.email.clone(), otp.clone()).await {
// Ok(_) => {
let message = format!("your otp code is {}", otp.code);
if let Err(err_send) =
send_email(&new_user.email, "OTP Verification", &message)
{
error!(
"Failed to send OTP email to {}: {}",
new_user.email, err_send
);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
&err_send.to_string(),
);
}
// }
// Err(err_store) => {
// error!("Failed to store OTP for {}: {}", new_user.email, err_store);
// return common_response(
// StatusCode::INTERNAL_SERVER_ERROR,
// &err_store.to_string(),
// );
// }
// }
match user_repo
.query_create_user(UsersSchema {
id: Uuid::new_v4().to_string(), // Directly use Uuid
email: Some(new_user.email.clone()), // email is now Option<String>
fullname: Some(new_user.fullname.clone()), // fullname is now Option<String>
password: Some(new_user.password.clone()), // password is now Option<String>
created_at: get_iso_date(),
updated_at: get_iso_date(),
role_id: Some(Uuid::parse_str(&role.id).unwrap_or(Uuid::new_v4())), // Use role.id directly
is_active: false,
is_deleted: false,
profile_extension: Some(UserProfileExtensionDto {
phone_number: new_user.phone_number.clone(),
..Default::default()
}),
legal_name: None,
avatar: None,
mentor_id: None,
})
.await
{
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(err_create) => {
error!("Failed to create user {}: {}", new_user.email, err_create);
common_response(StatusCode::INTERNAL_SERVER_ERROR, &err_create.to_string())
}
}
})
}
fn mutation_resend_otp(
payload: AuthResendOtpRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let user_repo = UsersRepository::new(&state);
if user_repo.query_user_by_email(payload.email.clone()).await.is_err() {
return common_response(StatusCode::BAD_REQUEST, "User not found");
}
// let _auth_repo = AuthRepository::new(&state);
// let _ = auth_repo.query_get_stored_otp(payload.email.clone()).await;
let otp = OtpManager::generate_otp();
let message = format!("Your OTP code is {}", otp.code);
match send_email(&payload.email, "OTP Verification", &message) {
Ok(_) => common_response(StatusCode::OK, "OTP sent"),
Err(err_send) => {
error!(
"Failed to send OTP email to {}: {}",
payload.email, err_send
);
common_response(StatusCode::BAD_REQUEST, &err_send.to_string())
}
}
})
}
fn mutation_refresh_token(
payload: AuthRefreshTokenRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let user_repo = UsersRepository::new(&state);
let user = match decode_refresh_token(&payload.refresh_token) {
Ok(token_data) => {
match user_repo.query_user_by_email(token_data.claims.sub.clone()).await {
Ok(user) => user,
Err(_) => return common_response(StatusCode::UNAUTHORIZED, "User not found"),
}
},
Err(_e) => {
return common_response(StatusCode::UNAUTHORIZED, "Invalid refresh token");
}
};
let access_token = match encode_access_token(user.email.clone(), user.id.clone()) {
Ok(token) => token,
Err(_e) => {
error!("Failed to generate access token for {}: {}", user.email, _e);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to generate access token",
);
}
};
let refresh_token = match encode_refresh_token(user.email.clone(), user.id.clone()) {
Ok(token) => token,
Err(_e) => {
error!("Failed to generate refresh token for {}: {}", user.email, _e);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to generate refresh token",
);
}
};
let response = ResponseSuccessDto {
data: TokenDto {
access_token,
refresh_token,
},
};
success_response(response)
})
}
fn mutation_forgot_password(
payload: AuthResendOtpRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
tokio::spawn(async move {
let user_repo = UsersRepository::new(&state);
if let Ok(user) = user_repo.query_user_by_email(payload.email.clone()).await {
let token = match encode_reset_password_token(user.email.clone(), user.id.clone()) {
Ok(token) => token,
Err(_e) => {
error!("Failed to generate reset password token for {}: {}", user.email, _e);
return;
}
};
let env = &environment::ENV;
let fe_url = env.fe_url.clone();
let message = format!(
"You have requested a password reset. Please click the link below to continue: {fe_url}/auth/reset-password?token={token}"
);
if let Err(err_send) = send_email(&payload.email, "Reset Password Request", &message) {
error!("Failed to send reset password email to {}: {}", payload.email, err_send);
}
}
});
common_response(StatusCode::OK, "If your email is registered, you will receive a password reset link.")
})
}
fn mutation_verify_email(
payload: AuthVerifyEmailRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let user_repo = UsersRepository::new(&state);
let _auth_repo = AuthRepository::new(&state);
let email = payload.email.clone();
let user = match user_repo.query_user_by_email(email.clone()).await {
Ok(user) => user,
_ => {
return common_response(StatusCode::NOT_FOUND, "User not found");
}
};
if user.is_active {
return common_response(StatusCode::BAD_REQUEST, "User already active");
}
let patch = UsersSchema {
id: user.id.clone(),
is_active: true,
email: Some(user.email.clone()),
fullname: Some(user.fullname),
password: Some(user.password.clone()),
avatar: user.avatar,
is_deleted: user.is_deleted,
created_at: user.created_at,
updated_at: user.updated_at,
legal_name: user.legal_name,
profile_extension: user.profile_extension.clone(),
role_id: Uuid::parse_str(&user.role.id).ok(),
mentor_id: user.mentor_id,
};
// Simulate OTP verification and user update success for now.
// The actual OTP logic involving AuthRepository needs to be refactored for Postgres.
return match user_repo.query_update_user(patch).await {
Ok(_) => common_response(StatusCode::OK, "Email verified successfully (simulated)"),
Err(err_update) => common_response(StatusCode::BAD_REQUEST, &err_update.to_string()),
};
})
}
fn mutation_new_password(
payload: AuthNewPasswordRequestDto,
state: &AppState,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let user_repo = UsersRepository::new(&state);
let email = match decode_access_token(&payload.token) {
Ok(claims) => claims.claims.sub,
Err(_) => return common_response(StatusCode::BAD_REQUEST, "Invalid or missing token"),
};
let user = match user_repo.query_user_by_email(email.clone()).await {
Ok(u) => u,
Err(e) => return common_response(StatusCode::BAD_REQUEST, &e.to_string()),
};
let password_hash = match hash_password(&payload.password) {
Ok(ph) => ph,
Err(e) => {
error!("Failed to hash new password for {}: {}", user.email, e);
return common_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to hash password");
}
};
let role_id_uuid = match Uuid::parse_str(&user.role.id) {
Ok(uuid) => Some(uuid),
Err(e) => {
error!("Failed to parse role ID {}: {}", user.role.id, e);
None
}
};
let patch = UsersSchema {
id: user.id.clone(),
password: Some(password_hash),
email: Some(user.email.clone()),
fullname: Some(user.fullname),
avatar: user.avatar,
is_active: user.is_active,
is_deleted: user.is_deleted,
created_at: user.created_at,
updated_at: user.updated_at,
profile_extension: user.profile_extension.clone(),
role_id: role_id_uuid,
legal_name: user.legal_name,
mentor_id: user.mentor_id,
};
match user_repo.query_update_user(patch).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(_e) => common_response(StatusCode::BAD_REQUEST, &_e.to_string()),
}
})
}
}
@@ -1,102 +0,0 @@
use axum::{
extract::{Query, State},
response::Redirect,
routing::get,
Json, Router, Extension,
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use std::sync::Arc;
use imphnen_libs::environment::ENV; // Import ENV
use crate::v1::auth::google::google_oauth_service::{AuthRequest, GoogleOauthService, GoogleOauthServiceImpl};
use imphnen_entities::error_dto::error::Error;
use crate::v1::auth::AuthLoginResponsetDto;
use crate::AppState;
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct GoogleAuthUrlResponse {
pub authorize_url: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GoogleLoginRequest {
pub redirect_uri: Option<String>,
}
pub struct GoogleOauthController<T> {
google_oauth_service: T,
}
impl GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
pub fn new() -> Self {
let google_oauth_service = GoogleOauthServiceImpl::<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>::with_services(
crate::v1::auth::auth_service::AuthService {},
crate::v1::users::users_service::UsersService {},
&ENV, // Pass a reference to the global ENV static
);
Self::with_service(google_oauth_service)
}
}
impl<T> GoogleOauthController<T>
where
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone + Send + Sync + 'static,
{
pub fn with_service(google_oauth_service: T) -> Self {
Self {
google_oauth_service,
}
}
pub fn get_routes(&self) -> Router {
Router::new()
.route(
"/login",
get(
move |State(controller): State<Arc<Self>>, Query(params): Query<GoogleLoginRequest>| async move {
controller.google_oauth_login(params).await
},
),
)
.route(
"/callback",
get(
move |State(controller): State<Arc<Self>>, Extension(app_state): Extension<AppState>, Query(auth_request): Query<AuthRequest>| async move {
let controller = Arc::clone(&controller);
controller.google_oauth_callback(auth_request, &app_state).await
},
),
)
.with_state(Arc::new(self.clone()))
}
pub async fn google_oauth_login(&self, params: GoogleLoginRequest) -> Result<Redirect, Error> {
let (authorize_url, _csrf_state) = self.google_oauth_service.generate_auth_url(params.redirect_uri);
Ok(Redirect::to(authorize_url.as_str()))
}
pub async fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Result<Json<AuthLoginResponsetDto>, Error> {
let (user, token) = self.google_oauth_service.google_oauth_callback(auth_request, app_state).await?;
let auth_response = AuthLoginResponsetDto {
user,
token,
};
Ok(Json(auth_response))
}
}
impl<T> Clone for GoogleOauthController<T>
where
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone,
{
fn clone(&self) -> Self {
Self::with_service(self.google_oauth_service.clone())
}
}
impl Default for GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
fn default() -> Self {
Self::new()
}
}
@@ -1,24 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct GoogleUser {
pub id: String,
pub email: String,
#[serde(default)]
pub verified_email: bool,
pub name: Option<String>,
pub given_name: Option<String>,
pub family_name: Option<String>,
pub picture: Option<String>,
pub locale: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GoogleTokenResponse {
pub access_token: String,
pub expires_in: u64,
pub refresh_token: Option<String>,
pub scope: String,
pub token_type: String,
pub id_token: String,
}
@@ -1,379 +0,0 @@
use std::pin::Pin;
use std::future::Future;
use anyhow::Result;
// Type alias to reduce clippy type_complexity warnings for long Future signatures
type GoogleOauthCallbackFut<'a> = Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + 'a>>;
use oauth2::{
AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier,
RedirectUrl, Scope, TokenUrl,
};
use serde::{Deserialize, Serialize};
use oauth2::url::Url;
use oauth2::TokenResponse;
use tracing::{info, error};
use imphnen_entities::error_dto::error::Error;
use imphnen_libs::{jsonwebtoken::{encode_access_token, encode_refresh_token}, environment::Env, AppState};
use crate::{generate_oauth_csrf_token, validate_oauth_csrf_token, validate_csrf_token};
use crate::v1::auth::TokenDto;
use crate::v1::auth::auth_service::AuthServiceTrait;
use crate::v1::users::users_dto::{UsersDetailItemDto, UsersCreateRequestDto};
use crate::v1::users::users_service::UsersServiceTrait;
use super::google_oauth_dto::GoogleUser;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AuthRequest {
pub code: String,
pub state: String,
pub redirect_uri: Option<String>,
}
impl AuthRequest {
/// Validate the OAuth callback request
pub fn validate(&self) -> Result<(), Error> {
// Validate code parameter
if self.code.is_empty() || self.code.len() > 2048 {
return Err(Error::Validation("Invalid authorization code".to_string()));
}
// Validate state parameter
if self.state.is_empty() || self.state.len() > 512 {
return Err(Error::Validation("Invalid state parameter".to_string()));
}
// Basic format validation for authorization code
// OAuth 2.0 authorization codes can contain URL-safe characters including base64 characters
if !self.code.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' || c == '/' || c == '+' || c == '=') {
return Err(Error::Validation("Authorization code contains invalid characters".to_string()));
}
Ok(())
}
/// Validate CSRF state token with signature verification and extract PKCE verifier
pub fn validate_csrf_state_and_get_pkce_verifier(&self, secret: &str) -> Result<PkceCodeVerifier, Error> {
// Maximum age of 30 minutes for OAuth flow (increased from 10)
const MAX_AGE_SECONDS: u64 = 300; // Changed from 30 minutes (1800s) to 5 minutes (300s)
let pkce_verifier_secret = validate_oauth_csrf_token(&self.state, secret, MAX_AGE_SECONDS)
.map_err(|e| {
error!("OAuth CSRF validation failed: {:?}", e);
Error::Auth("Invalid or expired OAuth CSRF state token".to_string())
})?;
Ok(PkceCodeVerifier::new(pkce_verifier_secret))
}
/// Validate CSRF state token with signature verification (legacy method for backward compatibility)
pub fn validate_csrf_state(&self, secret: &str) -> Result<(), Error> {
// Try OAuth CSRF validation first, if it fails, fall back to regular CSRF validation
match validate_oauth_csrf_token(&self.state, secret, 1800) {
Ok(_) => Ok(()),
Err(_) => {
// Fallback to regular CSRF validation for backward compatibility
validate_csrf_token(&self.state, secret, 600)
.map_err(|e| {
error!("CSRF validation failed: {:?}", e);
Error::Auth("Invalid or expired CSRF state token".to_string())
})
}
}
}
}
use crate::{RolesRepository, RolesEnum};
/// Helper function to get default role ID for new OAuth users
async fn get_default_role_id(app_state: &AppState) -> Result<String, Error> {
let role_repo = RolesRepository::new(app_state);
match role_repo.query_role_by_name(RolesEnum::User.to_string()).await {
Ok(role) => {
info!("Using default User role ID: {}", role.id);
Ok(role.id)
},
Err(e) => {
error!("Failed to retrieve User role: {:?}", e);
Err(Error::Anyhow(anyhow::Error::msg("Failed to get default role ID".to_string())))
}
}
}
pub trait GoogleOauthService<A: AuthServiceTrait + Send + Sync + 'static, U: UsersServiceTrait + Send + Sync + 'static>: Send + Sync + 'static {
// Removed new() from trait
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self;
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken);
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> GoogleOauthCallbackFut<'_>; // Changed return type
}
#[derive(Clone)]
pub struct GoogleOauthServiceImpl<A: AuthServiceTrait, U: UsersServiceTrait> {
users_service: U,
env: &'static Env,
_auth_service: A,
}
impl GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> {
/// Generate Google OAuth authorization URL
pub fn get_auth_url(&self, custom_redirect_uri: Option<String>) -> String {
let (auth_url, _csrf_token) = self.generate_auth_url(custom_redirect_uri);
auth_url.to_string()
}
}
impl<A, U> GoogleOauthService<A, U> for GoogleOauthServiceImpl<A, U>
where
A: AuthServiceTrait + Send + Sync + 'static,
U: UsersServiceTrait + Send + Sync + 'static,
{
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self {
Self {
_auth_service: auth_service,
users_service,
env,
}
}
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken) {
let google_client_id = ClientId::new(self.env.google_client_id.clone());
let google_client_secret = ClientSecret::new(self.env.google_client_secret.clone());
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
.expect("Invalid authorization endpoint URL");
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
.expect("Invalid token endpoint URL");
let redirect_uri = custom_redirect_uri.unwrap_or_else(|| self.env.google_redirect_url.clone());
let client = oauth2::basic::BasicClient::new(google_client_id)
.set_client_secret(google_client_secret)
.set_auth_uri(auth_url)
.set_token_uri(token_url)
.set_redirect_uri(
RedirectUrl::new(redirect_uri.clone())
.expect("Invalid redirect URL"),
);
info!("OAuth client configured with redirect URI: {}", redirect_uri);
let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
info!("Generated PKCE Code Challenge: {}", pkce_code_challenge.as_str());
info!("Generated PKCE Code Verifier: {}", pkce_code_verifier.secret());
// Generate a signed CSRF token with PKCE verifier for stateless validation
let csrf_token_str = generate_oauth_csrf_token(&self.env.access_token_secret, pkce_code_verifier.secret())
.unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()); // Fallback to UUID if signing fails
let (auth_url, csrf_token) = client
.authorize_url(|| CsrfToken::new(csrf_token_str.clone()))
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.email".to_string()))
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.profile".to_string()))
.set_pkce_challenge(pkce_code_challenge)
.url();
(auth_url, csrf_token)
}
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + '_>> {
let self_clone = self; // Use reference instead of clone
let app_state = app_state.to_owned();
Box::pin(async move {
// Validate input parameters first
info!("Received OAuth callback request with state: {}", auth_request.state);
auth_request.validate()?;
// CRITICAL: Validate CSRF state token and extract PKCE verifier
let pkce_verifier = auth_request.validate_csrf_state_and_get_pkce_verifier(&self_clone.env.access_token_secret)?;
info!("Starting Google OAuth callback process");
info!("Redirect URI used: {:?}", auth_request.redirect_uri);
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
// Use the SAME redirect URI that was used for auth URL generation
// This is crucial for OAuth security and consistency
let google_client_id = ClientId::new(self_clone.env.google_client_id.clone());
let google_client_secret = ClientSecret::new(self_clone.env.google_client_secret.clone());
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
.expect("Invalid authorization endpoint URL");
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
.expect("Invalid token endpoint URL");
let redirect_uri = auth_request.redirect_uri.clone().unwrap_or_else(|| self_clone.env.google_redirect_url.clone());
let client = oauth2::basic::BasicClient::new(google_client_id)
.set_client_secret(google_client_secret)
.set_auth_uri(auth_url)
.set_token_uri(token_url)
.set_redirect_uri(
RedirectUrl::new(redirect_uri.clone())
.expect("Invalid redirect URL"),
);
info!("OAuth client configured with redirect URI: {}", redirect_uri);
// Debug the OAuth client configuration
let effective_redirect_uri = auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url);
info!("Effective redirect URI for OAuth client: {}", effective_redirect_uri);
info!("Google Client ID: {}", self_clone.env.google_client_id);
info!("Attempting to exchange authorization code with Google");
info!("Using PKCE verifier for secure exchange");
info!("Authorization code length: {}", auth_request.code.len());
let token_response = client
.exchange_code(oauth2::AuthorizationCode::new(auth_request.code.clone()))
.set_pkce_verifier(pkce_verifier)
.request_async(&reqwest::Client::new())
.await
.map_err(|e| {
error!("Failed to exchange OAuth code with Google: {}", e);
error!("OAuth code was: {}", auth_request.code);
error!("Redirect URI was: {:?}", auth_request.redirect_uri);
// Debug OAuth client configuration
error!("Google Client ID: {}", self_clone.env.google_client_id);
error!("OAuth client redirect URI configured: {}",
auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url));
// Try to extract more details from the error
match &e {
oauth2::RequestTokenError::ServerResponse(response) => {
error!("Google OAuth Server Response Error: {:?}", response);
},
oauth2::RequestTokenError::Request(req_err) => {
error!("Google OAuth Request Error: {:?}", req_err);
},
oauth2::RequestTokenError::Parse(parse_err, response_body) => {
error!("Google OAuth Parse Error: {:?}", parse_err);
error!("Response body: {:?}", response_body);
},
oauth2::RequestTokenError::Other(other) => {
error!("Google OAuth Other Error: {:?}", other);
},
}
Error::Auth("Authentication error: Failed to exchange authorization code".to_string())
})?;
info!("Successfully exchanged authorization code for access token");
// Extract access token from Google's response
let access_token = token_response.access_token().secret();
info!("Obtained access token from Google, fetching user info...");
let client = reqwest::Client::new();
let user_info_url = "https://www.googleapis.com/oauth2/v2/userinfo";
let google_user: GoogleUser = client
.get(user_info_url)
.bearer_auth(access_token)
.send()
.await
.map_err(|e| {
error!("Failed to fetch user info from Google: {}", e);
Error::Auth("Failed to fetch user information".to_string())
})?
.json()
.await
.map_err(|e| {
error!("Failed to parse user info from Google: {}", e);
Error::Auth("Failed to parse user information".to_string())
})?;
info!("Successfully retrieved user info for email: {}", google_user.email);
info!("Google user picture URL: {:?}", google_user.picture);
info!("Google user data: name={:?}, given_name={:?}, family_name={:?}, picture={:?}",
google_user.name, google_user.given_name, google_user.family_name, google_user.picture);
let user = self_clone.users_service.get_user_by_email(&google_user.email, &app_state).await?;
let user = match user {
Some(mut user) => {
info!("Existing user found for email: {}", google_user.email);
// Update avatar if user doesn't have one and Google provides one
if user.avatar.is_none() && google_user.picture.is_some() {
info!("Updating avatar for existing user: {}", google_user.email);
match U::update_user_avatar(&google_user.email, google_user.picture.clone(), &app_state).await {
Ok(_) => {
info!("Successfully updated avatar for user: {}", google_user.email);
user.avatar = google_user.picture.clone();
},
Err(e) => {
error!("Failed to update avatar for user {}: {:?}", google_user.email, e);
}
}
}
user
},
None => {
info!("Creating new user for email: {}", google_user.email);
// Get default role ID using robust lookup
let default_role_id = get_default_role_id(&app_state).await
.map_err(|e| {
error!("Failed to get default role ID: {:?}", e);
Error::Anyhow(anyhow::Error::msg("Failed to get default role ID for new user".to_string()))
})?;
let new_user = UsersCreateRequestDto {
email: google_user.email.clone(),
password: format!("GOOGLE_OAUTH_{}", uuid::Uuid::new_v4()), // Random placeholder
fullname: google_user.name.clone().unwrap_or_else(|| {
// Fallback: use given_name + family_name if available, otherwise use email prefix
match (&google_user.given_name, &google_user.family_name) {
(Some(given), Some(family)) => format!("{} {}", given, family),
(Some(given), None) => given.clone(),
(None, Some(family)) => family.clone(),
(None, None) => {
// Extract email prefix as last resort
google_user.email.split('@').next().unwrap_or("User").to_string()
}
}
}),
is_active: true,
role_id: default_role_id,
avatar: google_user.picture.clone(), // Set avatar from Google user picture
};
self_clone.users_service.create_user_by_dto(new_user, &app_state).await?
}
};
let access_token = encode_access_token(user.email.clone(), user.id.clone())
.map_err(|e| {
error!("Failed to generate access token for {}: {:?}", user.email, e);
Error::Auth("Failed to generate access token".to_string())
})?;
let refresh_token = encode_refresh_token(user.email.clone(), user.id.clone())
.map_err(|e| {
error!("Failed to generate refresh token for {}: {:?}", user.email, e);
Error::Auth("Failed to generate refresh token".to_string())
})?;
let token_dto = TokenDto {
access_token,
refresh_token,
};
// Cache the user in auth repository for subsequent requests
let _auth_repo = crate::v1::auth::AuthRepository::new(&app_state);
let _user_query_dto: imphnen_entities::UsersDetailQueryDto = (&user).into();
// if let Err(err_store) = auth_repo.query_store_user(user_query_dto).await {
// error!(
// "Failed to store user cache for {}: {}",
// user.email, err_store
// );
// // Don't fail the login, just log the error
// error!("Google OAuth login succeeded but caching failed for user: {}", user.email);
// } else {
info!("Successfully cached user {} after Google OAuth login", user.email);
// }
info!("Successfully completed Google OAuth for user: {}", user.email);
Ok((user, token_dto))
})
}
}
-7
View File
@@ -1,7 +0,0 @@
/// Google OAuth integration module
pub mod google_oauth_controller;
pub mod google_oauth_dto;
pub mod google_oauth_service;
// Export only essential types and functions from Google OAuth submodules
pub use google_oauth_controller::GoogleOauthController;
-51
View File
@@ -1,51 +0,0 @@
use axum::{Router, routing::post};
pub mod auth_controller;
pub mod auth_dto;
pub mod auth_repository;
pub mod auth_schema;
pub mod auth_service;
pub mod google;
// Export only the essential types and functions from each submodule
pub use auth_dto::{
AuthLoginRequestDto,
AuthLoginResponsetDto,
AuthRegisterRequestDto,
AuthResendOtpRequestDto,
AuthVerifyEmailRequestDto,
AuthNewPasswordRequestDto,
AuthRefreshTokenRequestDto,
TokenDto,
UserCacheSchema,
};
pub use auth_repository::AuthRepository;
pub use imphnen_libs::AuthRepositoryTrait;
pub use auth_schema::AuthOtpSchema;
pub use auth_service::AuthServiceTrait;
// Export controller functions that are used in routing
pub use auth_controller::{
post_login,
post_login_mentor,
post_register,
post_forgot_password,
post_new_password,
post_refresh_token,
post_resend_otp,
post_verify_email
};
pub fn auth_router() -> Router {
Router::new()
.nest("/google", google::google_oauth_controller::GoogleOauthController::new().get_routes())
.route("/forgot", post(post_forgot_password))
.route("/login", post(post_login))
.route("/login-mentor", post(post_login_mentor))
.route("/new-password", post(post_new_password))
.route("/refresh", post(post_refresh_token))
.route("/register", post(post_register))
.route("/send-otp", post(post_resend_otp))
.route("/verify-email", post(post_verify_email))
}
-27
View File
@@ -1,27 +0,0 @@
use axum::Router;
pub mod auth;
pub mod permissions;
pub mod roles;
pub mod users;
// Export only the essential router functions from each module
pub use auth::auth_router;
pub use permissions::{permissions_router, permissions_dto, permissions_service, permissions_guard};
pub use roles::{roles_router, roles_service};
pub use users::users_router;
// Main route constructors
pub fn iam_public_routes() -> Router {
Router::new().nest("/auth", auth_router())
}
pub fn iam_protected_routes() -> Router {
Router::new()
.nest("/users", users_router())
.nest("/users/admin", users::admin_users_router())
.nest("/roles", roles_router())
.nest("/roles/admin", roles::admin_roles_router())
.nest("/permissions", permissions_router())
.nest("/permissions/admin", permissions::admin_permissions_router())
}
-47
View File
@@ -1,47 +0,0 @@
use axum::{
Router,
routing::{delete, get, post, put},
};
pub mod permissions_controller;
pub mod permissions_dto;
pub mod permissions_enum;
pub mod permissions_guard;
pub mod permissions_repository;
pub mod permissions_schema;
pub mod permissions_service;
// Export only essential types and functions from each submodule
pub use permissions_controller::{
get_permission_list,
get_permission_by_id,
post_create_permission,
put_update_permission,
delete_permission
};
pub use permissions_dto::{
PermissionsRequestDto,
PermissionsUpdateRequestDto,
};
pub use permissions_enum::PermissionsEnum;
pub use permissions_guard::permissions_guard;
pub use permissions_repository::PermissionsRepository;
pub use permissions_schema::PermissionsSchema;
pub fn permissions_router() -> Router {
Router::new()
.route("/", get(get_permission_list))
.route("/create", post(post_create_permission))
.route("/detail/{id}", get(get_permission_by_id))
.route("/update/{id}", put(put_update_permission))
.route("/delete/{id}", delete(delete_permission))
}
// Minimal admin router to satisfy test expectations at /v1/permissions/admin
pub fn admin_permissions_router() -> Router {
use permissions_controller as controller;
Router::new()
.route("/", axum::routing::get(controller::get_permission_list))
.route("/detail/{id}", axum::routing::get(controller::get_permission_by_id))
}
@@ -1,170 +0,0 @@
use axum::{
Extension, Json,
extract::{Path, Query},
response::IntoResponse,
};
use crate::{
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
ResponseSuccessDto,
v1::{
permissions_dto::{PermissionsRequestDto, PermissionsUpdateRequestDto},
permissions_service::PermissionsService,
},
};
use super::{PermissionsEnum, permissions_guard};
use imphnen_entities::PermissionsItemDto;
#[utoipa::path(
get,
path = "/v1/permissions",
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 = "Get permission list", body = ResponseListSuccessDto<Vec<PermissionsItemDto>>)
),
tag = "Permissions"
)]
pub async fn get_permission_list(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Query(meta): Query<MetaRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadListPermissions],
)
.await
{
Ok((_claims, state)) => PermissionsService::get_permission_list(&state, meta).await,
Err(response) => response,
}
}
#[utoipa::path(
get,
path = "/v1/permissions/detail/{id}",
security(
("Bearer" = [])
),
params(("id" = String, Path, description = "Permission ID")),
responses(
(status = 200, description = "Get permission by ID", body = ResponseSuccessDto<PermissionsItemDto>)
),
tag = "Permissions"
)]
pub async fn get_permission_by_id(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadDetailPermissions],
)
.await
{
Ok((_claims, state)) => PermissionsService::get_permission_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/permissions/create",
request_body = PermissionsRequestDto,
responses(
(status = 201, description = "Create new permission", body = MessageResponseDto)
),
tag = "Permissions"
)]
pub async fn post_create_permission(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<PermissionsRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::CreatePermissions],
)
.await
{
Ok((_claims, state)) => PermissionsService::create_role(&state, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
put,
security(
("Bearer" = [])
),
path = "/v1/permissions/update/{id}",
request_body = PermissionsUpdateRequestDto,
responses(
(status = 200, description = "Update permission", body = MessageResponseDto)
),
tag = "Permissions"
)]
pub async fn put_update_permission(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
Json(payload): Json<PermissionsUpdateRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::UpdatePermissions],
)
.await
{
Ok((_claims, state)) => PermissionsService::update_permission(&state, payload, id).await,
Err(response) => response,
}
}
#[utoipa::path(
delete,
security(
("Bearer" = [])
),
path = "/v1/permissions/delete/{id}",
responses(
(status = 200, description = "Delete permission", body = MessageResponseDto)
),
tag = "Permissions"
)]
pub async fn delete_permission(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::DeletePermissions],
)
.await
{
Ok((_claims, state)) => PermissionsService::delete_permission(&state, id).await,
Err(response) => response,
}
}
@@ -1,16 +0,0 @@
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::Validate;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct PermissionsRequestDto {
#[validate(length(min = 1, message = "Permission name must not be empty"))]
pub name: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct PermissionsUpdateRequestDto {
#[validate(length(min = 1, message = "Permission name must not be empty"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
@@ -1 +0,0 @@
pub use imphnen_entities::PermissionsEnum;
@@ -1,102 +0,0 @@
use super::PermissionsEnum;
use crate::{AppState, common_response, decode_access_token, UsersRepository};
use axum::{
http::{HeaderMap, StatusCode},
response::Response, Extension,
};
use axum_extra::headers::{authorization::Bearer, Authorization, HeaderMapExt};
use uuid::Uuid;
pub async fn permissions_guard(
headers: HeaderMap,
Extension(state): Extension<AppState>,
required_permissions: Vec<PermissionsEnum>,
) -> Result<(imphnen_libs::jsonwebtoken::Claims, AppState), Response> {
let auth_header = headers
.typed_get::<Authorization<Bearer>>()
.ok_or_else(|| {
common_response(
StatusCode::UNAUTHORIZED,
"Invalid or missing authorization token",
)
})?;
let token = auth_header.token();
let claims = decode_access_token(token)
.map_err(|_| {
common_response(
StatusCode::UNAUTHORIZED,
"Invalid or expired token",
)
})?
.claims;
// Fetch user from database to get permissions. Try email first, then try using the sub as a user id.
let user_repo = UsersRepository::new(&state);
let user = match user_repo.query_user_by_email(claims.sub.clone()).await {
Ok(u) => u,
Err(_) => {
// Try treat claims.sub as a UUID (user id)
let user_id = Uuid::parse_str(&claims.sub).map_err(|_| {
common_response(StatusCode::UNAUTHORIZED, "Invalid user ID format")
})?;
match user_repo.query_user_by_id(&user_id.to_string()).await {
Ok(u2) => u2,
Err(_) => {
return Err(common_response(
StatusCode::UNAUTHORIZED,
"User not found",
));
}
}
}
};
// Check permissions from database: collect both names and raw ids so checks
// succeed whether permissions are stored by name or by UUID.
let user_permissions: Vec<String> = user
.role
.permissions
.as_ref()
.unwrap_or(&vec![])
.iter()
.filter_map(|p| p.as_ref())
.flat_map(|pp| {
let mut res: Vec<String> = Vec::new();
if let Some(name) = pp.name.clone() {
res.push(name);
}
if let Some(id) = pp.id.as_ref().map(|id| id.to_string()) {
res.push(id);
}
res
})
.collect();
// If user has Administrator permission, allow all.
// Accept either the permission name or the canonical permission id.
let admin_name = PermissionsEnum::Administrator.to_string();
let admin_id = PermissionsEnum::Administrator.id();
if user_permissions.contains(&admin_name) || user_permissions.contains(&admin_id) {
return Ok((claims, state));
}
for required in &required_permissions {
let required_str = required.to_string();
let required_id = required.id();
if !user_permissions.contains(&required_str) && !user_permissions.contains(&required_id) {
eprintln!(" MISSING REQUIRED PERMISSION: {required_str} (ID: {required_id})");
eprintln!(" USER PERMISSIONS: {:?}", user_permissions);
return Err(common_response(
StatusCode::FORBIDDEN,
"You don't have the required permissions",
));
}
}
Ok((claims, state))
}
@@ -1,282 +0,0 @@
use imphnen_entities::{PermissionsItemDto, MetaRequestDto, ResponseListSuccessDto};
use super::PermissionsSchema;
use crate::{AppState};
use imphnen_libs::AppStatePostgresExt;
use imphnen_entities::seaorm::auth::permissions::Entity as PermissionsEntity;
use sea_orm::{EntityTrait, QueryFilter, ColumnTrait, QueryOrder, PaginatorTrait, QuerySelect, ActiveModelTrait, ActiveValue};
use anyhow::{Result, bail};
use std::time::Instant;
use tracing::instrument;
use tracing::info;
use uuid::Uuid;
pub struct PermissionsRepository<'a> {
state: &'a AppState,
}
impl<'a> PermissionsRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
#[instrument(skip(self, meta), err)]
pub async fn query_permission_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<PermissionsItemDto>>> {
let now = Instant::now();
info!("Executing SeaORM query for Permissions list with meta: {:?}", meta);
let db = self.state.postgres_db();
// Build base query
let mut query = PermissionsEntity::find()
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false));
// Apply search if provided
if let Some(search) = &meta.search {
query = query.filter(imphnen_entities::seaorm::auth::permissions::Column::Name.contains(search));
}
// Apply ordering
let order_column = match meta.sort_by.as_deref() {
Some("name") => imphnen_entities::seaorm::auth::permissions::Column::Name,
Some("created_at") => imphnen_entities::seaorm::auth::permissions::Column::CreatedAt,
_ => imphnen_entities::seaorm::auth::permissions::Column::CreatedAt,
};
query = match meta.order.as_deref() {
Some("desc") => query.order_by_desc(order_column),
_ => query.order_by_asc(order_column),
};
// Get total count for pagination
let total_count = query.clone().count(db).await?;
// Apply pagination
let page = meta.page.unwrap_or(1);
let per_page = meta.per_page.unwrap_or(10);
let offset = (page - 1) * per_page;
let permissions = query
.offset(offset)
.limit(per_page)
.all(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
println!("Query 'query_permission_list' took: {elapsed:.2?}");
}
let transformed_data = permissions
.into_iter()
.map(|permission| PermissionsItemDto {
id: permission.id.to_string(),
name: permission.name,
created_at: Some(permission.created_at.to_rfc3339()),
updated_at: Some(permission.updated_at.to_rfc3339()),
})
.collect();
Ok(ResponseListSuccessDto {
data: transformed_data,
meta: Some(imphnen_entities::MetaResponseDto {
page: Some(page),
per_page: Some(per_page),
total: Some(total_count),
}),
})
}
#[instrument(skip(self, id), err)]
pub async fn query_permission_by_id(
&self,
id: String,
) -> Result<PermissionsSchema> {
let now = Instant::now();
let db = self.state.postgres_db();
info!(id = %id, "Executing SeaORM select for Permissions");
let permission_id = Uuid::parse_str(&id)?;
let permission = PermissionsEntity::find_by_id(permission_id)
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false))
.one(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
println!("Query 'query_permission_by_id' took: {elapsed:.2?}");
}
match permission {
Some(permission) => Ok(PermissionsSchema {
id: permission.id,
name: permission.name,
is_deleted: permission.is_deleted,
created_at: Some(permission.created_at.to_rfc3339()),
updated_at: Some(permission.updated_at.to_rfc3339()),
}),
None => bail!("Permission not found"),
}
}
#[instrument(skip(self, id), err)]
pub async fn transformed_query_permission_by_id(
&self,
id: String,
) -> Result<PermissionsItemDto> {
let now = Instant::now();
info!(id = %id, "Executing transformed_query_permission_by_id (delegates to query_permission_by_id)");
let raw_result = self.query_permission_by_id(id.clone()).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
println!("Query 'transformed_query_permission_by_id' took: {elapsed:.2?}");
}
let transformed_data = PermissionsItemDto {
id: raw_result.id.to_string(),
name: raw_result.name,
created_at: raw_result.created_at,
updated_at: raw_result.updated_at,
};
Ok(transformed_data)
}
#[instrument(skip(self, name), err)]
pub async fn query_permission_by_name(
&self,
name: String,
) -> Result<PermissionsSchema> {
let now = Instant::now();
let db = self.state.postgres_db();
info!(name = %name, "Executing SeaORM query for permission by name");
let permission = PermissionsEntity::find_by_name(&name)
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false))
.one(db)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
println!("Query 'query_permission_by_name' took: {elapsed:.2?}");
}
match permission {
Some(permission) => Ok(PermissionsSchema {
id: permission.id,
name: permission.name,
is_deleted: permission.is_deleted,
created_at: Some(permission.created_at.to_rfc3339()),
updated_at: Some(permission.updated_at.to_rfc3339()),
}),
None => bail!("Permission not found"),
}
}
#[instrument(skip(self, data), err)]
pub async fn query_create_permission(
&self,
data: PermissionsSchema,
) -> Result<String> {
let now = Instant::now();
let db = self.state.postgres_db();
info!("Executing SeaORM create for Permissions with data: {:?}", data);
let active_model = imphnen_entities::seaorm::auth::permissions::ActiveModel {
id: ActiveValue::Set(data.id),
name: ActiveValue::Set(data.name),
is_deleted: ActiveValue::Set(data.is_deleted),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
};
let result = PermissionsEntity::insert(active_model).exec(db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
println!("Query 'query_create_permission' took: {elapsed:.2?}");
}
Ok(format!("Success create permission with id: {}", result.last_insert_id))
}
#[instrument(skip(self, data), err)]
pub async fn query_update_permission(
&self,
data: PermissionsSchema,
) -> Result<String> {
let now = Instant::now();
let db = self.state.postgres_db();
// Check if permission exists and is not deleted
let existing = self.query_permission_by_id(data.id.to_string()).await?;
if existing.is_deleted {
bail!("Permission already deleted");
}
info!(id = %data.id, "Executing SeaORM update for Permissions");
let active_model = imphnen_entities::seaorm::auth::permissions::ActiveModel {
id: ActiveValue::Set(data.id),
name: ActiveValue::Set(data.name),
is_deleted: ActiveValue::Set(data.is_deleted),
created_at: ActiveValue::Unchanged(existing.created_at.map(|s| {
chrono::DateTime::parse_from_rfc3339(&s)
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))
.unwrap()
.with_timezone(&chrono::Utc)
})
.unwrap_or(chrono::Utc::now())),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
};
let result = active_model.update(db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
println!("Query 'query_update_permission' took: {elapsed:.2?}");
}
Ok(format!("Success update permission with id: {}", result.id))
}
#[instrument(skip(self, id), err)]
pub async fn query_delete_permission(&self, id: String) -> Result<String> {
let now = Instant::now();
let db = self.state.postgres_db();
let permission_id = Uuid::parse_str(&id)?;
// Check if permission exists and is not deleted
let permission = PermissionsEntity::find_by_id(permission_id)
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false))
.one(db)
.await?;
let _permission = match permission {
Some(p) => p,
None => bail!("Permission not found"),
};
info!(id = %id, "Executing SeaORM soft delete for Permissions");
let active_model = imphnen_entities::seaorm::auth::permissions::ActiveModel {
id: ActiveValue::Set(permission_id),
is_deleted: ActiveValue::Set(true),
deleted_at: ActiveValue::Set(Some(chrono::Utc::now())),
..Default::default()
};
let result = active_model.update(db).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
println!("Query 'query_delete_permission' took: {elapsed:.2?}");
}
Ok(format!("Success delete permission with id: {}", result.id))
}
}
@@ -1,52 +0,0 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use imphnen_entities::{PermissionsItemDto, PermissionsQueryDto};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PermissionsSchema {
pub id: Uuid,
pub name: String,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for PermissionsSchema {
fn default() -> Self {
Self {
id: Uuid::new_v4(),
name: String::new(),
is_deleted: false,
created_at: None,
updated_at: None,
}
}
}
impl PermissionsSchema {
pub fn list(&self) -> PermissionsItemDto {
PermissionsItemDto {
id: self.to_string(),
name: self.name.clone(),
created_at: self.created_at.clone(),
updated_at: self.updated_at.clone(),
}
}
pub fn from(dto: PermissionsQueryDto) -> Self {
Self {
id: Uuid::parse_str(&dto.id.unwrap_or_default()).unwrap_or(Uuid::new_v4()),
name: dto.name.unwrap_or_default(),
is_deleted: false,
created_at: dto.created_at,
updated_at: dto.updated_at,
}
}
}
impl std::fmt::Display for PermissionsSchema {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.id)
}
}
@@ -1,125 +0,0 @@
use crate::{
AppState, MetaRequestDto, PermissionsRepository, PermissionsSchema, ResourceEnum,
ResponseListSuccessDto, ResponseSuccessDto, common_response,
success_list_response, success_response, validate_request,
};
use axum::http::StatusCode;
use axum::response::Response;
use crate::get_iso_date;
use imphnen_utils::make_thing;
use uuid::Uuid;
use super::{PermissionsRequestDto, PermissionsUpdateRequestDto};
pub struct PermissionsService;
impl PermissionsService {
pub async fn get_permission_list(
state: &AppState,
meta: MetaRequestDto,
) -> Response {
let repo = PermissionsRepository::new(state);
match repo.query_permission_list(meta).await {
Ok(data) => {
let response = ResponseListSuccessDto {
data: data.data,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn get_permission_by_id(state: &AppState, id: String) -> Response {
let repo = PermissionsRepository::new(state);
match repo.transformed_query_permission_by_id(id).await {
Ok(permission) => success_response(ResponseSuccessDto { data: permission }),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_role(
state: &AppState,
payload: PermissionsRequestDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = PermissionsRepository::new(state);
match repo.query_permission_by_name(payload.name.clone()).await {
Ok(_role) => {
return common_response(
StatusCode::CONFLICT,
"Permission name already exists",
);
}
Err(err) if err.to_string().contains("not found") => {}
Err(e) => {
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
}
}
match repo
.query_create_permission(PermissionsSchema {
name: payload.name,
..Default::default()
})
.await
{
Ok(msg) => common_response(StatusCode::CREATED, &msg),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn update_permission(
state: &AppState,
payload: PermissionsUpdateRequestDto,
id: String,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = PermissionsRepository::new(state);
// Get current permission data first
let _thing_id = make_thing(&ResourceEnum::Permissions.to_string(), &id);
let current_permission = match repo.query_permission_by_id(id.clone()).await {
Ok(permission) => permission,
Err(_) => return common_response(StatusCode::NOT_FOUND, "Permission not found"),
};
let mut updated_permission = current_permission;
updated_permission.id = Uuid::parse_str(&id).unwrap_or_else(|_| Uuid::new_v4());
updated_permission.updated_at = Some(get_iso_date());
// Only update fields that are provided
if let Some(name) = payload.name {
updated_permission.name = name;
}
match repo.query_update_permission(updated_permission).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Permission not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
pub async fn delete_permission(state: &AppState, id: String) -> Response {
let repo = PermissionsRepository::new(state);
match repo.query_delete_permission(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => {
if e.to_string().contains("not found") {
common_response(StatusCode::NOT_FOUND, "Permission not found")
} else {
common_response(StatusCode::BAD_REQUEST, &e.to_string())
}
}
}
}
}
-49
View File
@@ -1,49 +0,0 @@
use axum::{
Router,
routing::{delete, get, post, put},
};
pub mod roles_controller;
pub mod roles_dto;
pub mod roles_enum;
pub mod roles_repository;
pub mod roles_schema;
pub mod roles_service;
// Export only essential types and functions from each submodule
pub use roles_controller::{
get_role_list,
get_role_by_id,
post_create_role,
put_update_role,
delete_role
};
pub use roles_dto::{
RolesRequestCreateDto,
RolesRequestUpdateDto,
RolesDetailItemDto,
RolesListItemDto,
RolesDetailQueryDto,
};
pub use roles_enum::RolesEnum;
pub use roles_repository::RolesRepository;
pub use roles_schema::RolesSchema;
pub fn roles_router() -> Router {
Router::new()
.route("/", get(get_role_list))
.route("/detail/{id}", get(get_role_by_id))
.route("/create", post(post_create_role))
.route("/update/{id}", put(put_update_role))
.route("/delete/{id}", delete(delete_role))
}
// Minimal admin router to satisfy test expectations at /v1/roles/admin
pub fn admin_roles_router() -> Router {
use roles_controller as controller;
Router::new()
.route("/", axum::routing::get(controller::get_role_list))
.route("/detail/{id}", axum::routing::get(controller::get_role_by_id))
}
@@ -1,167 +0,0 @@
use axum::{
Extension, Json,
extract::{Path, Query},
response::IntoResponse,
};
use super::{
RolesDetailItemDto, RolesListItemDto, RolesRequestCreateDto, RolesRequestUpdateDto,
};
use crate::{
AppState, MessageResponseDto, MetaRequestDto, PermissionsEnum,
ResponseListSuccessDto, ResponseSuccessDto, permissions_guard,
v1::roles_service::RolesService,
};
#[utoipa::path(
get,
security(
("Bearer" = [])
),
path = "/v1/roles",
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 = "Get role list", body = ResponseListSuccessDto<Vec<RolesListItemDto>>)
),
tag = "Roles"
)]
pub async fn get_role_list(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Query(meta): Query<MetaRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadListRoles],
)
.await
{
Ok((_claims, state)) => RolesService::get_role_list(&state, meta).await,
Err(response) => response,
}
}
#[utoipa::path(
get,
security(
("Bearer" = [])
),
path = "/v1/roles/detail/{id}",
params(("id" = String, Path, description = "Role ID")),
responses(
(status = 200, description = "Get role by ID", body = ResponseSuccessDto<RolesDetailItemDto>)
),
tag = "Roles"
)]
pub async fn get_role_by_id(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadDetailRoles],
)
.await
{
Ok((_claims, state)) => RolesService::get_role_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/roles/create",
request_body = RolesRequestCreateDto,
responses(
(status = 201, description = "Create new role", body = MessageResponseDto)
),
tag = "Roles"
)]
pub async fn post_create_role(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<RolesRequestCreateDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::CreateRoles],
)
.await
{
Ok((_claims, state)) => RolesService::create_role(&state, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
put,
security(
("Bearer" = [])
),
path = "/v1/roles/update/{id}",
request_body = RolesRequestUpdateDto,
responses(
(status = 200, description = "Update role", body = MessageResponseDto)
),
tag = "Roles"
)]
pub async fn put_update_role(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
Json(payload): Json<RolesRequestUpdateDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::UpdateRoles],
)
.await
{
Ok((_claims, state)) => RolesService::update_role(&state, id, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
delete,
security(
("Bearer" = [])
),
path = "/v1/roles/delete/{id}",
responses(
(status = 200, description = "Delete role", body = MessageResponseDto)
),
tag = "Roles"
)]
pub async fn delete_role(
headers: axum::http::HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::DeleteRoles],
)
.await
{
Ok((_claims, state)) => RolesService::delete_role(&state, id).await,
Err(response) => response,
}
}
-111
View File
@@ -1,111 +0,0 @@
use imphnen_entities::{PermissionsItemDto, PermissionsQueryDto, PermissionsEnum};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use uuid::Uuid;
use validator::Validate;
use strum::IntoEnumIterator;
use super::RolesSchema;
use imphnen_entities::seaorm::auth::roles::Model as RolesModel;
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct RolesRequestUpdateDto {
#[validate(length(min = 1, message = "Role name must not be empty"))]
pub name: Option<String>,
pub permissions: Option<Vec<String>>,
pub overwrite: Option<bool>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct RolesRequestCreateDto {
#[validate(length(min = 1, message = "Role name must not be empty"))]
pub name: String,
pub permissions: Vec<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct RolesListItemDto {
pub id: String,
pub name: String,
pub permissions_count: usize,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)] // Added Default derive
pub struct RolesDetailItemDto {
pub id: String,
pub name: String,
pub description: String,
pub is_system_role: bool,
pub is_default: bool,
pub permissions: Vec<PermissionsItemDto>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl From<&RolesModel> for RolesDetailItemDto {
fn from(model: &RolesModel) -> Self {
let schema = RolesSchema::from(model);
let mut permissions_dto = vec![];
if let Some(serde_json::Value::Array(perms)) = &model.permissions {
for p in perms {
if let Some(p_str) = p.as_str() {
// Find matching enum
for enum_val in PermissionsEnum::iter() {
if enum_val.to_string() == p_str {
permissions_dto.push(PermissionsItemDto {
id: enum_val.id(),
name: p_str.to_string(),
created_at: None,
updated_at: None,
});
break;
}
}
}
}
}
Self {
id: schema.id.to_string(),
name: schema.name.clone(),
description: schema.description.clone(),
is_system_role: schema.is_system_role,
is_default: schema.is_default,
permissions: permissions_dto,
created_at: Some(schema.created_at.clone()),
updated_at: Some(schema.updated_at.clone()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RolesDetailQueryDto {
pub id: Uuid,
pub name: String,
pub permissions: Option<Vec<Option<PermissionsQueryDto>>>,
pub is_deleted: bool,
pub created_at: Option<String>,
pub updated_at: Option<String>,
}
impl Default for RolesDetailQueryDto {
fn default() -> Self {
Self {
id: Uuid::new_v4(),
name: String::new(),
permissions: None,
is_deleted: false,
created_at: None,
updated_at: None,
}
}
}
impl std::fmt::Display for RolesDetailQueryDto {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.id)
}
}
-37
View File
@@ -1,37 +0,0 @@
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RolesEnum {
Admin,
Administrator, // Added Administrator role
User,
Staff,
Mentor, // Added Mentor role
}
impl fmt::Display for RolesEnum {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let roles_str = match self {
RolesEnum::Admin => "Admin",
RolesEnum::Administrator => "Administrator", // Added Administrator role
RolesEnum::User => "User",
RolesEnum::Staff => "Staff",
RolesEnum::Mentor => "Mentor", // Added Mentor role
};
write!(f, "{roles_str}")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_roles_enum_display() {
assert_eq!(format!("{}", RolesEnum::Admin), "Admin");
assert_eq!(format!("{}", RolesEnum::Administrator), "Administrator");
assert_eq!(format!("{}", RolesEnum::User), "User");
assert_eq!(format!("{}", RolesEnum::Staff), "Staff");
assert_eq!(format!("{}", RolesEnum::Mentor), "Mentor");
}
}
@@ -1,241 +0,0 @@
use super::{
RolesDetailItemDto, RolesListItemDto, RolesRequestCreateDto,
RolesRequestUpdateDto, RolesSchema,
};
use crate::{
AppState, MetaRequestDto, ResponseListSuccessDto,
};
use anyhow::Result;
use imphnen_entities::seaorm::auth::roles::{Entity as RolesEntity, Column as RolesColumn};
use sea_orm::{EntityTrait, QueryFilter, QueryOrder, PaginatorTrait, ActiveModelTrait, ActiveValue, DatabaseConnection, ColumnTrait, QuerySelect, Order};
use serde_json;
use std::time::Instant;
use uuid::Uuid;
use tracing::instrument;
pub struct RolesRepository<'a> {
state: &'a AppState,
}
impl<'a> RolesRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
fn db(&self) -> &DatabaseConnection {
&self.state.postgres_connection.conn
}
#[instrument(skip(self, meta), err)]
pub async fn query_role_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<RolesListItemDto>>> {
let now = Instant::now();
// Build SeaORM query
let mut query = RolesEntity::find()
.filter(RolesColumn::DeletedAt.is_null());
// Apply search filter
if let Some(search) = &meta.search {
query = query.filter(RolesColumn::Name.contains(search));
}
// Apply sorting
let sort_column = match meta.sort_by.as_deref() {
Some("name") => RolesColumn::Name,
Some("created_at") => RolesColumn::CreatedAt,
_ => RolesColumn::CreatedAt,
};
query = match meta.order.as_deref() {
Some("desc") => query.order_by(sort_column, Order::Desc),
_ => query.order_by(sort_column, Order::Asc),
};
// Get total count
let total_count = query.clone().count(self.db()).await?;
// Apply pagination
let page = meta.page.unwrap_or(1);
let per_page = meta.per_page.unwrap_or(10);
let offset = (page - 1) * per_page;
let roles = query
.offset(offset)
.limit(per_page)
.all(self.db())
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_role_list' took: {elapsed:.2?}");
}
let data = roles
.into_iter()
.map(|role| {
let schema = RolesSchema::from(&role);
schema.list()
})
.collect();
Ok(ResponseListSuccessDto {
data,
meta: Some(imphnen_entities::MetaResponseDto {
total: Some(total_count),
page: Some(page),
per_page: Some(per_page),
}),
})
}
#[instrument(skip(self, name), err)]
pub async fn query_role_by_name(
&self,
name: String,
) -> Result<RolesDetailItemDto> {
let now = Instant::now();
let role = RolesEntity::find()
.filter(RolesColumn::Name.eq(name))
.filter(RolesColumn::DeletedAt.is_null())
.one(self.db())
.await?
.ok_or_else(|| anyhow::anyhow!("Role not found"))?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_role_by_name' took: {elapsed:.2?}");
}
Ok(RolesDetailItemDto::from(&role))
}
#[instrument(skip(self, id), err)]
pub async fn query_role_by_id(&self, id: String) -> Result<RolesDetailItemDto> {
let now = Instant::now();
let role_id = Uuid::parse_str(&id)
.map_err(|_| anyhow::anyhow!("Invalid role ID"))?;
let role = RolesEntity::find_by_id(role_id)
.filter(RolesColumn::DeletedAt.is_null())
.one(self.db())
.await?
.ok_or_else(|| anyhow::anyhow!("Role not found"))?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_role_by_id' took: {elapsed:.2?}");
}
Ok(RolesDetailItemDto::from(&role))
}
#[instrument(skip(self, payload), err)]
pub async fn query_create_role(
&self,
payload: RolesRequestCreateDto,
) -> Result<RolesDetailItemDto> {
let now = Instant::now();
let role_id = Uuid::new_v4();
let permissions_json = serde_json::to_value(&payload.permissions)
.map_err(|e| anyhow::anyhow!("Failed to serialize permissions: {}", e))?;
let active_model = imphnen_entities::seaorm::auth::roles::ActiveModel {
id: ActiveValue::Set(role_id),
name: ActiveValue::Set(payload.name),
description: ActiveValue::Set("".to_string()), // Default description
is_system_role: ActiveValue::Set(false),
is_default: ActiveValue::Set(false),
permissions: ActiveValue::Set(Some(permissions_json)),
created_at: ActiveValue::Set(chrono::Utc::now()),
updated_at: ActiveValue::Set(chrono::Utc::now()),
deleted_at: ActiveValue::NotSet,
};
let created_role = active_model.insert(self.db()).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_create_role' took: {elapsed:.2?}");
}
// Return the created role
Ok(RolesDetailItemDto::from(&created_role))
}
#[instrument(skip(self, id, data), err)]
pub async fn query_update_role(
&self,
id: String,
data: RolesRequestUpdateDto,
) -> Result<String> {
let now = Instant::now();
let role_id = Uuid::parse_str(&id)
.map_err(|_| anyhow::anyhow!("Invalid role ID"))?;
let mut active_model = imphnen_entities::seaorm::auth::roles::ActiveModel {
id: ActiveValue::Unchanged(role_id),
..Default::default()
};
if let Some(name) = data.name {
active_model.name = ActiveValue::Set(name);
}
if let Some(permissions) = data.permissions {
let permissions_json = serde_json::to_value(&permissions)
.map_err(|e| anyhow::anyhow!("Failed to serialize permissions: {}", e))?;
active_model.permissions = ActiveValue::Set(Some(permissions_json));
}
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
let _updated_role = active_model.update(self.db()).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_update_role' took: {elapsed:.2?}");
}
Ok("Success update role".into())
}
#[instrument(skip(self, id), err)]
pub async fn query_delete_role(&self, id: String) -> Result<String> {
let now = Instant::now();
let role_id = Uuid::parse_str(&id)
.map_err(|_| anyhow::anyhow!("Invalid role ID"))?;
let active_model = imphnen_entities::seaorm::auth::roles::ActiveModel {
id: ActiveValue::Unchanged(role_id),
deleted_at: ActiveValue::Set(Some(chrono::Utc::now())),
..Default::default()
};
let _updated_role = active_model.update(self.db()).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_delete_role' took: {elapsed:.2?}");
}
Ok("Success delete role".into())
}
}
-50
View File
@@ -1,50 +0,0 @@
use super::RolesListItemDto;
use imphnen_entities::seaorm::auth::roles::Model as RolesModel;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RolesSchema {
pub id: Uuid,
pub name: String,
pub description: String,
pub is_system_role: bool,
pub is_default: bool,
pub permissions: Vec<String>,
pub created_at: String,
pub updated_at: String,
pub deleted_at: Option<String>,
}
impl From<&RolesModel> for RolesSchema {
fn from(model: &RolesModel) -> Self {
let permissions = model.permissions
.as_ref()
.and_then(|p| serde_json::from_value(p.clone()).ok())
.unwrap_or_default();
Self {
id: model.id,
name: model.name.clone(),
description: model.description.clone(),
is_system_role: model.is_system_role,
is_default: model.is_default,
permissions,
created_at: model.created_at.to_rfc3339(),
updated_at: model.updated_at.to_rfc3339(),
deleted_at: model.deleted_at.map(|dt| dt.to_rfc3339()),
}
}
}
impl RolesSchema {
pub fn list(&self) -> RolesListItemDto {
RolesListItemDto {
id: self.id.to_string(),
name: self.name.clone(),
permissions_count: self.permissions.len(),
created_at: Some(self.created_at.clone()),
updated_at: Some(self.updated_at.clone()),
}
}
}
-113
View File
@@ -1,113 +0,0 @@
use super::{RolesRepository, RolesRequestCreateDto, RolesRequestUpdateDto};
use crate::{
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
common_response, success_list_response, success_response, validate_request,
};
use crate::success_created_response;
use axum::{http::StatusCode, response::Response};
pub struct RolesService;
impl RolesService {
pub async fn get_role_list(state: &AppState, meta: MetaRequestDto) -> Response {
let repo = RolesRepository::new(state);
match repo.query_role_list(meta).await {
Ok(data) => {
let response = ResponseListSuccessDto {
data: data.data,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn get_role_by_id(state: &AppState, id: String) -> Response {
let repo = RolesRepository::new(state);
match repo.query_role_by_id(id).await {
Ok(role) => success_response(ResponseSuccessDto { data: role }),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn create_role(
state: &AppState,
payload: RolesRequestCreateDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = RolesRepository::new(state);
match repo.query_role_by_name(payload.name.clone()).await {
Ok(_role) => {
return common_response(StatusCode::CONFLICT, "Role name already exists");
}
Err(err) if err.to_string().contains("not found") => {}
Err(e) => {
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
}
}
match repo.query_create_role(payload).await {
Ok(created_role) => success_created_response(ResponseSuccessDto { data: created_role }),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
pub async fn update_role(
state: &AppState,
id: String,
payload: RolesRequestUpdateDto,
) -> Response {
if let Err((status, message)) = validate_request(&payload) {
return common_response(status, &message);
}
let repo = RolesRepository::new(state);
let existing_role = match repo.query_role_by_id(id.clone()).await {
Ok(role) => role,
Err(err) if err.to_string().contains("not found") => {
return common_response(StatusCode::NOT_FOUND, "Role not found");
}
Err(e) => {
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
}
};
if let Some(new_name) = payload.name.clone() {
match repo.query_role_by_name(new_name.clone()).await {
Ok(role_with_same_name) => {
if role_with_same_name.id != existing_role.id {
return common_response(
StatusCode::CONFLICT,
"Role name already exists",
);
}
}
Err(err) if err.to_string().contains("not found") => {}
Err(e) => {
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
}
}
}
match repo.query_update_role(id, payload).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
pub async fn delete_role(state: &AppState, id: String) -> Response {
let repo = RolesRepository::new(state);
match repo.query_role_by_id(id.clone()).await {
Ok(_) => {}
Err(err) if err.to_string().contains("not found") => {
return common_response(StatusCode::NOT_FOUND, "Role not found");
}
Err(e) => {
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
}
}
match repo.query_delete_role(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
}
-57
View File
@@ -1,57 +0,0 @@
use axum::{
Router,
routing::{delete, get, post, put},
};
pub mod users_controller;
pub mod users_dto;
pub mod users_repository;
pub mod users_schema;
pub mod users_service;
// Export only essential types and functions from each submodule
pub use users_controller::{
get_user_list,
get_user_by_id,
get_user_me,
post_create_user,
put_update_user,
put_update_user_me,
delete_user,
patch_user_active_status,
upload_file
};
pub use users_dto::{
UsersActiveInactiveRequestDto,
UsersCreateRequestDto,
UsersUpdateRequestDto,
UsersSetNewPasswordRequestDto,
UsersDetailItemDto,
UsersListItemDto,
UsersListQueryDto,
};
pub use users_repository::UsersRepository;
pub use users_schema::UsersSchema;
pub fn users_router() -> Router {
Router::new()
.route("/", get(get_user_list))
.route("/activate/{id}", put(patch_user_active_status))
.route("/create", post(post_create_user))
.route("/me", get(get_user_me))
.route("/delete/{id}", delete(delete_user))
.route("/detail/{id}", get(get_user_by_id))
.route("/update/{id}", put(put_update_user))
.route("/update/me", put(put_update_user_me))
.route("/upload", post(upload_file))
}
// Minimal admin router to satisfy test expectations at /v1/users/admin
pub fn admin_users_router() -> Router {
use users_controller as controller;
Router::new()
.route("/", axum::routing::get(controller::get_user_list))
.route("/detail/{id}", axum::routing::get(controller::get_user_by_id))
}
@@ -1,302 +0,0 @@
use crate::{AppState, MetaRequestDto};
use crate::{
MessageResponseDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
UsersCreateRequestDto, UsersDetailItemDto, permissions_guard,
};
use axum::extract::{Path, Multipart};
use axum::http::HeaderMap;
use axum::response::IntoResponse;
use axum::{Extension, Json};
use utoipa::ToSchema;
use serde::{Deserialize, Serialize};
use super::{
UsersActiveInactiveRequestDto, UsersListItemDto, UsersUpdateRequestDto,
};
use crate::v1::users::users_service::{UsersServiceTrait, UsersService};
#[derive(Serialize, Deserialize, ToSchema)]
#[schema(description = "File upload form data for multipart/form-data")]
pub struct FileUploadSchema {
/// Binary file data to upload
#[schema(format = "binary")]
pub file: String,
}
#[utoipa::path(
get,
security(
("Bearer" = [])
),
path = "/v1/users",
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>,
axum::extract::Query(meta): axum::extract::Query<MetaRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadListUsers],
)
.await
{
Ok((_claims, state)) => UsersService::get_user_list(&state, meta).await,
Err(response) => response,
}
}
#[utoipa::path(
get,
security(
("Bearer" = [])
),
path = "/v1/users/detail/{id}",
params(
("id" = String, Path, description = "User ID")
),
responses(
(status = 200, description = "[USER] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
),
tag = "Users"
)]
pub async fn get_user_by_id(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ReadDetailUsers],
)
.await
{
Ok((_claims, state)) => UsersService::get_user_by_id(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
get,
security(
("Bearer" = [])
),
path = "/v1/users/me",
responses(
(status = 200, description = "[ADMIN] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
),
tag = "Users"
)]
pub async fn get_user_me(
headers: HeaderMap,
Extension(state): Extension<AppState>,
) -> impl IntoResponse {
match permissions_guard(headers, Extension(state), vec![]).await {
Ok((claims, state)) => UsersService::get_user_me(claims, &state).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/users/create",
request_body = UsersCreateRequestDto,
responses(
(status = 200, description = "[ADMIN] Create new user", body = ResponseSuccessDto<UsersDetailItemDto>)
),
tag = "Users"
)]
pub async fn post_create_user(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<UsersCreateRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::CreateUsers],
)
.await
{
Ok((_claims, state)) => UsersService::create_user(&state, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
put,
security(
("Bearer" = [])
),
path = "/v1/users/update/{id}",
params(
("id" = String, Path, description = "User ID")
),
request_body = UsersUpdateRequestDto,
responses(
(status = 200, description = "[ADMIN] Update user", body = ResponseSuccessDto<UsersDetailItemDto>)
),
tag = "Users"
)]
pub async fn put_update_user(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
Json(payload): Json<UsersUpdateRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::UpdateUsers],
)
.await
{
Ok((_claims, state)) => UsersService::update_user(&state, id, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
put,
security(
("Bearer" = [])
),
path = "/v1/users/update/me",
request_body = UsersUpdateRequestDto,
responses(
(status = 200, description = "[USER] Update current user", body = ResponseSuccessDto<UsersDetailItemDto>)
),
tag = "Users"
)]
pub async fn put_update_user_me(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Json(payload): Json<UsersUpdateRequestDto>,
) -> impl IntoResponse {
match permissions_guard(headers.clone(), Extension(state), vec![]).await {
Ok((claims, state)) => UsersService::update_user_me(claims, &state, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
put,
security(
("Bearer" = [])
),
path = "/v1/users/activate/{id}",
params(
("id" = String, Path, description = "User ID")
),
request_body = UsersActiveInactiveRequestDto,
responses(
(status = 200, description = "[ADMIN] Set user active status", body = MessageResponseDto)
),
tag = "Users"
)]
pub async fn patch_user_active_status(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
Json(payload): Json<UsersActiveInactiveRequestDto>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::ActivateUsers],
)
.await
{
Ok((_claims, state)) => UsersService::set_user_active_status(&state, id, payload).await,
Err(response) => response,
}
}
#[utoipa::path(
delete,
security(
("Bearer" = [])
),
path = "/v1/users/delete/{id}",
responses(
(status = 200, description = "[ADMIN] Soft delete user", body = MessageResponseDto)
),
tag = "Users"
)]
pub async fn delete_user(
headers: HeaderMap,
Extension(state): Extension<AppState>,
Path(id): Path<String>,
) -> impl IntoResponse {
match permissions_guard(
headers,
Extension(state),
vec![PermissionsEnum::DeleteUsers],
)
.await
{
Ok((_claims, state)) => UsersService::delete_user(&state, id).await,
Err(response) => response,
}
}
#[utoipa::path(
post,
security(
("Bearer" = [])
),
path = "/v1/users/upload",
request_body(
content = FileUploadSchema,
description = "Upload file with multipart form data. Only 'file' field is required - file type will be detected automatically from the uploaded file.",
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>,
multipart: Multipart,
) -> impl IntoResponse {
// Check authentication first
match permissions_guard(
headers,
Extension(state),
vec![], // No specific permission needed, just authentication
)
.await
{
Ok((claims, state)) => {
// Extract user ID from user data
let user_id = claims.user_id.clone(); // Use claims.user_id directly
// Process upload - don't use match here since it returns Response directly
UsersService::upload_file(&state, user_id, multipart).await
},
Err(response) => response,
}
}
-193
View File
@@ -1,193 +0,0 @@
use imphnen_entities::{UsersDetailQueryDto, RolesDetailQueryDto, RolesDetailItemDto, users::UserProfileExtensionDto};
use lazy_static::lazy_static;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use validator::Validate;
use crate::UsersSchema; // Import UsersSchema
lazy_static! {
static ref PASSWORD_REGEX: regex::Regex =
regex::Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
}
#[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, Validate)]
pub struct UsersCreateRequestDto {
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
pub email: String,
#[validate(length(
min = 8,
message = "Password must have at least 8 characters"
))]
#[validate(regex(
path = "*PASSWORD_REGEX",
message = "Password must include uppercase, lowercase, number, and special character"
))]
pub password: String,
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
pub fullname: String,
pub is_active: bool,
pub role_id: String,
pub avatar: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
pub struct UsersUpdateRequestDto {
#[validate(
length(min = 1, message = "Email cannot be empty"),
email(message = "Email not valid")
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
#[validate(length(
min = 8,
message = "Password must have at least 8 characters"
))]
#[serde(skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub fullname: Option<String>,
#[validate(length(min = 2, message = "Legal name at least have 2 character"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub legal_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_active: Option<bool>,
#[validate(length(min = 1, message = "Avatar is required"))]
#[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>,
}
#[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 UsersDetailItemDto {
pub 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(),
}
}
pub fn from_schema(schema: &UsersSchema) -> Self {
Self {
id: schema.id.clone(),
role: RolesDetailItemDto::default(), // Placeholder, role needs to be fetched
fullname: schema.fullname.clone().unwrap_or_default(),
legal_name: schema.legal_name.clone(),
email: schema.email.clone().unwrap_or_default(),
avatar: schema.avatar.clone(),
is_active: schema.is_active,
profile_extension: schema.profile_extension.clone(),
created_at: schema.created_at.clone(),
updated_at: schema.updated_at.clone(),
}
}
}
#[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,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsersListQueryDto {
pub id: String,
pub role: RolesDetailQueryDto,
pub fullname: String,
pub email: String,
pub avatar: Option<String>,
pub is_active: bool,
pub created_at: String,
pub updated_at: String,
}
impl UsersListQueryDto {
pub fn from(self) -> UsersListItemDto {
UsersListItemDto {
id: self.id,
role: self.role.name,
fullname: self.fullname,
email: self.email,
avatar: self.avatar,
is_active: self.is_active,
created_at: self.created_at,
updated_at: self.updated_at,
}
}
}
impl From<&UsersDetailItemDto> for UsersDetailQueryDto {
fn from(dto: &UsersDetailItemDto) -> Self {
let mut s = UsersDetailQueryDto::default();
s.id = dto.id.clone();
s.fullname = dto.fullname.clone();
s.legal_name = dto.legal_name.clone();
s.email = dto.email.clone();
s.avatar = dto.avatar.clone();
s.is_active = dto.is_active;
s.is_deleted = false;
s.profile_extension = dto.profile_extension.clone();
s.password = String::new();
s.role = RolesDetailQueryDto::default();
s.created_at = dto.created_at.clone();
s.updated_at = dto.updated_at.clone();
s.mentor_id = None;
s.from_profile_extension()
}
}
impl UsersDetailItemDto {
pub fn extract_permissions_from_user_role(&self) -> Vec<String> {
self.role.permissions.iter().map(|p| p.name.clone()).collect()
}
}
@@ -1,374 +0,0 @@
use imphnen_entities::{
UsersDetailQueryDto,
seaorm::auth::users::{Entity as UsersEntity, ActiveModel as UserActiveModel, Column as UserColumn},
seaorm::auth::roles::{Entity as RolesEntity},
RolesDetailQueryDto,
PermissionsQueryDto // Import this
};
use crate::{
UsersSchema,
AppState,
MetaRequestDto,
ResponseListSuccessDto,
MetaResponseDto
};
use super::users_dto::UsersListItemDto;
use sea_orm::{
EntityTrait,
QueryFilter,
PaginatorTrait,
ActiveModelTrait,
ActiveValue,
DatabaseConnection,
ColumnTrait,
};
use anyhow::{Result, bail, anyhow};
use uuid::Uuid;
use chrono::Utc;
use std::time::Instant;
pub struct UsersRepository<'a> {
state: &'a AppState,
}
impl<'a> UsersRepository<'a> {
pub fn new(state: &'a AppState) -> Self {
Self { state }
}
fn db(&self) -> &DatabaseConnection {
&self.state.postgres_connection.conn
}
pub async fn query_user_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<UsersListItemDto>>> {
let now = Instant::now();
// Build the query
let query = UsersEntity::find()
.filter(UserColumn::DeletedAt.is_null())
.filter(UserColumn::IsActive.eq(true));
// Apply search if provided
// if let Some(search) = &meta.search {
// query = query.filter(
// UserColumn::Email.contains(search)
// .or(UserColumn::Username.contains(search))
// .or(UserColumn::FirstName.contains(search))
// .or(UserColumn::LastName.contains(search))
// );
// } // Re-add search capability once query building is fixed
// Apply ordering
// query = query.order_by(UserColumn::CreatedAt, sea_orm::Order::Desc); // Re-add ordering
// Apply pagination
let page = meta.page.unwrap_or(1);
let per_page = meta.per_page.unwrap_or(10);
let paginator = query.paginate(self.db(), per_page);
let users = paginator.fetch_page(page - 1).await?;
// Optimize: Load all roles in one query
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())
.await?
.into_iter()
.map(|r| (r.id, r.name))
.collect::<std::collections::HashMap<_, _>>()
} else {
std::collections::HashMap::new()
};
// Convert to DTOs
let mut data: Vec<UsersListItemDto> = Vec::with_capacity(users.len());
for user in users.into_iter() {
let role_name = user.role_id.and_then(|rid| roles.get(&rid).cloned()).unwrap_or_default();
data.push(UsersListItemDto {
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(),
});
}
let total = paginator.num_items().await?;
let meta_response = MetaResponseDto {
page: Some(page),
per_page: Some(per_page),
total: Some(total),
};
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_user_list' took: {elapsed:.2?}");
}
Ok(ResponseListSuccessDto {
data,
meta: Some(meta_response),
})
}
pub async fn query_user_by_email(
&self,
email: String,
) -> Result<UsersDetailQueryDto> {
let now = Instant::now();
let user_and_role = UsersEntity::find()
.filter(UserColumn::Email.eq(email))
.filter(UserColumn::DeletedAt.is_null())
.find_also_related(RolesEntity)
.one(self.db())
.await?
.ok_or_else(|| anyhow::anyhow!("User not found"))?;
let (user, role) = user_and_role;
let role_dto = 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()),
});
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_user_by_email' took: {elapsed:.2?}");
}
// Convert UserModel to UsersDetailQueryDto
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()); // Extract from metadata
dto.password = String::new(); // Don't expose password
dto.role = role_dto; // Use actual role DTO
dto.created_at = user.created_at.to_rfc3339();
dto.updated_at = user.updated_at.to_rfc3339();
dto.mentor_id = None; // Not in model
Ok(dto.from_profile_extension())
}
pub async fn query_user_by_id(&self, id: &str) -> Result<UsersDetailQueryDto> {
let now = Instant::now();
let user_id = Uuid::parse_str(id)?;
let user_and_role = UsersEntity::find_by_id(user_id)
.filter(UserColumn::DeletedAt.is_null())
.find_also_related(RolesEntity)
.one(self.db())
.await?
.ok_or_else(|| anyhow::anyhow!("User not found in database"))?;
let (user, role) = user_and_role;
let role_dto = 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()),
});
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_user_by_id' took: {elapsed:.2?}");
}
// Convert UserModel to UsersDetailQueryDto
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()); // Extract from metadata
dto.password = String::new(); // Don't expose password
dto.role = role_dto; // Use actual role DTO
dto.created_at = user.created_at.to_rfc3339();
dto.updated_at = user.updated_at.to_rfc3339();
dto.mentor_id = None; // Not in model
Ok(dto.from_profile_extension())
}
pub async fn query_create_user(&self, data: UsersSchema) -> Result<String> {
let now = Instant::now();
// Check if user already exists
let existing_user = UsersEntity::find()
.filter(UserColumn::Email.eq(data.email.clone()))
.one(self.db())
.await?;
if existing_user.is_some() {
bail!("User with this email already exists");
}
let email = data.email.ok_or_else(|| anyhow!("Email is required"))?;
let password = data.password.ok_or_else(|| anyhow!("Password is required"))?;
let full_name = data.fullname.unwrap_or_default();
let (first_name, last_name) = full_name.split_once(' ').unwrap_or((&full_name, ""));
let user_active_model = UserActiveModel {
id: ActiveValue::Set(Uuid::new_v4()),
email: ActiveValue::Set(email.clone()),
password_hash: ActiveValue::Set(password),
username: ActiveValue::Set(email.clone()), // Use email as username for now
first_name: ActiveValue::Set(Some(first_name.to_string())),
last_name: ActiveValue::Set(Some(last_name.to_string())),
avatar_url: ActiveValue::Set(data.avatar),
is_verified: ActiveValue::Set(false),
is_active: ActiveValue::Set(data.is_active),
metadata: ActiveValue::Set(data.profile_extension.map(|p| serde_json::to_value(p).unwrap_or_default())), // Save profile_extension to metadata
created_at: ActiveValue::Set(Utc::now()),
updated_at: ActiveValue::Set(Utc::now()),
deleted_at: ActiveValue::Set(None),
role_id: ActiveValue::Set(data.role_id), // Add this line
};
let _result = UsersEntity::insert(user_active_model).exec(self.db()).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_create_user' took: {elapsed:.2?}");
}
Ok("Successfully created user".into())
}
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
let now = Instant::now();
let user_id = Uuid::parse_str(&data.id)?;
let existing = self.query_user_by_id(&data.id).await?;
if existing.is_deleted {
bail!("User already deleted");
}
let mut user_active_model: UserActiveModel = UsersEntity::find_by_id(user_id)
.one(self.db())
.await?
.ok_or_else(|| anyhow::anyhow!("User not found"))?
.into();
let email = data.email.ok_or_else(|| anyhow!("Email is required"))?;
let full_name = data.fullname.unwrap_or_default();
let (first_name, last_name) = full_name.split_once(' ').unwrap_or((&full_name, ""));
// Update fields
user_active_model.email = ActiveValue::Set(email);
user_active_model.first_name = ActiveValue::Set(Some(first_name.to_string()));
user_active_model.last_name = ActiveValue::Set(Some(last_name.to_string()));
user_active_model.avatar_url = ActiveValue::Set(data.avatar);
user_active_model.is_active = ActiveValue::Set(data.is_active);
user_active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
if data.role_id.is_some() { // Conditionally update role_id
user_active_model.role_id = ActiveValue::Set(data.role_id);
}
if data.profile_extension.is_some() { // Conditionally update profile_extension
user_active_model.metadata = ActiveValue::Set(data.profile_extension.map(|p| serde_json::to_value(p).unwrap_or_default()));
}
let _result = user_active_model.update(self.db()).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_update_user' took: {elapsed:.2?}");
}
Ok("Success update user".into())
}
pub async fn query_delete_user(&self, id: String) -> Result<String> {
let now = Instant::now();
let user_id = Uuid::parse_str(&id)?;
let user = self.query_user_by_id(&id).await?;
if user.is_deleted {
bail!("User not found");
}
let mut user_active_model: UserActiveModel = UsersEntity::find_by_id(user_id)
.one(self.db())
.await?
.ok_or_else(|| anyhow::anyhow!("User not found"))?
.into();
// Soft delete
user_active_model.deleted_at = ActiveValue::Set(Some(chrono::Utc::now()));
user_active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
let _result = user_active_model.update(self.db()).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_delete_user' took: {elapsed:.2?}");
}
Ok("Success delete user".into())
}
}
-156
View File
@@ -1,156 +0,0 @@
use imphnen_entities::{UsersDetailQueryDto, users::UserProfileExtensionDto};
use super::{UsersCreateRequestDto, UsersUpdateRequestDto};
use imphnen_libs::hash_password; // Keep hash_password
use imphnen_utils::generate_date::get_iso_date; // Keep get_iso_date
use serde::{Deserialize, Serialize};
use uuid::Uuid; // Keep Uuid
use anyhow::Result;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsersSchema {
pub id: String,
pub fullname: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub legal_name: Option<String>,
pub email: Option<String>,
pub password: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar: Option<String>,
pub is_active: bool,
pub is_deleted: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub mentor_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub profile_extension: Option<UserProfileExtensionDto>,
pub role_id: Option<Uuid>,
pub created_at: String,
pub updated_at: String,
}
impl Default for UsersSchema {
fn default() -> Self {
Self {
id: Uuid::new_v4().to_string(),
fullname: None,
legal_name: None,
email: None,
password: None,
avatar: None,
is_active: false,
is_deleted: false,
mentor_id: None,
profile_extension: None,
role_id: None,
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
}
}
impl UsersSchema {
pub fn from(dto: UsersDetailQueryDto) -> Self {
Self {
id: dto.id,
fullname: Some(dto.fullname),
legal_name: dto.legal_name,
email: Some(dto.email),
avatar: dto.avatar,
is_active: dto.is_active,
is_deleted: dto.is_deleted,
mentor_id: dto.mentor_id,
profile_extension: dto.profile_extension,
password: Some(dto.password),
created_at: dto.created_at,
updated_at: dto.updated_at,
role_id: Uuid::parse_str(&dto.role.id).ok(),
}
}
pub fn create(dto: UsersCreateRequestDto) -> Result<Self> {
let password_hash = hash_password(&dto.password).map_err(|e| anyhow::anyhow!("Hash password failed: {}", e))?;
Ok(Self {
id: Uuid::new_v4().to_string(),
email: Some(dto.email),
password: Some(password_hash),
fullname: Some(dto.fullname),
is_active: dto.is_active,
role_id: Some(Uuid::parse_str(&dto.role_id)?),
..Default::default()
})
}
pub fn update(_user: UsersUpdateRequestDto, id: String) -> Self {
Self {
id,
updated_at: get_iso_date(),
created_at: String::new(),
fullname: None,
legal_name: None,
email: None,
password: None,
avatar: None,
is_active: false,
is_deleted: false,
mentor_id: None,
profile_extension: None,
role_id: None,
}
}
pub fn partial_update(current_user: UsersDetailQueryDto, user: UsersUpdateRequestDto) -> Self {
let mut schema = Self::from(current_user);
schema.updated_at = get_iso_date();
// Only update fields that are provided (Some)
if let Some(fullname) = user.fullname {
schema.fullname = Some(fullname);
}
if let Some(email) = user.email {
schema.email = Some(email);
}
if let Some(password) = user.password {
schema.password = Some(hash_password(&password).unwrap_or(password));
}
if let Some(is_active) = user.is_active {
schema.is_active = is_active;
}
if let Some(role_id) = user.role_id {
schema.role_id = Uuid::parse_str(&role_id).ok();
}
schema.legal_name = user.legal_name;
schema.avatar = user.avatar;
schema.profile_extension = user.profile_extension;
schema
}
pub fn patch_password(dto: UsersDetailQueryDto, password: String) -> Self {
Self {
password: Some(password),
id: dto.id.clone(),
fullname: Some(dto.fullname),
legal_name: dto.legal_name,
email: Some(dto.email),
avatar: dto.avatar,
is_active: dto.is_active,
is_deleted: dto.is_deleted,
mentor_id: dto.mentor_id,
profile_extension: dto.profile_extension,
created_at: dto.created_at,
updated_at: dto.updated_at,
role_id: Uuid::parse_str(&dto.role.id).ok(),
}
}
pub fn update_mentor_id(mut self, mentor_id: Option<String>) -> Self {
self.mentor_id = mentor_id; // Removed make_thing_from_enum
self.updated_at = get_iso_date();
self
}
/// Convert role string to Uuid for database operations
pub fn get_role_id(&self) -> Result<Option<Uuid>> {
Ok(self.role_id) // Removed parsing from `role` field
}
}
-613
View File
@@ -1,613 +0,0 @@
use super::{
UsersActiveInactiveRequestDto, UsersCreateRequestDto,
UsersSetNewPasswordRequestDto, UsersUpdateRequestDto,
};
use crate::{
AppState, MetaRequestDto, ResponseListSuccessDto, UsersRepository, UsersSchema,
ResponseSuccessDto, common_response, success_list_response,
success_response, validate_request,
};
use imphnen_utils::{errors::AppError, response_format::error_response};
use imphnen_utils::response_format::success_created_response;
use axum::{http::StatusCode, response::Response, extract::Multipart};
use imphnen_libs::{hash_password, verify_password, MinioConfig, FileType, decode_base64_file, extract_content_type_from_data_url, create_minio_service_from_config};
use imphnen_utils::make_thing_from_enum;
use uuid::Uuid;
use std::pin::Pin;
use std::future::Future;
use anyhow::Result;
use tracing::info;
use tracing::error;
use crate::v1::users::users_dto::{UsersDetailItemDto as UserDto, UsersCreateRequestDto as CreateUserDto};
use serde_json::json;
pub trait UsersServiceTrait: Send + Sync + 'static {
fn get_user_list(state: &AppState, meta: MetaRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn get_user_by_id(state: &AppState, id: String) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn get_user_me(claims: imphnen_libs::jsonwebtoken::Claims, state: &AppState) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn create_user(state: &AppState, new_user: UsersCreateRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn update_user(state: &AppState, id: String, user: UsersUpdateRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn update_user_me(claims: imphnen_libs::jsonwebtoken::Claims, state: &AppState, user: UsersUpdateRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn set_user_active_status(state: &AppState, id: String, payload: UsersActiveInactiveRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn update_user_password(state: &AppState, email: String, payload: UsersSetNewPasswordRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn get_user_by_mentor_id(state: &AppState, mentor_id: String) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn delete_user(state: &AppState, id: String) -> Pin<Box<dyn Future<Output = Response> + Send>>;
fn get_user_by_email(&self, email: &str, state: &AppState) -> Pin<Box<dyn Future<Output = Result<Option<UserDto>>> + Send>>;
fn create_user_by_dto(&self, new_user: CreateUserDto, state: &AppState) -> Pin<Box<dyn Future<Output = Result<UserDto>> + Send>>;
fn update_user_avatar(email: &str, avatar_url: Option<String>, state: &AppState) -> Pin<Box<dyn Future<Output = Result<()>> + Send>>;
fn upload_file(state: &AppState, user_id: String, multipart: Multipart) -> Pin<Box<dyn Future<Output = Response> + Send>>;
}
#[derive(Clone)]
pub struct UsersService;
impl UsersService {
}
impl UsersServiceTrait for UsersService {
fn get_user_list(state: &AppState, meta: MetaRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
match repo.query_user_list(meta).await {
Ok(data) => {
let response = ResponseListSuccessDto {
data: data.data,
meta: data.meta,
};
success_list_response(response)
}
Err(e) => error_response(AppError::BadRequestError(e.to_string())),
}
})
}
fn get_user_by_id(state: &AppState, id: String) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
let id = id.to_owned();
Box::pin(async move {
if Uuid::parse_str(&id).is_err() {
return error_response(AppError::BadRequestError("Invalid User ID format".into()));
}
let repo = UsersRepository::new(&state);
let thing_id = make_thing_from_enum("users", &id);
match repo.query_user_by_id(&thing_id).await {
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
data: UserDto::from(&user), // Corrected to use UserDto::from by reference
}),
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
Err(e) => error_response(AppError::NotFoundError(e.to_string())),
}
})
}
fn get_user_me(claims: imphnen_libs::jsonwebtoken::Claims, state: &AppState) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let claims = claims.to_owned();
let state = state.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
let thing_id = make_thing_from_enum("users", &claims.user_id);
match repo.query_user_by_id(&thing_id).await {
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
data: UserDto::from(&user),
}),
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
})
}
fn create_user(
state: &AppState,
new_user: UsersCreateRequestDto,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
Box::pin(async move {
if let Err((status, message)) = validate_request(&new_user) {
return common_response(status, &message);
}
let repo = UsersRepository::new(&state);
if repo
.query_user_by_email(new_user.email.clone())
.await
.is_ok()
{
return error_response(AppError::ConflictError("User already exists".into()));
}
match repo.query_create_user(UsersSchema::create(new_user.clone()).expect("Failed to create user schema")).await {
Ok(_msg) => {
// After successful creation, fetch the created user
match repo.query_user_by_email(new_user.email).await {
Ok(created_user) => success_created_response(ResponseSuccessDto {
data: UserDto::from(&created_user),
}),
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
}
}
Err(err) => {
error_response(AppError::InternalServerError(err.to_string()))
}
}
})
}
fn update_user(
state: &AppState,
id: String,
user: UsersUpdateRequestDto,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
let id = id.to_owned();
Box::pin(async move {
if Uuid::parse_str(&id).is_err() {
return error_response(AppError::BadRequestError("Invalid User ID format".into()));
}
let repo = UsersRepository::new(&state);
if let Err((status, message)) = validate_request(&user) {
return common_response(status, &message);
}
// Get current user data first
let thing_id = make_thing_from_enum("users", &id);
let current_user = match repo.query_user_by_id(&thing_id).await {
Ok(user) => user,
Err(_) => return error_response(AppError::NotFoundError("User not found".into())),
};
let updated_user = UsersSchema::partial_update(current_user, user);
match repo.query_update_user(updated_user).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => error_response(AppError::BadRequestError(e.to_string())),
}
})
}
fn update_user_me(
claims: imphnen_libs::jsonwebtoken::Claims,
state: &AppState,
user_update_dto: UsersUpdateRequestDto,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let claims = claims.to_owned();
let state = state.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
let thing_id = make_thing_from_enum("users", &claims.user_id);
let user_data = match repo.query_user_by_id(&thing_id).await {
Ok(user) => user,
Err(_) => return common_response(StatusCode::NOT_FOUND, "User not found"),
};
if let Err((status, message)) = validate_request(&user_update_dto) {
return common_response(status, &message);
}
let updated_user = UsersSchema::partial_update(user_data, user_update_dto);
match repo.query_update_user(updated_user).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
})
}
fn set_user_active_status(
state: &AppState,
id: String,
payload: UsersActiveInactiveRequestDto,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
let id = id.to_owned();
Box::pin(async move {
if Uuid::parse_str(&id).is_err() {
return error_response(AppError::BadRequestError("Invalid User ID format".into()));
}
let repo = UsersRepository::new(&state);
let thing_id = make_thing_from_enum("users", &id);
match repo.query_user_by_id(&thing_id).await {
Ok(user) if !user.is_deleted => {
let patch = UsersSchema {
id: user.id.clone(),
is_active: payload.is_active,
..UsersSchema::from(user)
};
match repo.query_update_user(patch).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
}
}
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
}
})
}
fn update_user_password(
state: &AppState,
email: String,
payload: UsersSetNewPasswordRequestDto,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
let email = email.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
let user = match repo.query_user_by_email(email.clone()).await {
Ok(user) if !user.is_deleted => user,
_ => return error_response(AppError::NotFoundError("User not found".into())),
};
let verify_result = match verify_password(&payload.old_password, &user.password)
{
Ok(result) => result,
Err(_) => {
return error_response(AppError::BadRequestError("Old password is incorrect".into()));
}
};
if !verify_result {
return error_response(AppError::BadRequestError("Old password is incorrect".into()));
}
let new_password = match hash_password(&payload.password) {
Ok(pw) => pw,
Err(_) => {
return error_response(AppError::InternalServerError("Failed to hash password".into()));
}
};
let patch = UsersSchema {
id: user.id.clone(),
password: Some(new_password),
..Default::default()
};
match repo.query_update_user(patch).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => error_response(AppError::BadRequestError(e.to_string())),
}
})
}
fn get_user_by_mentor_id(
state: &AppState,
mentor_id: String,
) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
let mentor_id = mentor_id.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
let thing_id = make_thing_from_enum("mentors", &mentor_id);
match repo.query_user_by_id(&thing_id).await {
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
data: UserDto::from(&user), // Corrected to use UserDto::from by reference
}),
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
})
}
fn delete_user(state: &AppState, id: String) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
let id = id.to_owned();
Box::pin(async move {
if Uuid::parse_str(&id).is_err() {
return error_response(AppError::BadRequestError("Invalid User ID format".into()));
}
let repo = UsersRepository::new(&state);
let thing_id = make_thing_from_enum("users", &id);
if repo.query_user_by_id(&thing_id).await.is_err() {
return error_response(AppError::NotFoundError("User not found".into()));
}
match repo.query_delete_user(id).await {
Ok(msg) => common_response(StatusCode::OK, &msg),
Err(e) => error_response(AppError::BadRequestError(e.to_string())),
}
})
}
fn get_user_by_email(&self, email: &str, state: &AppState) -> Pin<Box<dyn Future<Output = Result<Option<UserDto>>> + Send>> {
let email = email.to_owned();
let state = state.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
let user = repo.query_user_by_email(email.to_string()).await;
match user {
Ok(u) => Ok(Some(UserDto::from(&u))),
Err(e) if e.to_string().contains("User not found") => Ok(None),
Err(e) => Err(anyhow::anyhow!(e.to_string())),
}
})
}
fn create_user_by_dto(&self, new_user: CreateUserDto, state: &AppState) -> Pin<Box<dyn Future<Output = Result<UserDto>> + Send>> {
let state = state.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
let email_clone = new_user.email.clone();
let hashed_password = match hash_password(&new_user.password) {
Ok(pw) => pw,
Err(_) => {
return Err(anyhow::anyhow!("Failed to hash password"));
}
};
let user_schema = UsersSchema {
email: Some(new_user.email),
password: Some(hashed_password),
fullname: Some(new_user.fullname),
is_active: new_user.is_active,
avatar: new_user.avatar,
role_id: Some(Uuid::parse_str(&new_user.role_id).unwrap_or(Uuid::new_v4())),
..Default::default()
};
match repo.query_create_user(user_schema).await {
Ok(_msg) => {
let created_user = repo.query_user_by_email(email_clone).await?;
Ok(UserDto::from(&created_user))
},
Err(e) => Err(anyhow::anyhow!(e.to_string())),
}
})
}
fn update_user_avatar(email: &str, avatar_url: Option<String>, state: &AppState) -> Pin<Box<dyn Future<Output = Result<()>> + Send>> {
let email = email.to_owned();
let avatar_url = avatar_url.to_owned();
let state = state.to_owned();
Box::pin(async move {
let repo = UsersRepository::new(&state);
let mut user = repo.query_user_by_email(email.to_string()).await
.map_err(|e| anyhow::anyhow!("Failed to get user: {}", e))?;
user.avatar = avatar_url;
let user_schema = UsersSchema::from(user);
match repo.query_update_user(user_schema).await {
Ok(_) => {
info!("Successfully updated avatar for user: {}", email);
Ok(())
},
Err(e) => Err(anyhow::anyhow!("Failed to update user avatar: {}", e)),
}
})
}
fn upload_file(state: &AppState, user_id: String, mut multipart: Multipart) -> Pin<Box<dyn Future<Output = Response> + Send>> {
let state = state.to_owned();
let user_id = user_id.to_owned();
Box::pin(async move {
info!("Entering upload_file function for user_id: {}", user_id);
// Initialize MinIO configuration
let minio_config = match MinioConfig::from_env() {
Ok(config) => {
info!("MinIO config loaded successfully.");
config
},
Err(e) => {
error!("Failed to load MinIO config: {}", e);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
"MinIO configuration error",
);
}
};
// Store bucket name before minio_config is moved
let bucket_name = minio_config.bucket_name.clone();
info!("MinIO bucket name: {}", bucket_name);
// Initialize MinIO service
let minio_service = match create_minio_service_from_config(minio_config).await {
Ok(service) => {
info!("MinIO service initialized successfully.");
service
},
Err(e) => {
error!("Failed to initialize MinIO service: {}", e);
return common_response(
StatusCode::INTERNAL_SERVER_ERROR,
"MinIO service initialization error",
);
}
};
// Get actual user data from database using user_id (which is a UUID)
let repo = UsersRepository::new(&state);
let thing_id = make_thing_from_enum("users", &user_id);
let user_data = match repo.query_user_by_id(&thing_id).await {
Ok(user) => {
info!("Found user in DB. User ID: {}, Email: {}", user.to_string(), user.email);
user
}
Err(e) => {
error!("Failed to find user in DB for ID {}: {}", user_id, e);
return common_response(
StatusCode::NOT_FOUND,
"User not found",
);
}
};
let actual_user_id = user_data.to_string();
let user_email = user_data.email;
let mut file_data: Option<Vec<u8>> = None;
let mut filename: Option<String> = None;
let mut content_type: Option<String> = None;
info!("Starting multipart form processing.");
while let Some(field) = multipart.next_field().await.unwrap_or(None) {
let name = field.name().unwrap_or("").to_string();
info!("Processing multipart field: {}", name);
match name.as_str() {
"file" => {
filename = field.file_name().map(|s| s.to_string());
content_type = field.content_type().map(|s| s.to_string());
info!("Detected file field. Filename: {:?}, Content-Type: {:?}", filename, content_type);
match field.bytes().await {
Ok(bytes) => {
file_data = Some(bytes.to_vec());
info!("Successfully read file data, size: {} bytes", file_data.as_ref().map_or(0, |d| d.len()));
},
Err(e) => {
error!("Failed to read file data from multipart: {}", e);
return common_response(
StatusCode::BAD_REQUEST,
"Failed to read file data",
);
}
}
}
"base64_data" => {
let base64_str = field.text().await.unwrap_or_default();
info!("Detected base64_data field, length: {}", base64_str.len());
if !base64_str.is_empty() {
match decode_base64_file(&base64_str) {
Ok(decoded_data) => {
file_data = Some(decoded_data);
info!("Successfully decoded base64 data, size: {} bytes", file_data.as_ref().map_or(0, |d| d.len()));
if let Some(detected_type) = extract_content_type_from_data_url(&base64_str) {
content_type = Some(detected_type);
info!("Detected content type from base64 data URL: {}", content_type.as_ref().unwrap());
}
}
Err(e) => {
error!("Failed to decode base64 data: {}", e);
return common_response(
StatusCode::BAD_REQUEST,
"Invalid base64 data",
);
}
}
}
}
"filename" => {
filename = Some(field.text().await.unwrap_or_default());
info!("Received filename from field: {:?}", filename);
}
"content_type" => {
content_type = Some(field.text().await.unwrap_or_default());
info!("Received content_type from field: {:?}", content_type);
}
_ => {
info!("Skipping unknown multipart field: {}", name);
}
}
}
info!("Finished multipart form processing.");
// Validate required fields
let file_data = match file_data {
Some(data) => data,
None => {
error!("File data is missing after multipart processing.");
return common_response(
StatusCode::BAD_REQUEST,
"file data is required",
);
}
};
info!("File data extracted, size: {} bytes.", file_data.len());
let filename = filename.unwrap_or_else(|| {
info!("Filename not provided, defaulting to 'unnamed_file'.");
"unnamed_file".to_string()
});
let content_type = content_type.unwrap_or_else(|| {
info!("Content type not provided, defaulting to 'application/octet-stream'.");
"application/octet-stream".to_string()
});
info!("Final filename: {}, Content-Type: {}", filename, content_type);
// Auto-detect file type based on content type and filename
let file_type = FileType::from_content_type(&content_type);
let file_type = if matches!(file_type, FileType::Unknown) {
info!("Content type detection failed, trying from filename.");
FileType::from_filename(&filename)
} else {
file_type
};
info!("Detected file type: {:?}", file_type);
// Validate file type is supported
if matches!(file_type, FileType::Unknown) {
error!("Unsupported file type detected: {:?}", file_type);
return common_response(
StatusCode::BAD_REQUEST,
"Unsupported file type. Supported types: JPEG, PNG, WEBP, GIF, PDF, DOC, DOCX",
);
}
// Validate file type matches content type
if !file_type.allowed_types().contains(&content_type.as_str()) {
error!("File type '{:?}' does not match content type '{}'.", file_type, content_type);
return common_response(
StatusCode::BAD_REQUEST,
&format!("File type '{file_type:?}' does not match content type '{content_type}'"),
);
}
// Validate file size
if file_data.len() > file_type.max_size() {
error!("File too large. Current size: {} bytes, Max size for {:?}: {} bytes",
file_data.len(), file_type, file_type.max_size());
return common_response(
StatusCode::BAD_REQUEST,
&format!("File too large. Maximum size for {:?} is {} bytes",
file_type, file_type.max_size()),
);
}
info!("File size validated: {} bytes.", file_data.len());
// Create secure upload path with user ID (sanitized for filesystem)
let sanitized_user_id = user_email
.replace("%", "")
.replace(":", "_")
.replace("@", "_at_")
.replace(".", "_");
info!("Sanitized user ID for folder path: {}", sanitized_user_id);
let folder = format!("{}/{sanitized_user_id}", file_type.as_folder());
info!("Upload folder: {folder}");
// Upload file to MinIO with deduplication
info!("Attempting to upload file to MinIO.");
match minio_service.upload_file_with_deduplication(&file_data, &content_type, &folder, &filename).await {
Ok(object_path) => {
info!("File uploaded successfully to MinIO. Object path: {}", object_path);
// Create permanent URL (no expiration)
let permanent_url = format!("https://cdn.asepharyana.tech/{}/{}",
bucket_name, object_path);
info!("Permanent URL: {}", permanent_url);
let response_data = json!({
"filename": filename,
"original_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": actual_user_id,
"email": user_email
});
success_response(ResponseSuccessDto {
data: response_data,
})
}
Err(e) => {
error!("Failed to upload file to MinIO: {}", e);
common_response(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("Upload failed: {e}"),
)
}
}
})
}
}