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:
1 parent
1b3366d735
commit
e432a1a743
379 files changed
+9013
-30532
No files matched your search
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
@@ -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};
|
||||
@@ -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;
|
||||
+158
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod domain;
|
||||
pub mod application;
|
||||
pub mod infrastructure;
|
||||
|
||||
pub use infrastructure::http::routes::{permissions_public_routes, permissions_protected_routes};
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod domain;
|
||||
pub mod application;
|
||||
pub mod infrastructure;
|
||||
|
||||
pub use infrastructure::http::routes::{roles_public_routes, roles_protected_routes};
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod user_service;
|
||||
pub use user_service::UserServiceImpl;
|
||||
@@ -0,0 +1,95 @@
|
||||
use std::sync::Arc;
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_utils::AppError;
|
||||
use imphnen_libs::{hash_password, verify_password};
|
||||
use crate::users::domain::{UserEntity, UserListItem, UserRepository, UserService};
|
||||
|
||||
pub struct UserServiceImpl {
|
||||
repo: Arc<dyn UserRepository>,
|
||||
}
|
||||
|
||||
impl UserServiceImpl {
|
||||
pub fn new(repo: Arc<dyn UserRepository>) -> Self {
|
||||
Self { repo }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UserService for UserServiceImpl {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<UserListItem>, AppError> {
|
||||
self.repo.find_all(params).await
|
||||
}
|
||||
|
||||
async fn get(&self, id: String) -> Result<UserEntity, AppError> {
|
||||
self.repo.find_by_id(&id).await
|
||||
}
|
||||
|
||||
async fn get_me(&self, user_id: String) -> Result<UserEntity, AppError> {
|
||||
self.repo.find_by_id(&user_id).await
|
||||
}
|
||||
|
||||
async fn get_by_email(&self, email: String) -> Result<UserEntity, AppError> {
|
||||
self.repo.find_by_email(email).await
|
||||
}
|
||||
|
||||
async fn create(&self, entity: UserEntity) -> Result<UserEntity, AppError> {
|
||||
// Check for email conflict
|
||||
match self.repo.find_by_email(entity.email.clone()).await {
|
||||
Ok(_) => return Err(AppError::ConflictError("User already exists".into())),
|
||||
Err(AppError::NotFoundError(_)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
let email = entity.email.clone();
|
||||
self.repo.create(entity).await?;
|
||||
self.repo.find_by_email(email).await
|
||||
}
|
||||
|
||||
async fn update(&self, entity: UserEntity) -> Result<String, AppError> {
|
||||
let existing = self.repo.find_by_id(&entity.id).await?;
|
||||
if existing.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
self.repo.update(entity).await
|
||||
}
|
||||
|
||||
async fn delete(&self, id: String) -> Result<String, AppError> {
|
||||
let user = self.repo.find_by_id(&id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
self.repo.delete(id).await
|
||||
}
|
||||
|
||||
async fn set_active_status(&self, id: String, is_active: bool) -> Result<String, AppError> {
|
||||
let mut user = self.repo.find_by_id(&id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
user.is_active = is_active;
|
||||
self.repo.update(user).await
|
||||
}
|
||||
|
||||
async fn update_password(&self, email: String, old_password: String, new_password: String) -> Result<String, AppError> {
|
||||
let user = self.repo.find_by_email(email.clone()).await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".into()))?;
|
||||
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
|
||||
let is_valid = verify_password(&old_password, &user.password)
|
||||
.map_err(|_| AppError::BadRequestError("Password verification failed".into()))?;
|
||||
if !is_valid {
|
||||
return Err(AppError::BadRequestError("Old password is incorrect".into()));
|
||||
}
|
||||
|
||||
let new_hash = hash_password(&new_password)
|
||||
.map_err(|_| AppError::InternalServerError("Failed to hash password".into()))?;
|
||||
|
||||
let mut updated = user;
|
||||
updated.password = new_hash;
|
||||
self.repo.update(updated).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub mod user;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
|
||||
pub use user::UserEntity;
|
||||
pub use repository::{UserRepository, UserListItem};
|
||||
pub use service::UserService;
|
||||
@@ -0,0 +1,28 @@
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_utils::AppError;
|
||||
use super::user::UserEntity;
|
||||
|
||||
/// Lightweight list item returned by list queries
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct UserListItem {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserRepository: Send + Sync {
|
||||
async fn find_all(&self, params: PaginationParams) -> Result<PaginatorResponse<UserListItem>, AppError>;
|
||||
async fn find_by_id(&self, id: &str) -> Result<UserEntity, AppError>;
|
||||
async fn find_by_email(&self, email: String) -> Result<UserEntity, AppError>;
|
||||
async fn create(&self, entity: UserEntity) -> Result<String, AppError>;
|
||||
async fn update(&self, entity: UserEntity) -> Result<String, AppError>;
|
||||
async fn delete(&self, id: String) -> Result<String, AppError>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
use async_trait::async_trait;
|
||||
use paginator_rs::PaginationParams;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_utils::AppError;
|
||||
use super::user::UserEntity;
|
||||
use super::repository::UserListItem;
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserService: Send + Sync {
|
||||
async fn list(&self, params: PaginationParams) -> Result<PaginatorResponse<UserListItem>, AppError>;
|
||||
async fn get(&self, id: String) -> Result<UserEntity, AppError>;
|
||||
async fn get_me(&self, user_id: String) -> Result<UserEntity, AppError>;
|
||||
async fn get_by_email(&self, email: String) -> Result<UserEntity, AppError>;
|
||||
async fn create(&self, entity: UserEntity) -> Result<UserEntity, AppError>;
|
||||
async fn update(&self, entity: UserEntity) -> Result<String, AppError>;
|
||||
async fn delete(&self, id: String) -> Result<String, AppError>;
|
||||
async fn set_active_status(&self, id: String, is_active: bool) -> Result<String, AppError>;
|
||||
async fn update_password(&self, email: String, old_password: String, new_password: String) -> Result<String, AppError>;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use imphnen_entities::{RolesDetailQueryDto, users::UserProfileExtensionDto};
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct UserEntity {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
pub fullname: String,
|
||||
pub legal_name: Option<String>,
|
||||
pub password: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub role: RolesDetailQueryDto,
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub mentor_id: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
use imphnen_entities::{RolesDetailItemDto, UsersDetailQueryDto, users::UserProfileExtensionDto};
|
||||
use imphnen_libs::ZodValidate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use zod_rs::prelude::*;
|
||||
use crate::users::domain::{UserEntity, UserListItem};
|
||||
|
||||
#[derive(Serialize, Deserialize, ToSchema)]
|
||||
#[schema(description = "File upload form data for multipart/form-data")]
|
||||
pub struct FileUploadSchema {
|
||||
#[schema(format = "binary")]
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersActiveInactiveRequestDto {
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersSetNewPasswordRequestDto {
|
||||
pub password: String,
|
||||
pub old_password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, ZodSchema)]
|
||||
pub struct UsersCreateRequestDto {
|
||||
#[zod(email, min_length(1))]
|
||||
pub email: String,
|
||||
#[zod(min_length(8), regex(pattern = "^[A-Za-z\\d@$!%*?&]{8,}$"))]
|
||||
pub password: String,
|
||||
#[zod(min_length(2))]
|
||||
pub fullname: String,
|
||||
pub is_active: bool,
|
||||
pub role_id: String,
|
||||
pub avatar: Option<String>,
|
||||
}
|
||||
|
||||
impl ZodValidate for UsersCreateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
Self::validate_and_parse(value).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersUpdateRequestDto {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub email: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub password: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fullname: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_active: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub role_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
}
|
||||
|
||||
impl ZodValidate for UsersUpdateRequestDto {
|
||||
fn zod_validate(value: &serde_json::Value) -> Result<Self, String> {
|
||||
serde_json::from_value(value.clone()).map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct UsersDetailItemDto {
|
||||
pub id: String,
|
||||
pub role: RolesDetailItemDto,
|
||||
pub fullname: String,
|
||||
pub legal_name: Option<String>,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl From<UserEntity> for UsersDetailItemDto {
|
||||
fn from(e: UserEntity) -> Self {
|
||||
Self {
|
||||
id: e.id,
|
||||
role: RolesDetailItemDto::from(&e.role),
|
||||
fullname: e.fullname,
|
||||
legal_name: e.legal_name,
|
||||
email: e.email,
|
||||
avatar: e.avatar,
|
||||
is_active: e.is_active,
|
||||
profile_extension: e.profile_extension,
|
||||
created_at: e.created_at,
|
||||
updated_at: e.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersListItemDto {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl From<&UsersDetailQueryDto> for UsersDetailItemDto {
|
||||
fn from(dto: &UsersDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.clone(),
|
||||
role: RolesDetailItemDto::from(&dto.role),
|
||||
fullname: dto.fullname.clone(),
|
||||
legal_name: dto.legal_name.clone(),
|
||||
email: dto.email.clone(),
|
||||
avatar: dto.avatar.clone(),
|
||||
is_active: dto.is_active,
|
||||
profile_extension: dto.profile_extension.clone(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<UserListItem> for UsersListItemDto {
|
||||
fn from(item: UserListItem) -> Self {
|
||||
Self {
|
||||
id: item.id,
|
||||
role: item.role,
|
||||
fullname: item.fullname,
|
||||
email: item.email,
|
||||
avatar: item.avatar,
|
||||
is_active: item.is_active,
|
||||
created_at: item.created_at,
|
||||
updated_at: item.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
use crate::require_permissions;
|
||||
use std::sync::Arc;
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Multipart},
|
||||
http::HeaderMap,
|
||||
response::IntoResponse,
|
||||
};
|
||||
use paginator_axum::PaginationQuery;
|
||||
use paginator_utils::PaginatorResponse;
|
||||
use imphnen_libs::{AppState, MinioConfig, FileType, decode_base64_file, extract_content_type_from_data_url, create_minio_service_from_config};
|
||||
use imphnen_utils::{ApiSuccess, ApiCreated, ApiPaginated, ApiMessage};
|
||||
use imphnen_entities::{ResponseSuccessDto, ResponseListSuccessDto, PermissionsEnum, RolesDetailQueryDto};
|
||||
use imphnen_utils::AppError;
|
||||
use crate::users::domain::{UserEntity, UserService};
|
||||
use super::dto::{
|
||||
FileUploadSchema, UsersActiveInactiveRequestDto, UsersCreateRequestDto, UsersDetailItemDto,
|
||||
UsersListItemDto, UsersUpdateRequestDto,
|
||||
};
|
||||
use imphnen_libs::hash_password;
|
||||
use serde_json::json;
|
||||
use tracing::error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/users",
|
||||
security(("Bearer" = [])),
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user list", body = ResponseListSuccessDto<Vec<UsersListItemDto>>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
PaginationQuery(params): PaginationQuery,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::ReadListUsers], {
|
||||
let result = service.list(params).await?;
|
||||
let mapped = PaginatorResponse {
|
||||
data: result.data.into_iter().map(UsersListItemDto::from).collect::<Vec<_>>(),
|
||||
meta: result.meta,
|
||||
};
|
||||
Ok(ApiPaginated(mapped))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/users/detail/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::ReadDetailUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let user = service.get(id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".to_string()));
|
||||
}
|
||||
Ok(ApiSuccess(UsersDetailItemDto::from(user)))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/users/me",
|
||||
security(("Bearer" = [])),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Get current user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let (claims, _) = crate::permissions_guard(headers, axum::extract::Extension(state.clone()), vec![]).await?;
|
||||
let user = service.get_me(claims.user_id).await?;
|
||||
if user.is_deleted {
|
||||
return Err(AppError::NotFoundError("User not found".to_string()));
|
||||
}
|
||||
Ok(ApiSuccess(UsersDetailItemDto::from(user)))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/users/create",
|
||||
security(("Bearer" = [])),
|
||||
request_body = UsersCreateRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "[ADMIN] Create new user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn post_create_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Json(payload): Json<UsersCreateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::CreateUsers], {
|
||||
let password_hash = hash_password(&payload.password)
|
||||
.map_err(|_| AppError::InternalServerError("Failed to hash password".to_string()))?;
|
||||
let role_id = payload.role_id.clone();
|
||||
let entity = UserEntity {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
email: payload.email,
|
||||
fullname: payload.fullname,
|
||||
password: password_hash,
|
||||
is_active: payload.is_active,
|
||||
avatar: payload.avatar,
|
||||
role: RolesDetailQueryDto {
|
||||
id: role_id,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let user = service.create(entity).await?;
|
||||
Ok(ApiCreated(UsersDetailItemDto::from(user)))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/users/update/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Update user")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::UpdateUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let current = service.get(id.clone()).await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
|
||||
let password = if let Some(ref pw) = payload.password {
|
||||
hash_password(pw).unwrap_or_else(|_| current.password.clone())
|
||||
} else {
|
||||
current.password.clone()
|
||||
};
|
||||
|
||||
let role_id = payload.role_id.clone().unwrap_or(current.role.id.clone());
|
||||
let entity = UserEntity {
|
||||
id: id.clone(),
|
||||
email: payload.email.unwrap_or(current.email),
|
||||
fullname: payload.fullname.unwrap_or(current.fullname),
|
||||
legal_name: payload.legal_name.or(current.legal_name),
|
||||
password,
|
||||
avatar: payload.avatar.or(current.avatar),
|
||||
is_active: payload.is_active.unwrap_or(current.is_active),
|
||||
is_deleted: current.is_deleted,
|
||||
role: RolesDetailQueryDto { id: role_id, ..current.role },
|
||||
profile_extension: payload.profile_extension.or(current.profile_extension),
|
||||
created_at: current.created_at,
|
||||
updated_at: current.updated_at,
|
||||
mentor_id: current.mentor_id,
|
||||
};
|
||||
let msg = service.update(entity).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/users/update/me",
|
||||
security(("Bearer" = [])),
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[USER] Update current user")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let (claims, _) = crate::permissions_guard(headers, axum::extract::Extension(state.clone()), vec![]).await?;
|
||||
let user_id = claims.user_id.clone();
|
||||
|
||||
let current = service.get_me(user_id).await
|
||||
.map_err(|_| AppError::NotFoundError("User not found".to_string()))?;
|
||||
|
||||
let password = if let Some(ref pw) = payload.password {
|
||||
hash_password(pw).unwrap_or_else(|_| current.password.clone())
|
||||
} else {
|
||||
current.password.clone()
|
||||
};
|
||||
|
||||
let role_id = payload.role_id.clone().unwrap_or(current.role.id.clone());
|
||||
let entity = UserEntity {
|
||||
id: current.id.clone(),
|
||||
email: payload.email.unwrap_or(current.email),
|
||||
fullname: payload.fullname.unwrap_or(current.fullname),
|
||||
legal_name: payload.legal_name.or(current.legal_name),
|
||||
password,
|
||||
avatar: payload.avatar.or(current.avatar),
|
||||
is_active: payload.is_active.unwrap_or(current.is_active),
|
||||
is_deleted: current.is_deleted,
|
||||
role: RolesDetailQueryDto { id: role_id, ..current.role },
|
||||
profile_extension: payload.profile_extension.or(current.profile_extension),
|
||||
created_at: current.created_at,
|
||||
updated_at: current.updated_at,
|
||||
mentor_id: current.mentor_id,
|
||||
};
|
||||
let msg = service.update(entity).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
path = "/v1/users/activate/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
request_body = UsersActiveInactiveRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Set user active status")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn patch_user_active_status(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersActiveInactiveRequestDto>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::ActivateUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let msg = service.set_active_status(id, payload.is_active).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/v1/users/delete/{id}",
|
||||
security(("Bearer" = [])),
|
||||
params(("id" = String, Path, description = "User ID")),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Soft delete user")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn delete_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Extension(service): Extension<Arc<dyn UserService>>,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
require_permissions!(headers, state, [PermissionsEnum::DeleteUsers], {
|
||||
Uuid::parse_str(&id)
|
||||
.map_err(|_| AppError::BadRequestError("Invalid User ID format".to_string()))?;
|
||||
let msg = service.delete(id).await?;
|
||||
Ok(ApiMessage::ok(&msg))
|
||||
})
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/users/upload",
|
||||
security(("Bearer" = [])),
|
||||
request_body(
|
||||
content = FileUploadSchema,
|
||||
description = "Upload file with multipart form data",
|
||||
content_type = "multipart/form-data"
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Upload file successfully", body = ResponseSuccessDto<serde_json::Value>),
|
||||
(status = 400, description = "[USER] Bad request"),
|
||||
(status = 401, description = "[USER] Unauthorized"),
|
||||
(status = 500, description = "[USER] Internal server error")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn upload_file(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<impl IntoResponse, AppError> {
|
||||
let (claims, _) = crate::permissions_guard(headers, axum::extract::Extension(state.clone()), vec![]).await?;
|
||||
let user_id = claims.user_id.clone();
|
||||
|
||||
let minio_config = MinioConfig::from_env()
|
||||
.map_err(|e| {
|
||||
error!("Failed to load MinIO config: {}", e);
|
||||
AppError::InternalServerError("MinIO configuration error".to_string())
|
||||
})?;
|
||||
let bucket_name = minio_config.bucket_name.clone();
|
||||
let minio_service = create_minio_service_from_config(minio_config).await
|
||||
.map_err(|e| {
|
||||
error!("Failed to initialize MinIO service: {}", e);
|
||||
AppError::InternalServerError("MinIO service initialization error".to_string())
|
||||
})?;
|
||||
|
||||
let mut file_data: Option<Vec<u8>> = None;
|
||||
let mut filename: Option<String> = None;
|
||||
let mut content_type: Option<String> = None;
|
||||
|
||||
while let Some(field) = multipart.next_field().await.unwrap_or(None) {
|
||||
let name = field.name().unwrap_or("").to_string();
|
||||
match name.as_str() {
|
||||
"file" => {
|
||||
filename = field.file_name().map(|s| s.to_string());
|
||||
content_type = field.content_type().map(|s| s.to_string());
|
||||
match field.bytes().await {
|
||||
Ok(bytes) => file_data = Some(bytes.to_vec()),
|
||||
Err(e) => {
|
||||
error!("Failed to read file data: {}", e);
|
||||
return Err(AppError::BadRequestError("Failed to read file data".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
"base64_data" => {
|
||||
let base64_str = field.text().await.unwrap_or_default();
|
||||
if !base64_str.is_empty() {
|
||||
match decode_base64_file(&base64_str) {
|
||||
Ok(decoded) => {
|
||||
file_data = Some(decoded);
|
||||
if let Some(ct) = extract_content_type_from_data_url(&base64_str) {
|
||||
content_type = Some(ct);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to decode base64 data: {}", e);
|
||||
return Err(AppError::BadRequestError("Invalid base64 data".to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"filename" => filename = Some(field.text().await.unwrap_or_default()),
|
||||
"content_type" => content_type = Some(field.text().await.unwrap_or_default()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let file_data = file_data
|
||||
.ok_or_else(|| AppError::BadRequestError("file data is required".to_string()))?;
|
||||
let filename = filename.unwrap_or_else(|| "unnamed_file".to_string());
|
||||
let content_type = content_type.unwrap_or_else(|| "application/octet-stream".to_string());
|
||||
|
||||
let file_type = {
|
||||
let ft = FileType::from_content_type(&content_type);
|
||||
if matches!(ft, FileType::Unknown) { FileType::from_filename(&filename) } else { ft }
|
||||
};
|
||||
if matches!(file_type, FileType::Unknown) {
|
||||
return Err(AppError::BadRequestError("Unsupported file type".to_string()));
|
||||
}
|
||||
if !file_type.allowed_types().contains(&content_type.as_str()) {
|
||||
return Err(AppError::BadRequestError(format!("File type does not match content type '{content_type}'")));
|
||||
}
|
||||
if file_data.len() > file_type.max_size() {
|
||||
return Err(AppError::BadRequestError(format!(
|
||||
"File too large. Maximum size for {:?} is {} bytes",
|
||||
file_type,
|
||||
file_type.max_size()
|
||||
)));
|
||||
}
|
||||
|
||||
let sanitized = user_id.replace('%', "").replace(':', "_").replace('@', "_at_").replace('.', "_");
|
||||
let folder = format!("{}/{sanitized}", file_type.as_folder());
|
||||
|
||||
let object_path = minio_service
|
||||
.upload_file_with_deduplication(&file_data, &content_type, &folder, &filename)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to upload file: {}", e);
|
||||
AppError::InternalServerError(format!("Upload failed: {e}"))
|
||||
})?;
|
||||
|
||||
let permanent_url = format!("https://cdn.asepharyana.tech/{}/{}", bucket_name, object_path);
|
||||
let response_data = json!({
|
||||
"filename": filename,
|
||||
"uploaded_path": object_path,
|
||||
"url": permanent_url,
|
||||
"size": file_data.len(),
|
||||
"content_type": content_type,
|
||||
"file_type": format!("{:?}", file_type).to_lowercase(),
|
||||
"user_id": user_id,
|
||||
});
|
||||
Ok(ApiSuccess(response_data))
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod dto;
|
||||
pub mod handlers;
|
||||
pub mod routes;
|
||||
|
||||
pub use routes::{users_public_routes, users_protected_routes};
|
||||
@@ -0,0 +1,37 @@
|
||||
use std::sync::Arc;
|
||||
use axum::{Router, routing::{delete, get, post, put}, Extension};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use imphnen_libs::AppState;
|
||||
use crate::users::application::UserServiceImpl;
|
||||
use crate::users::domain::UserService;
|
||||
use crate::users::infrastructure::persistence::PostgresUserRepository;
|
||||
use super::handlers::{
|
||||
get_user_list, get_user_by_id, get_user_me, post_create_user,
|
||||
put_update_user, put_update_user_me, patch_user_active_status,
|
||||
delete_user, upload_file,
|
||||
};
|
||||
|
||||
fn build_service(db: DatabaseConnection) -> Arc<dyn UserService> {
|
||||
let repo = Arc::new(PostgresUserRepository::new(db));
|
||||
Arc::new(UserServiceImpl::new(repo))
|
||||
}
|
||||
|
||||
pub fn users_public_routes(_db: DatabaseConnection) -> Router {
|
||||
Router::new()
|
||||
}
|
||||
|
||||
pub fn users_protected_routes(db: DatabaseConnection, state: Arc<AppState>) -> Router {
|
||||
let service = build_service(db);
|
||||
Router::new()
|
||||
.route("/users", get(get_user_list))
|
||||
.route("/users/detail/{id}", get(get_user_by_id))
|
||||
.route("/users/me", get(get_user_me))
|
||||
.route("/users/create", post(post_create_user))
|
||||
.route("/users/update/{id}", put(put_update_user))
|
||||
.route("/users/update/me", put(put_update_user_me))
|
||||
.route("/users/activate/{id}", put(patch_user_active_status))
|
||||
.route("/users/delete/{id}", delete(delete_user))
|
||||
.route("/users/upload", post(upload_file))
|
||||
.layer(Extension(service))
|
||||
.layer(Extension((*state).clone()))
|
||||
}
|
||||
Loaded 50 of 379 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user