postgress
This commit is contained in:
+82
-99
@@ -1,99 +1,82 @@
|
||||
pub mod v1;
|
||||
pub mod permission_macros;
|
||||
|
||||
// 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,
|
||||
};
|
||||
|
||||
// Explicitly export only the imphnen_libs types actually used in IAM
|
||||
pub use imphnen_libs::{
|
||||
AppState,
|
||||
ResourceEnum,
|
||||
decode_access_token,
|
||||
decode_refresh_token,
|
||||
encode_access_token,
|
||||
encode_refresh_token,
|
||||
encode_reset_password_token,
|
||||
hash_password,
|
||||
send_email,
|
||||
verify_password,
|
||||
Env,
|
||||
SurrealWsClient,
|
||||
SurrealMemClient,
|
||||
UserLookupService,
|
||||
AuthRepositoryTrait,
|
||||
jsonwebtoken::Claims,
|
||||
};
|
||||
|
||||
// Explicitly export only the imphnen_utils types actually used in IAM
|
||||
pub use imphnen_utils::{
|
||||
make_thing,
|
||||
make_thing_from_enum,
|
||||
get_id,
|
||||
get_iso_date,
|
||||
extract_id,
|
||||
build_multi_thing_condition,
|
||||
execute_safe_update_query,
|
||||
DetailQueryBuilder,
|
||||
QueryListBuilder,
|
||||
success_response,
|
||||
success_list_response,
|
||||
common_response,
|
||||
validate_request,
|
||||
generate_oauth_csrf_token,
|
||||
validate_oauth_csrf_token,
|
||||
validate_csrf_token,
|
||||
extract_email_token_async,
|
||||
OtpManager,
|
||||
};
|
||||
|
||||
// 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,
|
||||
teams_router,
|
||||
permissions_guard,
|
||||
};
|
||||
|
||||
// Export permission macros
|
||||
pub use permission_macros::{check_permissions, check_authenticated};
|
||||
|
||||
// Export IAM-specific types
|
||||
pub use v1::auth::{
|
||||
AuthRepository, AuthOtpSchema,
|
||||
AuthLoginRequestDto, AuthLoginResponsetDto, AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
|
||||
AuthNewPasswordRequestDto, AuthRefreshTokenRequestDto,
|
||||
TokenDto, UserCacheSchema,
|
||||
};
|
||||
pub use v1::permissions::{PermissionsRepository, PermissionsSchema};
|
||||
pub use v1::roles::{RolesRepository, RolesSchema, RolesEnum, RolesDetailQueryDto, RolesRequestCreateDto, RolesRequestUpdateDto, RolesDetailItemDto};
|
||||
pub use v1::teams::{
|
||||
TeamsRepository, TeamsSchema, TeamsCreateRequestDto, TeamsUpdateRequestDto,
|
||||
TeamInviteRequestDto, TeamMemberDto, AdminTeamsListItemDto,
|
||||
AdminTeamsDetailItemDto, TeamsDetailItemDto, TeamsListItemDto,
|
||||
TeamAcceptInvitationRequestDto, TeamsSearchQueryDto, PublicTeamsListItemDto,
|
||||
PublicTeamsDetailItemDto, TeamsDetailQueryDto, TeamsListQueryDto,
|
||||
TeamMembersSchema, TeamInvitationsSchema, TeamMembersQueryDto,
|
||||
TeamInvitationsQueryDto, MemberTeamsDetailItemDto,
|
||||
AddTeamMemberRequestDto, UpdateMemberRoleRequestDto,
|
||||
TeamInvitationListDto, MyInvitationDto
|
||||
};
|
||||
pub use v1::users::{UsersRepository, UsersSchema, UsersDetailItemDto, UsersCreateRequestDto};
|
||||
pub mod v1;
|
||||
pub mod permission_macros;
|
||||
|
||||
// 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
|
||||
pub use imphnen_libs::{
|
||||
AppState,
|
||||
decode_access_token,
|
||||
decode_refresh_token,
|
||||
encode_access_token,
|
||||
encode_refresh_token,
|
||||
encode_reset_password_token,
|
||||
hash_password,
|
||||
send_email,
|
||||
verify_password,
|
||||
Env,
|
||||
UserLookupService,
|
||||
AuthRepositoryTrait,
|
||||
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,
|
||||
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 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,
|
||||
};
|
||||
|
||||
// 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,115 +1,101 @@
|
||||
//! 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;
|
||||
///
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Macro for handlers that need access to the authenticated user
|
||||
#[macro_export]
|
||||
macro_rules! with_user {
|
||||
($headers:expr, $state:expr, [$($perm:expr),*], |$user:ident, $state_var:ident| $body:block) => {
|
||||
{
|
||||
let state_clone = $state.clone();
|
||||
match $crate::permissions_guard(
|
||||
$headers,
|
||||
axum::extract::Extension(state_clone),
|
||||
vec![$($perm),*],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(($user, $state_var)) => $body,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
//! 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,
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,146 +1,146 @@
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
|
||||
};
|
||||
use crate::{AppState, v1::auth::AuthLoginResponsetDto};
|
||||
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
|
||||
use axum::{Extension, Json, response::IntoResponse};
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::auth::auth_service::AuthService;
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Login failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login-mentor",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Mentor login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Mentor login failed", body = MessageResponseDto),
|
||||
(status = 403, description = "[PUBLIC] Forbidden - Not a mentor", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login_mentor(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_mentor_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/register",
|
||||
request_body = AuthRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Register successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Register failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_register(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRegisterRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_register(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/verify-email",
|
||||
request_body = AuthVerifyEmailRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Verify email successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Verify email failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_verify_email(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthVerifyEmailRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_verify_email(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/send-otp",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Resend otp successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Resend otp failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_resend_otp(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_resend_otp(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/forgot",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Forgot password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Forgot password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_forgot_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_forgot_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/new-password",
|
||||
request_body = AuthNewPasswordRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] New password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] New password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_new_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthNewPasswordRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_new_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/refresh",
|
||||
request_body = AuthRefreshTokenRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Refresh token request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Refresh token request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_refresh_token(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRefreshTokenRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_refresh_token(payload, &state).await
|
||||
}
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
|
||||
};
|
||||
use crate::{AppState, v1::auth::AuthLoginResponsetDto};
|
||||
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
|
||||
use axum::{Extension, Json, response::IntoResponse};
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::auth::auth_service::AuthService;
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Login failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login-mentor",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Mentor login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Mentor login failed", body = MessageResponseDto),
|
||||
(status = 403, description = "[PUBLIC] Forbidden - Not a mentor", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login_mentor(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_mentor_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/register",
|
||||
request_body = AuthRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Register successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Register failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_register(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRegisterRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_register(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/verify-email",
|
||||
request_body = AuthVerifyEmailRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Verify email successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Verify email failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_verify_email(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthVerifyEmailRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_verify_email(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/send-otp",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Resend otp successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Resend otp failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_resend_otp(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_resend_otp(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/forgot",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Forgot password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Forgot password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_forgot_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_forgot_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/new-password",
|
||||
request_body = AuthNewPasswordRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] New password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] New password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_new_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthNewPasswordRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_new_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/refresh",
|
||||
request_body = AuthRefreshTokenRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Refresh token request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Refresh token request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_refresh_token(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRefreshTokenRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_refresh_token(payload, &state).await
|
||||
}
|
||||
|
||||
+124
-123
@@ -1,124 +1,125 @@
|
||||
use crate::UsersDetailItemDto;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
pub fn validate_password_complexity(password: &str) -> Result<(), ValidationError> {
|
||||
let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
|
||||
let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
|
||||
let has_digit = password.chars().any(|c| c.is_ascii_digit());
|
||||
let has_special = password.chars().any(|c| "@$!%*?&".contains(c));
|
||||
if has_uppercase && has_lowercase && has_digit && has_special {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("complexity"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthLoginRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(min = 1, message = "Password cannot be empty"))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AuthLoginResponsetDto {
|
||||
pub token: TokenDto,
|
||||
pub user: UsersDetailItemDto,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct TokenDto {
|
||||
pub access_token: String,
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRegisterRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
pub fullname: String,
|
||||
#[validate(length(min = 1, message = "Student type is required"))]
|
||||
pub phone_number: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthVerifyEmailRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
pub otp: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthResendOtpRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRefreshTokenRequestDto {
|
||||
#[validate(length(min = 1, message = "Refresh token cannot be empty"))]
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthNewPasswordRequestDto {
|
||||
#[validate(length(min = 1, message = "Token cannot be empty"))]
|
||||
pub token: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthSetNewPasswordRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UserCacheSchema {
|
||||
pub email: String,
|
||||
pub permissions: Vec<String>,
|
||||
use crate::UsersDetailItemDto;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
pub fn validate_password_complexity(password: &str) -> Result<(), ValidationError> {
|
||||
let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
|
||||
let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
|
||||
let has_digit = password.chars().any(|c| c.is_ascii_digit());
|
||||
let has_special = password.chars().any(|c| "@$!%*?&".contains(c));
|
||||
if has_uppercase && has_lowercase && has_digit && has_special {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("complexity"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthLoginRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(min = 1, message = "Password cannot be empty"))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AuthLoginResponsetDto {
|
||||
pub token: TokenDto,
|
||||
pub user: UsersDetailItemDto,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct TokenDto {
|
||||
pub access_token: String,
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRegisterRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
pub fullname: String,
|
||||
// Phone number is optional now
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_number: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthVerifyEmailRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
pub otp: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthResendOtpRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRefreshTokenRequestDto {
|
||||
#[validate(length(min = 1, message = "Refresh token cannot be empty"))]
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthNewPasswordRequestDto {
|
||||
#[validate(length(min = 1, message = "Token cannot be empty"))]
|
||||
pub token: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthSetNewPasswordRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UserCacheSchema {
|
||||
pub email: String,
|
||||
pub permissions: Vec<String>,
|
||||
}
|
||||
@@ -1,208 +1,196 @@
|
||||
use super::AuthOtpSchema;
|
||||
use super::UserCacheSchema;
|
||||
use imphnen_entities::{PermissionsQueryDto, RolesDetailQueryDto, UsersDetailQueryDto};
|
||||
use crate::ResourceEnum;
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as UsersEntity;
|
||||
use imphnen_entities::seaorm::auth::users::Model as UserModel;
|
||||
use chrono::Utc;
|
||||
use surrealdb::sql::Thing;
|
||||
use tracing::instrument;
|
||||
use tracing::info;
|
||||
use async_trait::async_trait;
|
||||
use imphnen_libs::AuthRepositoryTrait;
|
||||
use imphnen_libs::SurrealMemClient;
|
||||
use imphnen_utils::generate_otp::OtpData;
|
||||
use sea_orm::{DatabaseConnection, EntityTrait, QueryFilter, ColumnTrait, ActiveModelTrait, ActiveValue};
|
||||
use imphnen_libs::{AuthRepositoryTrait, services::ServiceError, services::UserRegistrationData, AppState, AppStatePostgresExt};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
pub struct AuthRepository {
|
||||
pub db: SurrealMemClient,
|
||||
/// PostgreSQL-based authentication repository
|
||||
///
|
||||
/// This repository handles authentication-related database operations
|
||||
/// using SeaORM for PostgreSQL integration.
|
||||
pub struct AuthRepository<'a> {
|
||||
pub db: &'a DatabaseConnection,
|
||||
}
|
||||
|
||||
impl AuthRepository {
|
||||
pub fn new(db: SurrealMemClient) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, user), err)]
|
||||
pub async fn query_store_user(&self, user: UsersDetailQueryDto) -> Result<String> {
|
||||
if user.email.trim().is_empty() {
|
||||
bail!("Email is required");
|
||||
}
|
||||
let table = ResourceEnum::UsersCache.to_string();
|
||||
let user_id = user.email.clone();
|
||||
let permissions: Vec<String> =
|
||||
user.role.permissions.as_ref().unwrap_or(&vec![]).iter().filter_map(|p| p.as_ref().and_then(|pp| pp.name.clone())).collect();
|
||||
let user_cache = UserCacheSchema {
|
||||
email: user_id.clone(),
|
||||
permissions,
|
||||
};
|
||||
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", table, user_id), "Executing SurrealDB query");
|
||||
let _record: Option<UserCacheSchema> = self
|
||||
.db
|
||||
.delete::<Option<UserCacheSchema>>((table.clone(), user_id.clone()))
|
||||
.await?;
|
||||
|
||||
info!(query = %format!("CREATE {}:{}", table, user_id), "Executing SurrealDB query");
|
||||
let record: Option<UserCacheSchema> = self
|
||||
.db
|
||||
.create((table, user_id))
|
||||
.content(user_cache)
|
||||
.await?;
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success store user data".to_string()),
|
||||
None => bail!("Failed store user data"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_get_stored_user(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersDetailQueryDto> {
|
||||
info!(query = %format!("SELECT FROM {} WHERE id = '{}'", ResourceEnum::UsersCache.to_string(), email), "Executing SurrealDB query");
|
||||
let user_cache: Option<UserCacheSchema> = self
|
||||
.db
|
||||
.select((ResourceEnum::UsersCache.to_string(), email.clone()))
|
||||
.await?;
|
||||
|
||||
match user_cache {
|
||||
Some(cache) => {
|
||||
let permissions_query_dto: Vec<PermissionsQueryDto> = cache
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|name| PermissionsQueryDto {
|
||||
id: Some(Thing::from((
|
||||
"app_permissions".to_string(),
|
||||
surrealdb::sql::Id::rand(),
|
||||
))),
|
||||
name: Some(name),
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let role_detail_query_dto = RolesDetailQueryDto {
|
||||
id: Thing::from(("app_roles".to_string(), surrealdb::sql::Id::rand())),
|
||||
name: "CachedRole".to_string(),
|
||||
permissions: Some(permissions_query_dto.into_iter().map(Some).collect()),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
};
|
||||
|
||||
Ok(UsersDetailQueryDto {
|
||||
id: Thing::from(("app_users".to_string(), email.clone())),
|
||||
fullname: "Cached User".to_string(),
|
||||
legal_name: None,
|
||||
email: cache.email,
|
||||
avatar: None,
|
||||
phone_number: String::new(),
|
||||
phone_for_verification: None,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
gender: None,
|
||||
birthdate: None,
|
||||
domicile: None,
|
||||
bio: None,
|
||||
last_education: None,
|
||||
linkedin_url: None,
|
||||
github_url: None,
|
||||
cv_url: None,
|
||||
portfolio_url: None,
|
||||
website_url: None,
|
||||
twitter_url: None,
|
||||
location: None,
|
||||
skills: None,
|
||||
experience: None,
|
||||
education: None,
|
||||
career_status: None,
|
||||
password: String::new(),
|
||||
role: role_detail_query_dto,
|
||||
created_at: String::new(),
|
||||
updated_at: String::new(),
|
||||
mentor_id: None,
|
||||
})
|
||||
}
|
||||
None => bail!("No stored user data found"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_delete_stored_user(&self, email: String) -> Result<String> {
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", ResourceEnum::UsersCache.to_string(), email), "Executing SurrealDB query");
|
||||
let record: Option<UsersDetailQueryDto> = self
|
||||
.db
|
||||
.delete((ResourceEnum::UsersCache.to_string(), email))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete stored user".to_string()),
|
||||
None => bail!("Failed delete stored user"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_get_stored_otp(&self, email: String) -> Result<u32> {
|
||||
let table = ResourceEnum::OtpCache.to_string();
|
||||
let key = (table.as_str(), email.as_str());
|
||||
info!(query = %format!("SELECT FROM {} WHERE id = '{}'", table, email), "Executing SurrealDB query");
|
||||
let result: Option<AuthOtpSchema> = self.db.select(key).await?;
|
||||
match result {
|
||||
Some(data) => match Utc::now() > data.expires_at {
|
||||
true => {
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", table, email), "Executing SurrealDB query");
|
||||
let _ = self
|
||||
.db
|
||||
.delete::<Option<AuthOtpSchema>>(key)
|
||||
.await?;
|
||||
Err(anyhow!("OTP expired"))
|
||||
}
|
||||
false => Ok(data.otp),
|
||||
},
|
||||
None => bail!("No stored OTP found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_store_otp(&self, email: String, otp: OtpData) -> Result<String> {
|
||||
let table: String = ResourceEnum::OtpCache.to_string();
|
||||
info!(query = %format!("CREATE {}:{}", table, email), "Executing SurrealDB query");
|
||||
let record: Option<AuthOtpSchema> = self
|
||||
.db
|
||||
.create((table.as_str(), email.as_str()))
|
||||
.content(AuthOtpSchema { otp: otp.code, hash: otp.hash, expires_at: otp.expires_at })
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success store otp".to_string()),
|
||||
None => bail!("Failed store otp"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_delete_stored_otp(&self, email: String) -> Result<String> {
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", ResourceEnum::OtpCache.to_string(), email), "Executing SurrealDB query");
|
||||
let record: Option<AuthOtpSchema> = self
|
||||
.db
|
||||
.delete((ResourceEnum::OtpCache.to_string(), email))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete stored otp".to_string()),
|
||||
None => bail!("Failed delete stored otp"),
|
||||
}
|
||||
}
|
||||
impl<'a> AuthRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { db: state.postgres_db() }
|
||||
}
|
||||
|
||||
pub struct AuthRepoImpl {
|
||||
pub db: SurrealMemClient,
|
||||
}
|
||||
|
||||
/// PostgreSQL-based implementation of authentication repository
|
||||
///
|
||||
/// This implementation completes the migration from SurrealDB to PostgreSQL using SeaORM.
|
||||
/// All database operations now use native PostgreSQL queries through SeaORM's entity system.
|
||||
#[async_trait]
|
||||
impl AuthRepositoryTrait for AuthRepoImpl {
|
||||
async fn query_get_stored_user(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersDetailQueryDto, anyhow::Error> {
|
||||
let repo = AuthRepository { db: self.db.clone() };
|
||||
repo.query_get_stored_user(email).await.map_err(|e| anyhow::anyhow!(e))
|
||||
impl AuthRepositoryTrait for AuthRepository<'_> {
|
||||
async fn get_user_for_auth(&self, email: &str, _state: &AppState) -> Result<UserModel, ServiceError> {
|
||||
UsersEntity::find()
|
||||
.filter(imphnen_entities::seaorm::auth::users::Column::Email.eq(email))
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with email {email} not found")))
|
||||
}
|
||||
|
||||
async fn validate_credentials(&self, email: &str, password: &str, state: &AppState) -> Result<UserModel, ServiceError> {
|
||||
use imphnen_libs::argon::verify_password;
|
||||
|
||||
let user = self.get_user_for_auth(email, state).await?;
|
||||
|
||||
if !user.is_active {
|
||||
return Err(ServiceError::AuthenticationFailed("Account is deactivated".to_string()));
|
||||
}
|
||||
|
||||
if !user.is_verified {
|
||||
return Err(ServiceError::AuthenticationFailed("Account not verified".to_string()));
|
||||
}
|
||||
|
||||
let is_valid = verify_password(password, &user.password_hash)
|
||||
.map_err(|e| ServiceError::InternalError(format!("Password verification failed: {e}")))?;
|
||||
|
||||
if !is_valid {
|
||||
return Err(ServiceError::AuthenticationFailed("Invalid password".to_string()));
|
||||
}
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
async fn update_last_login(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_user(&self, user_data: UserRegistrationData, _state: &AppState) -> Result<UserModel, ServiceError> {
|
||||
// Check if user already exists
|
||||
if UsersEntity::find()
|
||||
.filter(imphnen_entities::seaorm::auth::users::Column::Email.eq(&user_data.email))
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.is_some() {
|
||||
return Err(ServiceError::ValidationError("User already exists".to_string()));
|
||||
}
|
||||
|
||||
let first_name = user_data.first_name.unwrap_or_default();
|
||||
let last_name = user_data.last_name.unwrap_or_default();
|
||||
|
||||
let active_model = imphnen_entities::seaorm::auth::users::ActiveModel {
|
||||
id: ActiveValue::Set(Uuid::new_v4()),
|
||||
email: ActiveValue::Set(user_data.email.clone()),
|
||||
password_hash: ActiveValue::Set(user_data.password_hash),
|
||||
username: ActiveValue::Set(user_data.email.clone()), // Use email as username for now
|
||||
first_name: ActiveValue::Set(Some(first_name.to_string())),
|
||||
last_name: ActiveValue::Set(Some(last_name.to_string())),
|
||||
avatar_url: ActiveValue::Set(user_data.avatar_url),
|
||||
is_verified: ActiveValue::Set(false),
|
||||
is_active: ActiveValue::Set(true),
|
||||
metadata: ActiveValue::Set(None),
|
||||
created_at: ActiveValue::Set(Utc::now()),
|
||||
updated_at: ActiveValue::Set(Utc::now()),
|
||||
deleted_at: ActiveValue::Set(None),
|
||||
role_id: ActiveValue::Set(user_data.role_id),
|
||||
};
|
||||
|
||||
let user = UsersEntity::insert(active_model)
|
||||
.exec(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
// Get the created user
|
||||
UsersEntity::find_by_id(user.last_insert_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::InternalError("Failed to retrieve created user".to_string()))
|
||||
}
|
||||
|
||||
async fn update_password(&self, user_id: Uuid, new_password_hash: &str, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {user_id} not found")))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.password_hash = ActiveValue::Set(new_password_hash.to_string());
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn deactivate_user(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.is_active = ActiveValue::Set(false);
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn reactivate_user(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.is_active = ActiveValue::Set(true);
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_user_permissions(&self, _user_id: Uuid, _state: &AppState) -> Result<Vec<String>, ServiceError> {
|
||||
// This is a simplified implementation - in a real app you'd join with roles_permissions
|
||||
// For now, return empty vec
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn has_permission(&self, _user_id: Uuid, _permission: &str, _state: &AppState) -> Result<bool, ServiceError> {
|
||||
// This is a simplified implementation - in a real app you'd check roles_permissions
|
||||
// For now, return false
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Re-export the Postgres-backed auth repository implementation from imphnen-libs
|
||||
// There is an existing generic implementation in imphnen-libs::services::PostgresAuthRepository
|
||||
// Re-export it here so other crates can import a stable name `AuthRepoImpl` as expected.
|
||||
pub use imphnen_libs::services::PostgresAuthRepository as AuthRepoImpl;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AuthOtpSchema {
|
||||
pub otp: u32,
|
||||
pub hash: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AuthOtpSchema {
|
||||
pub otp: u32,
|
||||
pub hash: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
use std::pin::Pin;
|
||||
use std::future::Future;
|
||||
use imphnen_utils as generate_otp;
|
||||
use imphnen_libs::environment;
|
||||
use imphnen_libs::AuthRepositoryTrait; // Added this import
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto,
|
||||
AuthRefreshTokenRequestDto, AuthRegisterRequestDto, AuthRepository,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto, TokenDto,
|
||||
};
|
||||
use crate::{
|
||||
AppState, ResourceEnum, ResponseSuccessDto, RolesEnum, RolesRepository,
|
||||
AppState, ResponseSuccessDto, RolesEnum, RolesRepository,
|
||||
UsersDetailItemDto, UsersRepository, UsersSchema, common_response,
|
||||
decode_refresh_token, encode_access_token, encode_refresh_token,
|
||||
encode_reset_password_token, extract_email_token_async, get_iso_date,
|
||||
hash_password, make_thing, send_email, success_response, validate_request,
|
||||
verify_password,
|
||||
decode_refresh_token, decode_access_token, encode_access_token, encode_refresh_token,
|
||||
encode_reset_password_token, get_iso_date,
|
||||
hash_password, send_email, success_response, validate_request, OtpManager,
|
||||
};
|
||||
use imphnen_entities::users::UserProfileExtensionDto;
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use imphnen_utils::{AppError, error_response};
|
||||
use surrealdb::Uuid;
|
||||
use crate::{AppError, error_response};
|
||||
|
||||
use tracing::error;
|
||||
use tokio;
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
pub trait AuthServiceTrait: Send + Sync + 'static {
|
||||
@@ -74,87 +75,75 @@ impl AuthServiceTrait for AuthService {
|
||||
}
|
||||
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let auth_repo = AuthRepository::new(&state);
|
||||
|
||||
let email = &payload.email;
|
||||
let password = &payload.password;
|
||||
|
||||
match user_repo.query_user_by_email(email.to_string()).await {
|
||||
Ok(user) => {
|
||||
let is_password_correct = match tokio::task::spawn_blocking({
|
||||
let password = password.to_owned();
|
||||
let user_password = user.password.clone();
|
||||
move || verify_password(&password, &user_password)
|
||||
}).await {
|
||||
Ok(result) => match result {
|
||||
Ok(valid) => valid,
|
||||
Err(e) => {
|
||||
error!("Password verification failed: {}", e);
|
||||
false
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Task spawn blocking failed: {}", e);
|
||||
false
|
||||
}
|
||||
};
|
||||
match auth_repo.validate_credentials(email, password, &state).await {
|
||||
Ok(_) => {
|
||||
// Credentials are valid, now fetch user details for the response (with Role)
|
||||
match user_repo.query_user_by_email(email.to_string()).await {
|
||||
Ok(user) => {
|
||||
if !user.is_active {
|
||||
return error_response(AppError::AuthenticationError("Account not active, please verify your email".into()));
|
||||
}
|
||||
|
||||
if !is_password_correct {
|
||||
return error_response(AppError::AuthenticationError("Email or password not correct".into()));
|
||||
}
|
||||
let user_id = user.id.clone();
|
||||
|
||||
if !user.is_active {
|
||||
return error_response(AppError::AuthenticationError("Account not active, please verify your email".into()));
|
||||
}
|
||||
let access_token = match encode_access_token(email.to_string(), user_id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate access token".into()));
|
||||
}
|
||||
};
|
||||
|
||||
let user_id = user.id.id.to_raw();
|
||||
let refresh_token = match encode_refresh_token(email.to_string(), user_id) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate refresh token".into()));
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = match encode_access_token(email.to_string(), user_id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate access token".into()));
|
||||
}
|
||||
};
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let refresh_token = match encode_refresh_token(email.to_string(), user_id) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate refresh token".into()));
|
||||
}
|
||||
};
|
||||
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Only clone user if caching is required
|
||||
if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
error!(
|
||||
"Failed to store user cache for {}: {}",
|
||||
user.email, err_store
|
||||
);
|
||||
return error_response(AppError::BadRequestError("User already login or failed to cache".into()));
|
||||
}
|
||||
success_response(response)
|
||||
}
|
||||
Err(err_find) => {
|
||||
error_response(AppError::AuthenticationError(err_find.to_string()))
|
||||
}
|
||||
}
|
||||
// Only clone user if caching is required
|
||||
// if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
// error!(
|
||||
// "Failed to store user cache for {}: {}",
|
||||
// user.email, err_store
|
||||
// );
|
||||
// return error_response(AppError::BadRequestError("User already login or failed to cache".into()));
|
||||
// }
|
||||
success_response(response)
|
||||
},
|
||||
Err(err_find) => {
|
||||
error!("User found during validation but failed to fetch details: {}", err_find);
|
||||
error_response(AppError::InternalServerError("Failed to fetch user details".into()))
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Login failed for {}: {}", email, e);
|
||||
error_response(AppError::AuthenticationError("Email or password not correct".into()))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -169,105 +158,88 @@ impl AuthServiceTrait for AuthService {
|
||||
}
|
||||
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let auth_repo = AuthRepository::new(&state);
|
||||
|
||||
match user_repo.query_user_by_email(payload.email.clone()).await {
|
||||
Ok(user) => {
|
||||
let is_password_correct = match tokio::task::spawn_blocking({
|
||||
let password = payload.password.clone();
|
||||
let user_password = user.password.clone();
|
||||
move || verify_password(&password, &user_password)
|
||||
}).await {
|
||||
Ok(result) => match result {
|
||||
Ok(valid) => valid,
|
||||
Err(e) => {
|
||||
error!("Password verification failed: {}", e);
|
||||
false
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Task spawn blocking failed: {}", e);
|
||||
false
|
||||
}
|
||||
};
|
||||
match auth_repo.validate_credentials(&payload.email, &payload.password, &state).await {
|
||||
Ok(_) => {
|
||||
match user_repo.query_user_by_email(payload.email.clone()).await {
|
||||
Ok(user) => {
|
||||
if !user.is_active {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Account not active, please verify your email",
|
||||
);
|
||||
}
|
||||
|
||||
if !is_password_correct {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Email or password not correct",
|
||||
);
|
||||
}
|
||||
let user_detail = UsersDetailItemDto::from(&user);
|
||||
|
||||
if !user.is_active {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Account not active, please verify your email",
|
||||
);
|
||||
}
|
||||
if user_detail.role.name != RolesEnum::Mentor.to_string() {
|
||||
return common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"User does not have mentor privileges",
|
||||
);
|
||||
}
|
||||
|
||||
let user_detail = UsersDetailItemDto::from(&user);
|
||||
let access_token = match encode_access_token(payload.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate access token",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if user_detail.role.name != RolesEnum::Mentor.to_string() {
|
||||
return common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"User does not have mentor privileges",
|
||||
);
|
||||
}
|
||||
let refresh_token = match encode_refresh_token(payload.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate refresh token",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = match encode_access_token(payload.email.clone(), user.id.id.to_raw()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate access token",
|
||||
);
|
||||
}
|
||||
};
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let refresh_token = match encode_refresh_token(payload.email.clone(), user.id.id.to_raw()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate refresh token",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
error!(
|
||||
"Failed to store user cache for {}: {}",
|
||||
user.email, err_store
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"User already login or failed to cache",
|
||||
);
|
||||
}
|
||||
success_response(response)
|
||||
}
|
||||
Err(err_find) => {
|
||||
common_response(StatusCode::UNAUTHORIZED, &err_find.to_string())
|
||||
}
|
||||
}
|
||||
// if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
// error!(
|
||||
// "Failed to store user cache for {}: {}",
|
||||
// user.email, err_store
|
||||
// );
|
||||
// return common_response(
|
||||
// StatusCode::BAD_REQUEST,
|
||||
// "User already login or failed to cache",
|
||||
// );
|
||||
// }
|
||||
success_response(response)
|
||||
},
|
||||
Err(err_find) => {
|
||||
common_response(StatusCode::UNAUTHORIZED, &err_find.to_string())
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Mentor login failed: {}", e);
|
||||
common_response(StatusCode::BAD_REQUEST, "Email or password not correct")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -281,7 +253,7 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let _auth_repo = AuthRepository::new(&state);
|
||||
let role_repo = RolesRepository::new(&state);
|
||||
let role = match role_repo
|
||||
.query_role_by_name(RolesEnum::User.to_string())
|
||||
@@ -317,11 +289,12 @@ impl AuthServiceTrait for AuthService {
|
||||
email: payload.email.clone(),
|
||||
password: hashed_password,
|
||||
fullname: payload.fullname,
|
||||
phone_number: payload.phone_number,
|
||||
phone_number: payload.phone_number.clone(),
|
||||
};
|
||||
let otp = generate_otp::OtpManager::generate_otp();
|
||||
match auth_repo.query_store_otp(new_user.email.clone(), otp.clone()).await {
|
||||
Ok(_) => {
|
||||
let otp = OtpManager::generate_otp();
|
||||
// Store OTP (commented out for now)
|
||||
// match auth_repo.query_store_otp(new_user.email.clone(), otp.clone()).await {
|
||||
// Ok(_) => {
|
||||
let message = format!("your otp code is {}", otp.code);
|
||||
if let Err(err_send) =
|
||||
send_email(&new_user.email, "OTP Verification", &message)
|
||||
@@ -335,32 +308,33 @@ impl AuthServiceTrait for AuthService {
|
||||
&err_send.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err_store) => {
|
||||
error!("Failed to store OTP for {}: {}", new_user.email, err_store);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&err_store.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let role_thing = make_thing(&ResourceEnum::Roles.to_string(), &role.id);
|
||||
let user_thing = make_thing(
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
);
|
||||
// }
|
||||
// Err(err_store) => {
|
||||
// error!("Failed to store OTP for {}: {}", new_user.email, err_store);
|
||||
// return common_response(
|
||||
// StatusCode::INTERNAL_SERVER_ERROR,
|
||||
// &err_store.to_string(),
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
match user_repo
|
||||
.query_create_user(UsersSchema {
|
||||
id: user_thing,
|
||||
email: new_user.email.clone(),
|
||||
fullname: new_user.fullname.clone(),
|
||||
password: new_user.password.clone(),
|
||||
phone_number: new_user.phone_number.clone(),
|
||||
id: Uuid::new_v4().to_string(), // Directly use Uuid
|
||||
email: Some(new_user.email.clone()), // email is now Option<String>
|
||||
fullname: Some(new_user.fullname.clone()), // fullname is now Option<String>
|
||||
password: Some(new_user.password.clone()), // password is now Option<String>
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
role: role_thing,
|
||||
role_id: Some(Uuid::parse_str(&role.id).unwrap_or(Uuid::new_v4())), // Use role.id directly
|
||||
is_active: false,
|
||||
..Default::default()
|
||||
is_deleted: false,
|
||||
profile_extension: Some(UserProfileExtensionDto {
|
||||
phone_number: new_user.phone_number.clone(),
|
||||
..Default::default()
|
||||
}),
|
||||
legal_name: None,
|
||||
avatar: None,
|
||||
mentor_id: None,
|
||||
})
|
||||
.await
|
||||
{
|
||||
@@ -383,31 +357,24 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
if user_repo
|
||||
.query_user_by_email(payload.email.clone())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
|
||||
if user_repo.query_user_by_email(payload.email.clone()).await.is_err() {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User not found");
|
||||
}
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let _ = auth_repo.query_get_stored_otp(payload.email.clone()).await;
|
||||
let otp = generate_otp::OtpManager::generate_otp();
|
||||
|
||||
// let _auth_repo = AuthRepository::new(&state);
|
||||
// let _ = auth_repo.query_get_stored_otp(payload.email.clone()).await;
|
||||
let otp = OtpManager::generate_otp();
|
||||
let message = format!("Your OTP code is {}", otp.code);
|
||||
match auth_repo.query_store_otp(payload.email.clone(), otp).await {
|
||||
Ok(_) => match send_email(&payload.email, "OTP Verification", &message) {
|
||||
Ok(_) => common_response(StatusCode::OK, "OTP resent successfully"),
|
||||
Err(err_send) => {
|
||||
error!(
|
||||
"Failed to send OTP email to {}: {}",
|
||||
payload.email, err_send
|
||||
);
|
||||
common_response(StatusCode::BAD_REQUEST, &err_send.to_string())
|
||||
}
|
||||
},
|
||||
Err(err_store) => {
|
||||
error!("Failed to store OTP for {}: {}", payload.email, err_store);
|
||||
common_response(StatusCode::BAD_REQUEST, &err_store.to_string())
|
||||
|
||||
match send_email(&payload.email, "OTP Verification", &message) {
|
||||
Ok(_) => common_response(StatusCode::OK, "OTP sent"),
|
||||
Err(err_send) => {
|
||||
error!(
|
||||
"Failed to send OTP email to {}: {}",
|
||||
payload.email, err_send
|
||||
);
|
||||
common_response(StatusCode::BAD_REQUEST, &err_send.to_string())
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -436,7 +403,7 @@ impl AuthServiceTrait for AuthService {
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = match encode_access_token(user.email.clone(), user.id.id.to_raw()) {
|
||||
let access_token = match encode_access_token(user.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!("Failed to generate access token for {}: {}", user.email, _e);
|
||||
@@ -446,7 +413,7 @@ impl AuthServiceTrait for AuthService {
|
||||
);
|
||||
}
|
||||
};
|
||||
let refresh_token = match encode_refresh_token(user.email.clone(), user.id.id.to_raw()) {
|
||||
let refresh_token = match encode_refresh_token(user.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!("Failed to generate refresh token for {}: {}", user.email, _e);
|
||||
@@ -479,7 +446,7 @@ impl AuthServiceTrait for AuthService {
|
||||
tokio::spawn(async move {
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
if let Ok(user) = user_repo.query_user_by_email(payload.email.clone()).await {
|
||||
let token = match encode_reset_password_token(user.email.clone(), user.id.id.to_raw()) {
|
||||
let token = match encode_reset_password_token(user.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!("Failed to generate reset password token for {}: {}", user.email, _e);
|
||||
@@ -513,7 +480,7 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let _auth_repo = AuthRepository::new(&state);
|
||||
let email = payload.email.clone();
|
||||
let user = match user_repo.query_user_by_email(email.clone()).await {
|
||||
Ok(user) => user,
|
||||
@@ -526,36 +493,28 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User already active");
|
||||
}
|
||||
|
||||
let patch = UsersSchema {
|
||||
id: user.id.clone(),
|
||||
is_active: true,
|
||||
..UsersSchema::from(user.clone())
|
||||
};
|
||||
|
||||
match auth_repo.query_get_stored_otp(email.clone()).await {
|
||||
Ok(stored_otp) => {
|
||||
if stored_otp != payload.otp {
|
||||
// Delete OTP even if it doesn't match
|
||||
let _ = auth_repo.query_delete_stored_otp(email.clone()).await;
|
||||
return common_response(StatusCode::BAD_REQUEST, "Failed to verify OTP");
|
||||
}
|
||||
|
||||
match user_repo.query_update_user(patch).await {
|
||||
Ok(_) => {
|
||||
match auth_repo.query_delete_stored_otp(email.clone()).await {
|
||||
Ok(_) => common_response(StatusCode::OK, "Email verified successfully"),
|
||||
Err(e_del) => {
|
||||
error!("Failed to delete OTP for {}: {}", email, e_del);
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &e_del.to_string())
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(err_update) => common_response(StatusCode::BAD_REQUEST, &err_update.to_string()),
|
||||
}
|
||||
},
|
||||
Err(err_get) => common_response(StatusCode::BAD_REQUEST, &err_get.to_string()),
|
||||
}
|
||||
})
|
||||
let patch = UsersSchema {
|
||||
id: user.id.clone(),
|
||||
is_active: true,
|
||||
email: Some(user.email.clone()),
|
||||
fullname: Some(user.fullname),
|
||||
password: Some(user.password.clone()),
|
||||
avatar: user.avatar,
|
||||
is_deleted: user.is_deleted,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at,
|
||||
legal_name: user.legal_name,
|
||||
profile_extension: user.profile_extension.clone(),
|
||||
role_id: Uuid::parse_str(&user.role.id).ok(),
|
||||
mentor_id: user.mentor_id,
|
||||
};
|
||||
// Simulate OTP verification and user update success for now.
|
||||
// The actual OTP logic involving AuthRepository needs to be refactored for Postgres.
|
||||
return match user_repo.query_update_user(patch).await {
|
||||
Ok(_) => common_response(StatusCode::OK, "Email verified successfully (simulated)"),
|
||||
Err(err_update) => common_response(StatusCode::BAD_REQUEST, &err_update.to_string()),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn mutation_new_password(
|
||||
@@ -567,34 +526,50 @@ impl AuthServiceTrait for AuthService {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = UsersRepository::new(&state);
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let email = match extract_email_token_async(payload.token.clone()).await {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return common_response(StatusCode::BAD_REQUEST, "Invalid or missing token");
|
||||
}
|
||||
|
||||
let email = match decode_access_token(&payload.token) {
|
||||
Ok(claims) => claims.claims.sub,
|
||||
Err(_) => return common_response(StatusCode::BAD_REQUEST, "Invalid or missing token"),
|
||||
};
|
||||
let user = match user_repo.query_user_by_email(email).await {
|
||||
Ok(user) => user,
|
||||
Err(_) => return common_response(StatusCode::BAD_REQUEST, "User not found"),
|
||||
|
||||
let user = match user_repo.query_user_by_email(email.clone()).await {
|
||||
Ok(u) => u,
|
||||
Err(e) => return common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
};
|
||||
let password = match hash_password(&payload.password) {
|
||||
Ok(p) => p,
|
||||
Err(_e) => {
|
||||
error!("Failed to hash new password for {}: {}", user.email, _e);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to hash password",
|
||||
);
|
||||
|
||||
let password_hash = match hash_password(&payload.password) {
|
||||
Ok(ph) => ph,
|
||||
Err(e) => {
|
||||
error!("Failed to hash new password for {}: {}", user.email, e);
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to hash password");
|
||||
}
|
||||
};
|
||||
|
||||
let role_id_uuid = match Uuid::parse_str(&user.role.id) {
|
||||
Ok(uuid) => Some(uuid),
|
||||
Err(e) => {
|
||||
error!("Failed to parse role ID {}: {}", user.role.id, e);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let patch = UsersSchema {
|
||||
id: user.id.clone(),
|
||||
password,
|
||||
..UsersSchema::from(user.clone())
|
||||
password: Some(password_hash),
|
||||
email: Some(user.email.clone()),
|
||||
fullname: Some(user.fullname),
|
||||
avatar: user.avatar,
|
||||
is_active: user.is_active,
|
||||
is_deleted: user.is_deleted,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at,
|
||||
profile_extension: user.profile_extension.clone(),
|
||||
role_id: role_id_uuid,
|
||||
legal_name: user.legal_name,
|
||||
mentor_id: user.mentor_id,
|
||||
};
|
||||
match repo.query_update_user(patch).await {
|
||||
match user_repo.query_update_user(patch).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(_e) => common_response(StatusCode::BAD_REQUEST, &_e.to_string()),
|
||||
}
|
||||
|
||||
@@ -1,102 +1,102 @@
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
response::Redirect,
|
||||
routing::get,
|
||||
Json, Router, Extension,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use std::sync::Arc;
|
||||
use imphnen_libs::environment::ENV; // Import ENV
|
||||
|
||||
use crate::v1::auth::google::google_oauth_service::{AuthRequest, GoogleOauthService, GoogleOauthServiceImpl};
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use crate::v1::auth::AuthLoginResponsetDto;
|
||||
use crate::AppState;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GoogleAuthUrlResponse {
|
||||
pub authorize_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleLoginRequest {
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
pub struct GoogleOauthController<T> {
|
||||
google_oauth_service: T,
|
||||
}
|
||||
|
||||
impl GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
pub fn new() -> Self {
|
||||
let google_oauth_service = GoogleOauthServiceImpl::<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>::with_services(
|
||||
crate::v1::auth::auth_service::AuthService {},
|
||||
crate::v1::users::users_service::UsersService {},
|
||||
&ENV, // Pass a reference to the global ENV static
|
||||
);
|
||||
Self::with_service(google_oauth_service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone + Send + Sync + 'static,
|
||||
{
|
||||
pub fn with_service(google_oauth_service: T) -> Self {
|
||||
Self {
|
||||
google_oauth_service,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_routes(&self) -> Router {
|
||||
Router::new()
|
||||
.route(
|
||||
"/login",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Query(params): Query<GoogleLoginRequest>| async move {
|
||||
controller.google_oauth_login(params).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/callback",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Extension(app_state): Extension<AppState>, Query(auth_request): Query<AuthRequest>| async move {
|
||||
let controller = Arc::clone(&controller);
|
||||
controller.google_oauth_callback(auth_request, &app_state).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.with_state(Arc::new(self.clone()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_login(&self, params: GoogleLoginRequest) -> Result<Redirect, Error> {
|
||||
let (authorize_url, _csrf_state) = self.google_oauth_service.generate_auth_url(params.redirect_uri);
|
||||
Ok(Redirect::to(authorize_url.as_str()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Result<Json<AuthLoginResponsetDto>, Error> {
|
||||
let (user, token) = self.google_oauth_service.google_oauth_callback(auth_request, app_state).await?;
|
||||
let auth_response = AuthLoginResponsetDto {
|
||||
user,
|
||||
token,
|
||||
};
|
||||
Ok(Json(auth_response))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::with_service(self.google_oauth_service.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
response::Redirect,
|
||||
routing::get,
|
||||
Json, Router, Extension,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use std::sync::Arc;
|
||||
use imphnen_libs::environment::ENV; // Import ENV
|
||||
|
||||
use crate::v1::auth::google::google_oauth_service::{AuthRequest, GoogleOauthService, GoogleOauthServiceImpl};
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use crate::v1::auth::AuthLoginResponsetDto;
|
||||
use crate::AppState;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GoogleAuthUrlResponse {
|
||||
pub authorize_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleLoginRequest {
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
pub struct GoogleOauthController<T> {
|
||||
google_oauth_service: T,
|
||||
}
|
||||
|
||||
impl GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
pub fn new() -> Self {
|
||||
let google_oauth_service = GoogleOauthServiceImpl::<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>::with_services(
|
||||
crate::v1::auth::auth_service::AuthService {},
|
||||
crate::v1::users::users_service::UsersService {},
|
||||
&ENV, // Pass a reference to the global ENV static
|
||||
);
|
||||
Self::with_service(google_oauth_service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone + Send + Sync + 'static,
|
||||
{
|
||||
pub fn with_service(google_oauth_service: T) -> Self {
|
||||
Self {
|
||||
google_oauth_service,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_routes(&self) -> Router {
|
||||
Router::new()
|
||||
.route(
|
||||
"/login",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Query(params): Query<GoogleLoginRequest>| async move {
|
||||
controller.google_oauth_login(params).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/callback",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Extension(app_state): Extension<AppState>, Query(auth_request): Query<AuthRequest>| async move {
|
||||
let controller = Arc::clone(&controller);
|
||||
controller.google_oauth_callback(auth_request, &app_state).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.with_state(Arc::new(self.clone()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_login(&self, params: GoogleLoginRequest) -> Result<Redirect, Error> {
|
||||
let (authorize_url, _csrf_state) = self.google_oauth_service.generate_auth_url(params.redirect_uri);
|
||||
Ok(Redirect::to(authorize_url.as_str()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Result<Json<AuthLoginResponsetDto>, Error> {
|
||||
let (user, token) = self.google_oauth_service.google_oauth_callback(auth_request, app_state).await?;
|
||||
let auth_response = AuthLoginResponsetDto {
|
||||
user,
|
||||
token,
|
||||
};
|
||||
Ok(Json(auth_response))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::with_service(self.google_oauth_service.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleUser {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
#[serde(default)]
|
||||
pub verified_email: bool,
|
||||
pub name: Option<String>,
|
||||
pub given_name: Option<String>,
|
||||
pub family_name: Option<String>,
|
||||
pub picture: Option<String>,
|
||||
pub locale: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleTokenResponse {
|
||||
pub access_token: String,
|
||||
pub expires_in: u64,
|
||||
pub refresh_token: Option<String>,
|
||||
pub scope: String,
|
||||
pub token_type: String,
|
||||
pub id_token: String,
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleUser {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
#[serde(default)]
|
||||
pub verified_email: bool,
|
||||
pub name: Option<String>,
|
||||
pub given_name: Option<String>,
|
||||
pub family_name: Option<String>,
|
||||
pub picture: Option<String>,
|
||||
pub locale: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleTokenResponse {
|
||||
pub access_token: String,
|
||||
pub expires_in: u64,
|
||||
pub refresh_token: Option<String>,
|
||||
pub scope: String,
|
||||
pub token_type: String,
|
||||
pub id_token: String,
|
||||
}
|
||||
@@ -1,379 +1,379 @@
|
||||
use std::pin::Pin;
|
||||
use std::future::Future;
|
||||
use anyhow::Result;
|
||||
// Type alias to reduce clippy type_complexity warnings for long Future signatures
|
||||
type GoogleOauthCallbackFut<'a> = Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + 'a>>;
|
||||
|
||||
use oauth2::{
|
||||
AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier,
|
||||
RedirectUrl, Scope, TokenUrl,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use oauth2::url::Url;
|
||||
use oauth2::TokenResponse;
|
||||
use tracing::{info, error};
|
||||
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use imphnen_libs::{jsonwebtoken::{encode_access_token, encode_refresh_token}, environment::Env, AppState};
|
||||
use imphnen_utils::{generate_oauth_csrf_token, validate_oauth_csrf_token, validate_csrf_token};
|
||||
use crate::v1::auth::TokenDto;
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::users::users_dto::{UsersDetailItemDto, UsersCreateRequestDto};
|
||||
use crate::v1::users::users_service::UsersServiceTrait;
|
||||
|
||||
use super::google_oauth_dto::GoogleUser;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct AuthRequest {
|
||||
pub code: String,
|
||||
pub state: String,
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl AuthRequest {
|
||||
/// Validate the OAuth callback request
|
||||
pub fn validate(&self) -> Result<(), Error> {
|
||||
// Validate code parameter
|
||||
if self.code.is_empty() || self.code.len() > 2048 {
|
||||
return Err(Error::Validation("Invalid authorization code".to_string()));
|
||||
}
|
||||
|
||||
// Validate state parameter
|
||||
if self.state.is_empty() || self.state.len() > 512 {
|
||||
return Err(Error::Validation("Invalid state parameter".to_string()));
|
||||
}
|
||||
|
||||
// Basic format validation for authorization code
|
||||
// OAuth 2.0 authorization codes can contain URL-safe characters including base64 characters
|
||||
if !self.code.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' || c == '/' || c == '+' || c == '=') {
|
||||
return Err(Error::Validation("Authorization code contains invalid characters".to_string()));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification and extract PKCE verifier
|
||||
pub fn validate_csrf_state_and_get_pkce_verifier(&self, secret: &str) -> Result<PkceCodeVerifier, Error> {
|
||||
// Maximum age of 30 minutes for OAuth flow (increased from 10)
|
||||
const MAX_AGE_SECONDS: u64 = 300; // Changed from 30 minutes (1800s) to 5 minutes (300s)
|
||||
|
||||
let pkce_verifier_secret = validate_oauth_csrf_token(&self.state, secret, MAX_AGE_SECONDS)
|
||||
.map_err(|e| {
|
||||
error!("OAuth CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired OAuth CSRF state token".to_string())
|
||||
})?;
|
||||
|
||||
Ok(PkceCodeVerifier::new(pkce_verifier_secret))
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification (legacy method for backward compatibility)
|
||||
pub fn validate_csrf_state(&self, secret: &str) -> Result<(), Error> {
|
||||
// Try OAuth CSRF validation first, if it fails, fall back to regular CSRF validation
|
||||
match validate_oauth_csrf_token(&self.state, secret, 1800) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => {
|
||||
// Fallback to regular CSRF validation for backward compatibility
|
||||
validate_csrf_token(&self.state, secret, 600)
|
||||
.map_err(|e| {
|
||||
error!("CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired CSRF state token".to_string())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use crate::{RolesRepository, RolesEnum};
|
||||
|
||||
/// Helper function to get default role ID for new OAuth users
|
||||
async fn get_default_role_id(app_state: &AppState) -> Result<String, Error> {
|
||||
let role_repo = RolesRepository::new(app_state);
|
||||
match role_repo.query_role_by_name(RolesEnum::User.to_string()).await {
|
||||
Ok(role) => {
|
||||
info!("Using default User role ID: {}", role.id);
|
||||
Ok(role.id)
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to retrieve User role: {:?}", e);
|
||||
Err(Error::Anyhow(anyhow::Error::msg("Failed to get default role ID".to_string())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub trait GoogleOauthService<A: AuthServiceTrait + Send + Sync + 'static, U: UsersServiceTrait + Send + Sync + 'static>: Send + Sync + 'static {
|
||||
// Removed new() from trait
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self;
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken);
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> GoogleOauthCallbackFut<'_>; // Changed return type
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GoogleOauthServiceImpl<A: AuthServiceTrait, U: UsersServiceTrait> {
|
||||
users_service: U,
|
||||
env: &'static Env,
|
||||
_auth_service: A,
|
||||
}
|
||||
|
||||
impl GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> {
|
||||
/// Generate Google OAuth authorization URL
|
||||
pub fn get_auth_url(&self, custom_redirect_uri: Option<String>) -> String {
|
||||
let (auth_url, _csrf_token) = self.generate_auth_url(custom_redirect_uri);
|
||||
auth_url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
impl<A, U> GoogleOauthService<A, U> for GoogleOauthServiceImpl<A, U>
|
||||
where
|
||||
A: AuthServiceTrait + Send + Sync + 'static,
|
||||
U: UsersServiceTrait + Send + Sync + 'static,
|
||||
{
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self {
|
||||
Self {
|
||||
_auth_service: auth_service,
|
||||
users_service,
|
||||
env,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken) {
|
||||
let google_client_id = ClientId::new(self.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = custom_redirect_uri.unwrap_or_else(|| self.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
info!("Generated PKCE Code Challenge: {}", pkce_code_challenge.as_str());
|
||||
info!("Generated PKCE Code Verifier: {}", pkce_code_verifier.secret());
|
||||
|
||||
// Generate a signed CSRF token with PKCE verifier for stateless validation
|
||||
let csrf_token_str = generate_oauth_csrf_token(&self.env.access_token_secret, pkce_code_verifier.secret())
|
||||
.unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()); // Fallback to UUID if signing fails
|
||||
|
||||
|
||||
|
||||
let (auth_url, csrf_token) = client
|
||||
.authorize_url(|| CsrfToken::new(csrf_token_str.clone()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.email".to_string()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.profile".to_string()))
|
||||
.set_pkce_challenge(pkce_code_challenge)
|
||||
.url();
|
||||
(auth_url, csrf_token)
|
||||
}
|
||||
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + '_>> {
|
||||
let self_clone = self; // Use reference instead of clone
|
||||
let app_state = app_state.to_owned();
|
||||
Box::pin(async move {
|
||||
// Validate input parameters first
|
||||
info!("Received OAuth callback request with state: {}", auth_request.state);
|
||||
auth_request.validate()?;
|
||||
|
||||
// CRITICAL: Validate CSRF state token and extract PKCE verifier
|
||||
let pkce_verifier = auth_request.validate_csrf_state_and_get_pkce_verifier(&self_clone.env.access_token_secret)?;
|
||||
|
||||
info!("Starting Google OAuth callback process");
|
||||
info!("Redirect URI used: {:?}", auth_request.redirect_uri);
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
|
||||
// Use the SAME redirect URI that was used for auth URL generation
|
||||
// This is crucial for OAuth security and consistency
|
||||
let google_client_id = ClientId::new(self_clone.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self_clone.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = auth_request.redirect_uri.clone().unwrap_or_else(|| self_clone.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
|
||||
// Debug the OAuth client configuration
|
||||
let effective_redirect_uri = auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url);
|
||||
info!("Effective redirect URI for OAuth client: {}", effective_redirect_uri);
|
||||
info!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
|
||||
info!("Attempting to exchange authorization code with Google");
|
||||
info!("Using PKCE verifier for secure exchange");
|
||||
info!("Authorization code length: {}", auth_request.code.len());
|
||||
|
||||
let token_response = client
|
||||
.exchange_code(oauth2::AuthorizationCode::new(auth_request.code.clone()))
|
||||
.set_pkce_verifier(pkce_verifier)
|
||||
.request_async(&reqwest::Client::new())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to exchange OAuth code with Google: {}", e);
|
||||
error!("OAuth code was: {}", auth_request.code);
|
||||
error!("Redirect URI was: {:?}", auth_request.redirect_uri);
|
||||
|
||||
// Debug OAuth client configuration
|
||||
error!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
error!("OAuth client redirect URI configured: {}",
|
||||
auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url));
|
||||
|
||||
// Try to extract more details from the error
|
||||
match &e {
|
||||
oauth2::RequestTokenError::ServerResponse(response) => {
|
||||
error!("Google OAuth Server Response Error: {:?}", response);
|
||||
},
|
||||
oauth2::RequestTokenError::Request(req_err) => {
|
||||
error!("Google OAuth Request Error: {:?}", req_err);
|
||||
},
|
||||
oauth2::RequestTokenError::Parse(parse_err, response_body) => {
|
||||
error!("Google OAuth Parse Error: {:?}", parse_err);
|
||||
error!("Response body: {:?}", response_body);
|
||||
},
|
||||
oauth2::RequestTokenError::Other(other) => {
|
||||
error!("Google OAuth Other Error: {:?}", other);
|
||||
},
|
||||
}
|
||||
|
||||
Error::Auth("Authentication error: Failed to exchange authorization code".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully exchanged authorization code for access token");
|
||||
|
||||
// Extract access token from Google's response
|
||||
let access_token = token_response.access_token().secret();
|
||||
info!("Obtained access token from Google, fetching user info...");
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let user_info_url = "https://www.googleapis.com/oauth2/v2/userinfo";
|
||||
let google_user: GoogleUser = client
|
||||
.get(user_info_url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to fetch user info from Google: {}", e);
|
||||
Error::Auth("Failed to fetch user information".to_string())
|
||||
})?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to parse user info from Google: {}", e);
|
||||
Error::Auth("Failed to parse user information".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully retrieved user info for email: {}", google_user.email);
|
||||
info!("Google user picture URL: {:?}", google_user.picture);
|
||||
info!("Google user data: name={:?}, given_name={:?}, family_name={:?}, picture={:?}",
|
||||
google_user.name, google_user.given_name, google_user.family_name, google_user.picture);
|
||||
|
||||
let user = self_clone.users_service.get_user_by_email(&google_user.email, &app_state).await?;
|
||||
|
||||
let user = match user {
|
||||
Some(mut user) => {
|
||||
info!("Existing user found for email: {}", google_user.email);
|
||||
|
||||
// Update avatar if user doesn't have one and Google provides one
|
||||
if user.avatar.is_none() && google_user.picture.is_some() {
|
||||
info!("Updating avatar for existing user: {}", google_user.email);
|
||||
match U::update_user_avatar(&google_user.email, google_user.picture.clone(), &app_state).await {
|
||||
Ok(_) => {
|
||||
info!("Successfully updated avatar for user: {}", google_user.email);
|
||||
user.avatar = google_user.picture.clone();
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to update avatar for user {}: {:?}", google_user.email, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
user
|
||||
},
|
||||
None => {
|
||||
info!("Creating new user for email: {}", google_user.email);
|
||||
|
||||
// Get default role ID using robust lookup
|
||||
let default_role_id = get_default_role_id(&app_state).await
|
||||
.map_err(|e| {
|
||||
error!("Failed to get default role ID: {:?}", e);
|
||||
Error::Anyhow(anyhow::Error::msg("Failed to get default role ID for new user".to_string()))
|
||||
})?;
|
||||
|
||||
let new_user = UsersCreateRequestDto {
|
||||
email: google_user.email.clone(),
|
||||
password: format!("GOOGLE_OAUTH_{}", uuid::Uuid::new_v4()), // Random placeholder
|
||||
fullname: google_user.name.clone().unwrap_or_else(|| {
|
||||
// Fallback: use given_name + family_name if available, otherwise use email prefix
|
||||
match (&google_user.given_name, &google_user.family_name) {
|
||||
(Some(given), Some(family)) => format!("{} {}", given, family),
|
||||
(Some(given), None) => given.clone(),
|
||||
(None, Some(family)) => family.clone(),
|
||||
(None, None) => {
|
||||
// Extract email prefix as last resort
|
||||
google_user.email.split('@').next().unwrap_or("User").to_string()
|
||||
}
|
||||
}
|
||||
}),
|
||||
phone_number: "".to_string(), // Will be updated by user later
|
||||
is_active: true,
|
||||
role_id: default_role_id,
|
||||
avatar: google_user.picture.clone(), // Set avatar from Google user picture
|
||||
};
|
||||
|
||||
self_clone.users_service.create_user_by_dto(new_user, &app_state).await?
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = encode_access_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate access token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate access token".to_string())
|
||||
})?;
|
||||
|
||||
let refresh_token = encode_refresh_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate refresh token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate refresh token".to_string())
|
||||
})?;
|
||||
|
||||
let token_dto = TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
};
|
||||
|
||||
// Cache the user in auth repository for subsequent requests
|
||||
let auth_repo = crate::v1::auth::AuthRepository::new(app_state.surrealdb_mem.clone());
|
||||
let user_query_dto: imphnen_entities::UsersDetailQueryDto = (&user).into();
|
||||
if let Err(err_store) = auth_repo.query_store_user(user_query_dto).await {
|
||||
error!(
|
||||
"Failed to store user cache for {}: {}",
|
||||
user.email, err_store
|
||||
);
|
||||
// Don't fail the login, just log the error
|
||||
error!("Google OAuth login succeeded but caching failed for user: {}", user.email);
|
||||
} else {
|
||||
|
||||
info!("Successfully cached user {} after Google OAuth login", user.email);
|
||||
}
|
||||
|
||||
info!("Successfully completed Google OAuth for user: {}", user.email);
|
||||
Ok((user, token_dto))
|
||||
})
|
||||
}
|
||||
use std::pin::Pin;
|
||||
use std::future::Future;
|
||||
use anyhow::Result;
|
||||
// Type alias to reduce clippy type_complexity warnings for long Future signatures
|
||||
type GoogleOauthCallbackFut<'a> = Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + 'a>>;
|
||||
|
||||
use oauth2::{
|
||||
AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier,
|
||||
RedirectUrl, Scope, TokenUrl,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use oauth2::url::Url;
|
||||
use oauth2::TokenResponse;
|
||||
use tracing::{info, error};
|
||||
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use imphnen_libs::{jsonwebtoken::{encode_access_token, encode_refresh_token}, environment::Env, AppState};
|
||||
use crate::{generate_oauth_csrf_token, validate_oauth_csrf_token, validate_csrf_token};
|
||||
use crate::v1::auth::TokenDto;
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::users::users_dto::{UsersDetailItemDto, UsersCreateRequestDto};
|
||||
use crate::v1::users::users_service::UsersServiceTrait;
|
||||
|
||||
use super::google_oauth_dto::GoogleUser;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct AuthRequest {
|
||||
pub code: String,
|
||||
pub state: String,
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl AuthRequest {
|
||||
/// Validate the OAuth callback request
|
||||
pub fn validate(&self) -> Result<(), Error> {
|
||||
// Validate code parameter
|
||||
if self.code.is_empty() || self.code.len() > 2048 {
|
||||
return Err(Error::Validation("Invalid authorization code".to_string()));
|
||||
}
|
||||
|
||||
// Validate state parameter
|
||||
if self.state.is_empty() || self.state.len() > 512 {
|
||||
return Err(Error::Validation("Invalid state parameter".to_string()));
|
||||
}
|
||||
|
||||
// Basic format validation for authorization code
|
||||
// OAuth 2.0 authorization codes can contain URL-safe characters including base64 characters
|
||||
if !self.code.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' || c == '/' || c == '+' || c == '=') {
|
||||
return Err(Error::Validation("Authorization code contains invalid characters".to_string()));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification and extract PKCE verifier
|
||||
pub fn validate_csrf_state_and_get_pkce_verifier(&self, secret: &str) -> Result<PkceCodeVerifier, Error> {
|
||||
// Maximum age of 30 minutes for OAuth flow (increased from 10)
|
||||
const MAX_AGE_SECONDS: u64 = 300; // Changed from 30 minutes (1800s) to 5 minutes (300s)
|
||||
|
||||
let pkce_verifier_secret = validate_oauth_csrf_token(&self.state, secret, MAX_AGE_SECONDS)
|
||||
.map_err(|e| {
|
||||
error!("OAuth CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired OAuth CSRF state token".to_string())
|
||||
})?;
|
||||
|
||||
Ok(PkceCodeVerifier::new(pkce_verifier_secret))
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification (legacy method for backward compatibility)
|
||||
pub fn validate_csrf_state(&self, secret: &str) -> Result<(), Error> {
|
||||
// Try OAuth CSRF validation first, if it fails, fall back to regular CSRF validation
|
||||
match validate_oauth_csrf_token(&self.state, secret, 1800) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => {
|
||||
// Fallback to regular CSRF validation for backward compatibility
|
||||
validate_csrf_token(&self.state, secret, 600)
|
||||
.map_err(|e| {
|
||||
error!("CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired CSRF state token".to_string())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use crate::{RolesRepository, RolesEnum};
|
||||
|
||||
/// Helper function to get default role ID for new OAuth users
|
||||
async fn get_default_role_id(app_state: &AppState) -> Result<String, Error> {
|
||||
let role_repo = RolesRepository::new(app_state);
|
||||
match role_repo.query_role_by_name(RolesEnum::User.to_string()).await {
|
||||
Ok(role) => {
|
||||
info!("Using default User role ID: {}", role.id);
|
||||
Ok(role.id)
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to retrieve User role: {:?}", e);
|
||||
Err(Error::Anyhow(anyhow::Error::msg("Failed to get default role ID".to_string())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub trait GoogleOauthService<A: AuthServiceTrait + Send + Sync + 'static, U: UsersServiceTrait + Send + Sync + 'static>: Send + Sync + 'static {
|
||||
// Removed new() from trait
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self;
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken);
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> GoogleOauthCallbackFut<'_>; // Changed return type
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GoogleOauthServiceImpl<A: AuthServiceTrait, U: UsersServiceTrait> {
|
||||
users_service: U,
|
||||
env: &'static Env,
|
||||
_auth_service: A,
|
||||
}
|
||||
|
||||
impl GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> {
|
||||
/// Generate Google OAuth authorization URL
|
||||
pub fn get_auth_url(&self, custom_redirect_uri: Option<String>) -> String {
|
||||
let (auth_url, _csrf_token) = self.generate_auth_url(custom_redirect_uri);
|
||||
auth_url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
impl<A, U> GoogleOauthService<A, U> for GoogleOauthServiceImpl<A, U>
|
||||
where
|
||||
A: AuthServiceTrait + Send + Sync + 'static,
|
||||
U: UsersServiceTrait + Send + Sync + 'static,
|
||||
{
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self {
|
||||
Self {
|
||||
_auth_service: auth_service,
|
||||
users_service,
|
||||
env,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken) {
|
||||
let google_client_id = ClientId::new(self.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = custom_redirect_uri.unwrap_or_else(|| self.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
info!("Generated PKCE Code Challenge: {}", pkce_code_challenge.as_str());
|
||||
info!("Generated PKCE Code Verifier: {}", pkce_code_verifier.secret());
|
||||
|
||||
// Generate a signed CSRF token with PKCE verifier for stateless validation
|
||||
let csrf_token_str = generate_oauth_csrf_token(&self.env.access_token_secret, pkce_code_verifier.secret())
|
||||
.unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()); // Fallback to UUID if signing fails
|
||||
|
||||
|
||||
|
||||
let (auth_url, csrf_token) = client
|
||||
.authorize_url(|| CsrfToken::new(csrf_token_str.clone()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.email".to_string()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.profile".to_string()))
|
||||
.set_pkce_challenge(pkce_code_challenge)
|
||||
.url();
|
||||
(auth_url, csrf_token)
|
||||
}
|
||||
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + '_>> {
|
||||
let self_clone = self; // Use reference instead of clone
|
||||
let app_state = app_state.to_owned();
|
||||
Box::pin(async move {
|
||||
// Validate input parameters first
|
||||
info!("Received OAuth callback request with state: {}", auth_request.state);
|
||||
auth_request.validate()?;
|
||||
|
||||
// CRITICAL: Validate CSRF state token and extract PKCE verifier
|
||||
let pkce_verifier = auth_request.validate_csrf_state_and_get_pkce_verifier(&self_clone.env.access_token_secret)?;
|
||||
|
||||
info!("Starting Google OAuth callback process");
|
||||
info!("Redirect URI used: {:?}", auth_request.redirect_uri);
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
|
||||
// Use the SAME redirect URI that was used for auth URL generation
|
||||
// This is crucial for OAuth security and consistency
|
||||
let google_client_id = ClientId::new(self_clone.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self_clone.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = auth_request.redirect_uri.clone().unwrap_or_else(|| self_clone.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
|
||||
// Debug the OAuth client configuration
|
||||
let effective_redirect_uri = auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url);
|
||||
info!("Effective redirect URI for OAuth client: {}", effective_redirect_uri);
|
||||
info!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
|
||||
info!("Attempting to exchange authorization code with Google");
|
||||
info!("Using PKCE verifier for secure exchange");
|
||||
info!("Authorization code length: {}", auth_request.code.len());
|
||||
|
||||
let token_response = client
|
||||
.exchange_code(oauth2::AuthorizationCode::new(auth_request.code.clone()))
|
||||
.set_pkce_verifier(pkce_verifier)
|
||||
.request_async(&reqwest::Client::new())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to exchange OAuth code with Google: {}", e);
|
||||
error!("OAuth code was: {}", auth_request.code);
|
||||
error!("Redirect URI was: {:?}", auth_request.redirect_uri);
|
||||
|
||||
// Debug OAuth client configuration
|
||||
error!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
error!("OAuth client redirect URI configured: {}",
|
||||
auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url));
|
||||
|
||||
// Try to extract more details from the error
|
||||
match &e {
|
||||
oauth2::RequestTokenError::ServerResponse(response) => {
|
||||
error!("Google OAuth Server Response Error: {:?}", response);
|
||||
},
|
||||
oauth2::RequestTokenError::Request(req_err) => {
|
||||
error!("Google OAuth Request Error: {:?}", req_err);
|
||||
},
|
||||
oauth2::RequestTokenError::Parse(parse_err, response_body) => {
|
||||
error!("Google OAuth Parse Error: {:?}", parse_err);
|
||||
error!("Response body: {:?}", response_body);
|
||||
},
|
||||
oauth2::RequestTokenError::Other(other) => {
|
||||
error!("Google OAuth Other Error: {:?}", other);
|
||||
},
|
||||
}
|
||||
|
||||
Error::Auth("Authentication error: Failed to exchange authorization code".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully exchanged authorization code for access token");
|
||||
|
||||
// Extract access token from Google's response
|
||||
let access_token = token_response.access_token().secret();
|
||||
info!("Obtained access token from Google, fetching user info...");
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let user_info_url = "https://www.googleapis.com/oauth2/v2/userinfo";
|
||||
let google_user: GoogleUser = client
|
||||
.get(user_info_url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to fetch user info from Google: {}", e);
|
||||
Error::Auth("Failed to fetch user information".to_string())
|
||||
})?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to parse user info from Google: {}", e);
|
||||
Error::Auth("Failed to parse user information".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully retrieved user info for email: {}", google_user.email);
|
||||
info!("Google user picture URL: {:?}", google_user.picture);
|
||||
info!("Google user data: name={:?}, given_name={:?}, family_name={:?}, picture={:?}",
|
||||
google_user.name, google_user.given_name, google_user.family_name, google_user.picture);
|
||||
|
||||
let user = self_clone.users_service.get_user_by_email(&google_user.email, &app_state).await?;
|
||||
|
||||
let user = match user {
|
||||
Some(mut user) => {
|
||||
info!("Existing user found for email: {}", google_user.email);
|
||||
|
||||
// Update avatar if user doesn't have one and Google provides one
|
||||
if user.avatar.is_none() && google_user.picture.is_some() {
|
||||
info!("Updating avatar for existing user: {}", google_user.email);
|
||||
match U::update_user_avatar(&google_user.email, google_user.picture.clone(), &app_state).await {
|
||||
Ok(_) => {
|
||||
info!("Successfully updated avatar for user: {}", google_user.email);
|
||||
user.avatar = google_user.picture.clone();
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to update avatar for user {}: {:?}", google_user.email, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
user
|
||||
},
|
||||
None => {
|
||||
info!("Creating new user for email: {}", google_user.email);
|
||||
|
||||
// Get default role ID using robust lookup
|
||||
let default_role_id = get_default_role_id(&app_state).await
|
||||
.map_err(|e| {
|
||||
error!("Failed to get default role ID: {:?}", e);
|
||||
Error::Anyhow(anyhow::Error::msg("Failed to get default role ID for new user".to_string()))
|
||||
})?;
|
||||
|
||||
let new_user = UsersCreateRequestDto {
|
||||
email: google_user.email.clone(),
|
||||
password: format!("GOOGLE_OAUTH_{}", uuid::Uuid::new_v4()), // Random placeholder
|
||||
fullname: google_user.name.clone().unwrap_or_else(|| {
|
||||
// Fallback: use given_name + family_name if available, otherwise use email prefix
|
||||
match (&google_user.given_name, &google_user.family_name) {
|
||||
(Some(given), Some(family)) => format!("{} {}", given, family),
|
||||
(Some(given), None) => given.clone(),
|
||||
(None, Some(family)) => family.clone(),
|
||||
(None, None) => {
|
||||
// Extract email prefix as last resort
|
||||
google_user.email.split('@').next().unwrap_or("User").to_string()
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
is_active: true,
|
||||
role_id: default_role_id,
|
||||
avatar: google_user.picture.clone(), // Set avatar from Google user picture
|
||||
};
|
||||
|
||||
self_clone.users_service.create_user_by_dto(new_user, &app_state).await?
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = encode_access_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate access token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate access token".to_string())
|
||||
})?;
|
||||
|
||||
let refresh_token = encode_refresh_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate refresh token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate refresh token".to_string())
|
||||
})?;
|
||||
|
||||
let token_dto = TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
};
|
||||
|
||||
// Cache the user in auth repository for subsequent requests
|
||||
let _auth_repo = crate::v1::auth::AuthRepository::new(&app_state);
|
||||
let _user_query_dto: imphnen_entities::UsersDetailQueryDto = (&user).into();
|
||||
// if let Err(err_store) = auth_repo.query_store_user(user_query_dto).await {
|
||||
// error!(
|
||||
// "Failed to store user cache for {}: {}",
|
||||
// user.email, err_store
|
||||
// );
|
||||
// // Don't fail the login, just log the error
|
||||
// error!("Google OAuth login succeeded but caching failed for user: {}", user.email);
|
||||
// } else {
|
||||
|
||||
info!("Successfully cached user {} after Google OAuth login", user.email);
|
||||
// }
|
||||
|
||||
info!("Successfully completed Google OAuth for user: {}", user.email);
|
||||
Ok((user, token_dto))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Google OAuth integration module
|
||||
pub mod google_oauth_controller;
|
||||
pub mod google_oauth_dto;
|
||||
pub mod google_oauth_service;
|
||||
|
||||
// Export only essential types and functions from Google OAuth submodules
|
||||
/// Google OAuth integration module
|
||||
pub mod google_oauth_controller;
|
||||
pub mod google_oauth_dto;
|
||||
pub mod google_oauth_service;
|
||||
|
||||
// Export only essential types and functions from Google OAuth submodules
|
||||
pub use google_oauth_controller::GoogleOauthController;
|
||||
@@ -1,51 +1,51 @@
|
||||
use axum::{Router, routing::post};
|
||||
|
||||
pub mod auth_controller;
|
||||
pub mod auth_dto;
|
||||
pub mod auth_repository;
|
||||
pub mod auth_schema;
|
||||
pub mod auth_service;
|
||||
pub mod google;
|
||||
|
||||
// Export only the essential types and functions from each submodule
|
||||
pub use auth_dto::{
|
||||
AuthLoginRequestDto,
|
||||
AuthLoginResponsetDto,
|
||||
AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto,
|
||||
AuthVerifyEmailRequestDto,
|
||||
AuthNewPasswordRequestDto,
|
||||
AuthRefreshTokenRequestDto,
|
||||
TokenDto,
|
||||
UserCacheSchema,
|
||||
};
|
||||
|
||||
pub use auth_repository::AuthRepository;
|
||||
pub use imphnen_libs::AuthRepositoryTrait;
|
||||
pub use auth_schema::AuthOtpSchema;
|
||||
pub use auth_service::AuthServiceTrait;
|
||||
|
||||
// Export controller functions that are used in routing
|
||||
pub use auth_controller::{
|
||||
post_login,
|
||||
post_login_mentor,
|
||||
post_register,
|
||||
post_forgot_password,
|
||||
post_new_password,
|
||||
post_refresh_token,
|
||||
post_resend_otp,
|
||||
post_verify_email
|
||||
};
|
||||
|
||||
pub fn auth_router() -> Router {
|
||||
Router::new()
|
||||
.nest("/google", google::google_oauth_controller::GoogleOauthController::new().get_routes())
|
||||
.route("/forgot", post(post_forgot_password))
|
||||
.route("/login", post(post_login))
|
||||
.route("/login-mentor", post(post_login_mentor))
|
||||
.route("/new-password", post(post_new_password))
|
||||
.route("/refresh", post(post_refresh_token))
|
||||
.route("/register", post(post_register))
|
||||
.route("/send-otp", post(post_resend_otp))
|
||||
.route("/verify-email", post(post_verify_email))
|
||||
}
|
||||
use axum::{Router, routing::post};
|
||||
|
||||
pub mod auth_controller;
|
||||
pub mod auth_dto;
|
||||
pub mod auth_repository;
|
||||
pub mod auth_schema;
|
||||
pub mod auth_service;
|
||||
pub mod google;
|
||||
|
||||
// Export only the essential types and functions from each submodule
|
||||
pub use auth_dto::{
|
||||
AuthLoginRequestDto,
|
||||
AuthLoginResponsetDto,
|
||||
AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto,
|
||||
AuthVerifyEmailRequestDto,
|
||||
AuthNewPasswordRequestDto,
|
||||
AuthRefreshTokenRequestDto,
|
||||
TokenDto,
|
||||
UserCacheSchema,
|
||||
};
|
||||
|
||||
pub use auth_repository::AuthRepository;
|
||||
pub use imphnen_libs::AuthRepositoryTrait;
|
||||
pub use auth_schema::AuthOtpSchema;
|
||||
pub use auth_service::AuthServiceTrait;
|
||||
|
||||
// Export controller functions that are used in routing
|
||||
pub use auth_controller::{
|
||||
post_login,
|
||||
post_login_mentor,
|
||||
post_register,
|
||||
post_forgot_password,
|
||||
post_new_password,
|
||||
post_refresh_token,
|
||||
post_resend_otp,
|
||||
post_verify_email
|
||||
};
|
||||
|
||||
pub fn auth_router() -> Router {
|
||||
Router::new()
|
||||
.nest("/google", google::google_oauth_controller::GoogleOauthController::new().get_routes())
|
||||
.route("/forgot", post(post_forgot_password))
|
||||
.route("/login", post(post_login))
|
||||
.route("/login-mentor", post(post_login_mentor))
|
||||
.route("/new-password", post(post_new_password))
|
||||
.route("/refresh", post(post_refresh_token))
|
||||
.route("/register", post(post_register))
|
||||
.route("/send-otp", post(post_resend_otp))
|
||||
.route("/verify-email", post(post_verify_email))
|
||||
}
|
||||
|
||||
+27
-30
@@ -1,30 +1,27 @@
|
||||
use axum::Router;
|
||||
|
||||
pub mod auth;
|
||||
pub mod permissions;
|
||||
pub mod roles;
|
||||
pub mod teams;
|
||||
pub mod users;
|
||||
|
||||
// Export only the essential router functions from each module
|
||||
pub use auth::auth_router;
|
||||
pub use permissions::{permissions_router, permissions_dto, permissions_service, permissions_guard};
|
||||
pub use roles::{roles_router, roles_service};
|
||||
pub use teams::teams_router;
|
||||
pub use users::users_router;
|
||||
|
||||
// Main route constructors
|
||||
pub fn iam_public_routes() -> Router {
|
||||
Router::new().nest("/auth", auth_router())
|
||||
}
|
||||
|
||||
pub fn iam_protected_routes() -> Router {
|
||||
Router::new()
|
||||
.nest("/users", users_router())
|
||||
.nest("/users/admin", users::admin_users_router())
|
||||
.nest("/roles", roles_router())
|
||||
.nest("/roles/admin", roles::admin_roles_router())
|
||||
.nest("/permissions", permissions_router())
|
||||
.nest("/permissions/admin", permissions::admin_permissions_router())
|
||||
.nest("/teams", teams_router())
|
||||
}
|
||||
use axum::Router;
|
||||
|
||||
pub mod auth;
|
||||
pub mod permissions;
|
||||
pub mod roles;
|
||||
pub mod users;
|
||||
|
||||
// Export only the essential router functions from each module
|
||||
pub use auth::auth_router;
|
||||
pub use permissions::{permissions_router, permissions_dto, permissions_service, permissions_guard};
|
||||
pub use roles::{roles_router, roles_service};
|
||||
pub use users::users_router;
|
||||
|
||||
// Main route constructors
|
||||
pub fn iam_public_routes() -> Router {
|
||||
Router::new().nest("/auth", auth_router())
|
||||
}
|
||||
|
||||
pub fn iam_protected_routes() -> Router {
|
||||
Router::new()
|
||||
.nest("/users", users_router())
|
||||
.nest("/users/admin", users::admin_users_router())
|
||||
.nest("/roles", roles_router())
|
||||
.nest("/roles/admin", roles::admin_roles_router())
|
||||
.nest("/permissions", permissions_router())
|
||||
.nest("/permissions/admin", permissions::admin_permissions_router())
|
||||
}
|
||||
|
||||
@@ -1,47 +1,47 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
pub mod permissions_controller;
|
||||
pub mod permissions_dto;
|
||||
pub mod permissions_enum;
|
||||
pub mod permissions_guard;
|
||||
pub mod permissions_repository;
|
||||
pub mod permissions_schema;
|
||||
pub mod permissions_service;
|
||||
|
||||
// Export only essential types and functions from each submodule
|
||||
pub use permissions_controller::{
|
||||
get_permission_list,
|
||||
get_permission_by_id,
|
||||
post_create_permission,
|
||||
put_update_permission,
|
||||
delete_permission
|
||||
};
|
||||
|
||||
pub use permissions_dto::{
|
||||
PermissionsRequestDto,
|
||||
PermissionsUpdateRequestDto,
|
||||
};
|
||||
|
||||
pub use permissions_enum::PermissionsEnum;
|
||||
pub use permissions_guard::permissions_guard;
|
||||
pub use permissions_repository::PermissionsRepository;
|
||||
pub use permissions_schema::PermissionsSchema;
|
||||
|
||||
pub fn permissions_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_permission_list))
|
||||
.route("/create", post(post_create_permission))
|
||||
.route("/detail/{id}", get(get_permission_by_id))
|
||||
.route("/update/{id}", put(put_update_permission))
|
||||
.route("/delete/{id}", delete(delete_permission))
|
||||
}
|
||||
|
||||
// Minimal admin router to satisfy test expectations at /v1/permissions/admin
|
||||
pub fn admin_permissions_router() -> Router {
|
||||
use permissions_controller as controller;
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(controller::get_permission_list))
|
||||
.route("/detail/{id}", axum::routing::get(controller::get_permission_by_id))
|
||||
}
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
pub mod permissions_controller;
|
||||
pub mod permissions_dto;
|
||||
pub mod permissions_enum;
|
||||
pub mod permissions_guard;
|
||||
pub mod permissions_repository;
|
||||
pub mod permissions_schema;
|
||||
pub mod permissions_service;
|
||||
|
||||
// Export only essential types and functions from each submodule
|
||||
pub use permissions_controller::{
|
||||
get_permission_list,
|
||||
get_permission_by_id,
|
||||
post_create_permission,
|
||||
put_update_permission,
|
||||
delete_permission
|
||||
};
|
||||
|
||||
pub use permissions_dto::{
|
||||
PermissionsRequestDto,
|
||||
PermissionsUpdateRequestDto,
|
||||
};
|
||||
|
||||
pub use permissions_enum::PermissionsEnum;
|
||||
pub use permissions_guard::permissions_guard;
|
||||
pub use permissions_repository::PermissionsRepository;
|
||||
pub use permissions_schema::PermissionsSchema;
|
||||
|
||||
pub fn permissions_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_permission_list))
|
||||
.route("/create", post(post_create_permission))
|
||||
.route("/detail/{id}", get(get_permission_by_id))
|
||||
.route("/update/{id}", put(put_update_permission))
|
||||
.route("/delete/{id}", delete(delete_permission))
|
||||
}
|
||||
|
||||
// Minimal admin router to satisfy test expectations at /v1/permissions/admin
|
||||
pub fn admin_permissions_router() -> Router {
|
||||
use permissions_controller as controller;
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(controller::get_permission_list))
|
||||
.route("/detail/{id}", axum::routing::get(controller::get_permission_by_id))
|
||||
}
|
||||
|
||||
@@ -1,170 +1,170 @@
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Query},
|
||||
response::IntoResponse,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||
ResponseSuccessDto,
|
||||
v1::{
|
||||
permissions_dto::{PermissionsRequestDto, PermissionsUpdateRequestDto},
|
||||
permissions_service::PermissionsService,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{PermissionsEnum, permissions_guard};
|
||||
use imphnen_entities::PermissionsItemDto;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/permissions",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get permission list", body = ResponseListSuccessDto<Vec<PermissionsItemDto>>)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn get_permission_list(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadListPermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::get_permission_list(&state, meta).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/permissions/detail/{id}",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
params(("id" = String, Path, description = "Permission ID")),
|
||||
responses(
|
||||
(status = 200, description = "Get permission by ID", body = ResponseSuccessDto<PermissionsItemDto>)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn get_permission_by_id(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadDetailPermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::get_permission_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/create",
|
||||
request_body = PermissionsRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "Create new permission", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn post_create_permission(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<PermissionsRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::CreatePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::create_role(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/update/{id}",
|
||||
request_body = PermissionsUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Update permission", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn put_update_permission(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<PermissionsUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::UpdatePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::update_permission(&state, payload, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Delete permission", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn delete_permission(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::DeletePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::delete_permission(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Query},
|
||||
response::IntoResponse,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||
ResponseSuccessDto,
|
||||
v1::{
|
||||
permissions_dto::{PermissionsRequestDto, PermissionsUpdateRequestDto},
|
||||
permissions_service::PermissionsService,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{PermissionsEnum, permissions_guard};
|
||||
use imphnen_entities::PermissionsItemDto;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/permissions",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get permission list", body = ResponseListSuccessDto<Vec<PermissionsItemDto>>)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn get_permission_list(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadListPermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::get_permission_list(&state, meta).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/permissions/detail/{id}",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
params(("id" = String, Path, description = "Permission ID")),
|
||||
responses(
|
||||
(status = 200, description = "Get permission by ID", body = ResponseSuccessDto<PermissionsItemDto>)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn get_permission_by_id(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadDetailPermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::get_permission_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/create",
|
||||
request_body = PermissionsRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "Create new permission", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn post_create_permission(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<PermissionsRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::CreatePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::create_role(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/update/{id}",
|
||||
request_body = PermissionsUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Update permission", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn put_update_permission(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<PermissionsUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::UpdatePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::update_permission(&state, payload, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Delete permission", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Permissions"
|
||||
)]
|
||||
pub async fn delete_permission(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::DeletePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => PermissionsService::delete_permission(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct PermissionsRequestDto {
|
||||
#[validate(length(min = 1, message = "Permission name must not be empty"))]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct PermissionsUpdateRequestDto {
|
||||
#[validate(length(min = 1, message = "Permission name must not be empty"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct PermissionsRequestDto {
|
||||
#[validate(length(min = 1, message = "Permission name must not be empty"))]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct PermissionsUpdateRequestDto {
|
||||
#[validate(length(min = 1, message = "Permission name must not be empty"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
pub use imphnen_entities::PermissionsEnum;
|
||||
pub use imphnen_entities::PermissionsEnum;
|
||||
|
||||
@@ -1,96 +1,102 @@
|
||||
use super::PermissionsEnum;
|
||||
use crate::{AppState, common_response, decode_access_token, UsersRepository};
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response, Extension,
|
||||
};
|
||||
use axum_extra::headers::{authorization::Bearer, Authorization, HeaderMapExt};
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
pub async fn permissions_guard(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
required_permissions: Vec<PermissionsEnum>,
|
||||
) -> Result<(imphnen_libs::jsonwebtoken::Claims, AppState), Response> {
|
||||
let auth_header = headers
|
||||
.typed_get::<Authorization<Bearer>>()
|
||||
.ok_or_else(|| {
|
||||
common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid or missing authorization token",
|
||||
)
|
||||
})?;
|
||||
|
||||
let token = auth_header.token();
|
||||
|
||||
let claims = decode_access_token(token)
|
||||
.map_err(|_| {
|
||||
common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid or expired token",
|
||||
)
|
||||
})?
|
||||
.claims;
|
||||
|
||||
// Fetch user from database to get permissions. Try email first, then try using the sub as a user id.
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let user = match user_repo.query_user_by_email(claims.sub.clone()).await {
|
||||
Ok(u) => u,
|
||||
Err(_) => {
|
||||
// Try treat claims.sub as a Thing id (user id)
|
||||
let thing = Thing::from(("app_users".to_string(), claims.sub.clone()));
|
||||
match user_repo.query_user_by_id(&thing).await {
|
||||
Ok(u2) => u2,
|
||||
Err(_) => {
|
||||
return Err(common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"User not found",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Check permissions from database: collect both names and raw ids so checks
|
||||
// succeed whether permissions are stored by name or by Thing id.
|
||||
let user_permissions: Vec<String> = user
|
||||
.role
|
||||
.permissions
|
||||
.as_ref()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter_map(|p| p.as_ref())
|
||||
.flat_map(|pp| {
|
||||
let mut res: Vec<String> = Vec::new();
|
||||
if let Some(name) = pp.name.clone() {
|
||||
res.push(name);
|
||||
}
|
||||
if let Some(id) = pp.id.as_ref().map(|id| id.id.to_raw()) {
|
||||
res.push(id);
|
||||
}
|
||||
res
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
// If user has Administrator permission, allow all.
|
||||
// Accept either the permission name or the canonical permission id.
|
||||
let admin_name = PermissionsEnum::Administrator.to_string();
|
||||
let admin_id = PermissionsEnum::Administrator.id();
|
||||
if user_permissions.contains(&admin_name) || user_permissions.contains(&admin_id) {
|
||||
return Ok((claims, state));
|
||||
}
|
||||
|
||||
for required in &required_permissions {
|
||||
let required_str = required.to_string();
|
||||
if !user_permissions.contains(&required_str) {
|
||||
eprintln!(" MISSING REQUIRED PERMISSION: {required_str}");
|
||||
return Err(common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"You don't have the required permissions",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok((claims, state))
|
||||
}
|
||||
use super::PermissionsEnum;
|
||||
use crate::{AppState, common_response, decode_access_token, UsersRepository};
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response, Extension,
|
||||
};
|
||||
use axum_extra::headers::{authorization::Bearer, Authorization, HeaderMapExt};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub async fn permissions_guard(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
required_permissions: Vec<PermissionsEnum>,
|
||||
) -> Result<(imphnen_libs::jsonwebtoken::Claims, AppState), Response> {
|
||||
let auth_header = headers
|
||||
.typed_get::<Authorization<Bearer>>()
|
||||
.ok_or_else(|| {
|
||||
common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid or missing authorization token",
|
||||
)
|
||||
})?;
|
||||
|
||||
let token = auth_header.token();
|
||||
|
||||
let claims = decode_access_token(token)
|
||||
.map_err(|_| {
|
||||
common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid or expired token",
|
||||
)
|
||||
})?
|
||||
.claims;
|
||||
|
||||
// Fetch user from database to get permissions. Try email first, then try using the sub as a user id.
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let user = match user_repo.query_user_by_email(claims.sub.clone()).await {
|
||||
Ok(u) => u,
|
||||
Err(_) => {
|
||||
// Try treat claims.sub as a UUID (user id)
|
||||
let user_id = Uuid::parse_str(&claims.sub).map_err(|_| {
|
||||
common_response(StatusCode::UNAUTHORIZED, "Invalid user ID format")
|
||||
})?;
|
||||
match user_repo.query_user_by_id(&user_id.to_string()).await {
|
||||
Ok(u2) => u2,
|
||||
Err(_) => {
|
||||
return Err(common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"User not found",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Check permissions from database: collect both names and raw ids so checks
|
||||
// succeed whether permissions are stored by name or by UUID.
|
||||
let user_permissions: Vec<String> = user
|
||||
.role
|
||||
.permissions
|
||||
.as_ref()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter_map(|p| p.as_ref())
|
||||
.flat_map(|pp| {
|
||||
let mut res: Vec<String> = Vec::new();
|
||||
if let Some(name) = pp.name.clone() {
|
||||
res.push(name);
|
||||
}
|
||||
if let Some(id) = pp.id.as_ref().map(|id| id.to_string()) {
|
||||
res.push(id);
|
||||
}
|
||||
res
|
||||
})
|
||||
.collect();
|
||||
|
||||
|
||||
// If user has Administrator permission, allow all.
|
||||
// Accept either the permission name or the canonical permission id.
|
||||
let admin_name = PermissionsEnum::Administrator.to_string();
|
||||
let admin_id = PermissionsEnum::Administrator.id();
|
||||
|
||||
if user_permissions.contains(&admin_name) || user_permissions.contains(&admin_id) {
|
||||
return Ok((claims, state));
|
||||
}
|
||||
|
||||
for required in &required_permissions {
|
||||
let required_str = required.to_string();
|
||||
let required_id = required.id();
|
||||
|
||||
if !user_permissions.contains(&required_str) && !user_permissions.contains(&required_id) {
|
||||
eprintln!(" MISSING REQUIRED PERMISSION: {required_str} (ID: {required_id})");
|
||||
eprintln!(" USER PERMISSIONS: {:?}", user_permissions);
|
||||
return Err(common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"You don't have the required permissions",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok((claims, state))
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use imphnen_entities::PermissionsItemDto;
|
||||
use imphnen_entities::{PermissionsItemDto, MetaRequestDto, ResponseListSuccessDto};
|
||||
use super::PermissionsSchema;
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto, get_id, make_thing,
|
||||
};
|
||||
use crate::{AppState};
|
||||
use imphnen_libs::AppStatePostgresExt;
|
||||
use imphnen_entities::seaorm::auth::permissions::Entity as PermissionsEntity;
|
||||
use sea_orm::{EntityTrait, QueryFilter, ColumnTrait, QueryOrder, PaginatorTrait, QuerySelect, ActiveModelTrait, ActiveValue};
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_utils::{DetailQueryBuilder, QueryListBuilder, extract_id};
|
||||
use serde_json;
|
||||
use std::time::Instant;
|
||||
use tracing::instrument;
|
||||
use tracing::info;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct PermissionsRepository<'a> {
|
||||
state: &'a AppState,
|
||||
@@ -25,35 +25,67 @@ impl<'a> PermissionsRepository<'a> {
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<PermissionsItemDto>>> {
|
||||
let now = Instant::now();
|
||||
info!("Executing SurrealDB query: QueryListBuilder for Permissions with meta: {:?}", meta);
|
||||
let raw_result: ResponseListSuccessDto<Vec<PermissionsSchema>> =
|
||||
QueryListBuilder::new(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Permissions.to_string(),
|
||||
&meta,
|
||||
)
|
||||
.with_condition("is_deleted = false")
|
||||
.search_field("name")
|
||||
.select_fields(vec!["*"])
|
||||
.build()
|
||||
info!("Executing SeaORM query for Permissions list with meta: {:?}", meta);
|
||||
|
||||
let db = self.state.postgres_db();
|
||||
|
||||
// Build base query
|
||||
let mut query = PermissionsEntity::find()
|
||||
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false));
|
||||
|
||||
// Apply search if provided
|
||||
if let Some(search) = &meta.search {
|
||||
query = query.filter(imphnen_entities::seaorm::auth::permissions::Column::Name.contains(search));
|
||||
}
|
||||
|
||||
// Apply ordering
|
||||
let order_column = match meta.sort_by.as_deref() {
|
||||
Some("name") => imphnen_entities::seaorm::auth::permissions::Column::Name,
|
||||
Some("created_at") => imphnen_entities::seaorm::auth::permissions::Column::CreatedAt,
|
||||
_ => imphnen_entities::seaorm::auth::permissions::Column::CreatedAt,
|
||||
};
|
||||
|
||||
query = match meta.order.as_deref() {
|
||||
Some("desc") => query.order_by_desc(order_column),
|
||||
_ => query.order_by_asc(order_column),
|
||||
};
|
||||
|
||||
// Get total count for pagination
|
||||
let total_count = query.clone().count(db).await?;
|
||||
|
||||
// Apply pagination
|
||||
let page = meta.page.unwrap_or(1);
|
||||
let per_page = meta.per_page.unwrap_or(10);
|
||||
let offset = (page - 1) * per_page;
|
||||
|
||||
let permissions = query
|
||||
.offset(offset)
|
||||
.limit(per_page)
|
||||
.all(db)
|
||||
.await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_permission_list' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let transformed_data = raw_result
|
||||
.data
|
||||
let transformed_data = permissions
|
||||
.into_iter()
|
||||
.map(|permission| PermissionsSchema::list(&permission))
|
||||
.map(|permission| PermissionsItemDto {
|
||||
id: permission.id.to_string(),
|
||||
name: permission.name,
|
||||
created_at: Some(permission.created_at.to_rfc3339()),
|
||||
updated_at: Some(permission.updated_at.to_rfc3339()),
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ResponseListSuccessDto {
|
||||
data: transformed_data,
|
||||
meta: raw_result.meta,
|
||||
meta: Some(imphnen_entities::MetaResponseDto {
|
||||
page: Some(page),
|
||||
per_page: Some(per_page),
|
||||
total: Some(total_count),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -63,20 +95,30 @@ impl<'a> PermissionsRepository<'a> {
|
||||
id: String,
|
||||
) -> Result<PermissionsSchema> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
info!(id = %id, "Executing SurrealDB select for Permissions");
|
||||
let result: Option<PermissionsSchema> = db
|
||||
.select((ResourceEnum::Permissions.to_string(), id.clone()))
|
||||
let db = self.state.postgres_db();
|
||||
info!(id = %id, "Executing SeaORM select for Permissions");
|
||||
|
||||
let permission_id = Uuid::parse_str(&id)?;
|
||||
|
||||
let permission = PermissionsEntity::find_by_id(permission_id)
|
||||
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false))
|
||||
.one(db)
|
||||
.await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_permission_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
match result {
|
||||
Some(permission) if !permission.is_deleted => Ok(permission),
|
||||
_ => bail!("Permission not found"),
|
||||
|
||||
match permission {
|
||||
Some(permission) => Ok(PermissionsSchema {
|
||||
id: permission.id,
|
||||
name: permission.name,
|
||||
is_deleted: permission.is_deleted,
|
||||
created_at: Some(permission.created_at.to_rfc3339()),
|
||||
updated_at: Some(permission.updated_at.to_rfc3339()),
|
||||
}),
|
||||
None => bail!("Permission not found"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,13 +131,11 @@ impl<'a> PermissionsRepository<'a> {
|
||||
info!(id = %id, "Executing transformed_query_permission_by_id (delegates to query_permission_by_id)");
|
||||
let raw_result = self.query_permission_by_id(id.clone()).await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'transformed_query_permission_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
let transformed_data = PermissionsItemDto {
|
||||
id: extract_id(&raw_result.id),
|
||||
id: raw_result.id.to_string(),
|
||||
name: raw_result.name,
|
||||
created_at: raw_result.created_at,
|
||||
updated_at: raw_result.updated_at,
|
||||
@@ -109,22 +149,27 @@ impl<'a> PermissionsRepository<'a> {
|
||||
name: String,
|
||||
) -> Result<PermissionsSchema> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Permissions.to_string())
|
||||
.with_where("name", Some(name.clone()))
|
||||
.with_select_fields(vec!["*"]);
|
||||
let sql = builder.build();
|
||||
info!(query = %sql, "Executing SurrealDB query");
|
||||
let result: Option<PermissionsSchema> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
let db = self.state.postgres_db();
|
||||
info!(name = %name, "Executing SeaORM query for permission by name");
|
||||
|
||||
let permission = PermissionsEntity::find_by_name(&name)
|
||||
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false))
|
||||
.one(db)
|
||||
.await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_permission_by_name' took: {elapsed:.2?}");
|
||||
}
|
||||
match result {
|
||||
Some(permission) => Ok(permission),
|
||||
|
||||
match permission {
|
||||
Some(permission) => Ok(PermissionsSchema {
|
||||
id: permission.id,
|
||||
name: permission.name,
|
||||
is_deleted: permission.is_deleted,
|
||||
created_at: Some(permission.created_at.to_rfc3339()),
|
||||
updated_at: Some(permission.updated_at.to_rfc3339()),
|
||||
}),
|
||||
None => bail!("Permission not found"),
|
||||
}
|
||||
}
|
||||
@@ -135,22 +180,26 @@ impl<'a> PermissionsRepository<'a> {
|
||||
data: PermissionsSchema,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
info!("Executing SurrealDB create for Permissions with data: {:?}", data);
|
||||
let record: Option<PermissionsSchema> = db
|
||||
.create(ResourceEnum::Permissions.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
let db = self.state.postgres_db();
|
||||
info!("Executing SeaORM create for Permissions with data: {:?}", data);
|
||||
|
||||
let active_model = imphnen_entities::seaorm::auth::permissions::ActiveModel {
|
||||
id: ActiveValue::Set(data.id),
|
||||
name: ActiveValue::Set(data.name),
|
||||
is_deleted: ActiveValue::Set(data.is_deleted),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
deleted_at: ActiveValue::NotSet,
|
||||
};
|
||||
|
||||
let result = PermissionsEntity::insert(active_model).exec(db).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_create_permission' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success create permission".into()),
|
||||
None => bail!("Failed to create permission"),
|
||||
}
|
||||
|
||||
Ok(format!("Success create permission with id: {}", result.last_insert_id))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
@@ -159,57 +208,75 @@ impl<'a> PermissionsRepository<'a> {
|
||||
data: PermissionsSchema,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(&data.id)?;
|
||||
let existing = self.query_permission_by_id(data.id.id.to_raw()).await?;
|
||||
let db = self.state.postgres_db();
|
||||
|
||||
// Check if permission exists and is not deleted
|
||||
let existing = self.query_permission_by_id(data.id.to_string()).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Permission already deleted");
|
||||
}
|
||||
let merged = PermissionsSchema {
|
||||
created_at: existing.created_at,
|
||||
..data.clone()
|
||||
|
||||
info!(id = %data.id, "Executing SeaORM update for Permissions");
|
||||
|
||||
let active_model = imphnen_entities::seaorm::auth::permissions::ActiveModel {
|
||||
id: ActiveValue::Set(data.id),
|
||||
name: ActiveValue::Set(data.name),
|
||||
is_deleted: ActiveValue::Set(data.is_deleted),
|
||||
created_at: ActiveValue::Unchanged(existing.created_at.map(|s| {
|
||||
chrono::DateTime::parse_from_rfc3339(&s)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to parse created_at: {}", e))
|
||||
.unwrap()
|
||||
.with_timezone(&chrono::Utc)
|
||||
})
|
||||
.unwrap_or(chrono::Utc::now())),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
deleted_at: ActiveValue::NotSet,
|
||||
};
|
||||
info!(record_key = ?record_key, "Executing SurrealDB update for Permissions");
|
||||
let record: Option<PermissionsSchema> =
|
||||
db.update(record_key).merge(merged).await?;
|
||||
|
||||
let result = active_model.update(db).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_update_permission' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success update permission".into()),
|
||||
None => bail!("Failed to update permission"),
|
||||
}
|
||||
|
||||
Ok(format!("Success update permission with id: {}", result.id))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_permission(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let permission_id = make_thing(&ResourceEnum::Permissions.to_string(), &id);
|
||||
let permission = self
|
||||
.query_permission_by_id(permission_id.id.to_raw())
|
||||
.await?;
|
||||
if permission.is_deleted {
|
||||
bail!("Permission already deleted");
|
||||
}
|
||||
let record_key = get_id(&permission.id)?;
|
||||
info!(record_key = ?record_key, "Executing SurrealDB soft delete for Permissions");
|
||||
let record: Option<PermissionsSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
let db = self.state.postgres_db();
|
||||
|
||||
let permission_id = Uuid::parse_str(&id)?;
|
||||
|
||||
// Check if permission exists and is not deleted
|
||||
let permission = PermissionsEntity::find_by_id(permission_id)
|
||||
.filter(imphnen_entities::seaorm::auth::permissions::Column::IsDeleted.eq(false))
|
||||
.one(db)
|
||||
.await?;
|
||||
|
||||
let _permission = match permission {
|
||||
Some(p) => p,
|
||||
None => bail!("Permission not found"),
|
||||
};
|
||||
|
||||
info!(id = %id, "Executing SeaORM soft delete for Permissions");
|
||||
|
||||
let active_model = imphnen_entities::seaorm::auth::permissions::ActiveModel {
|
||||
id: ActiveValue::Set(permission_id),
|
||||
is_deleted: ActiveValue::Set(true),
|
||||
deleted_at: ActiveValue::Set(Some(chrono::Utc::now())),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let result = active_model.update(db).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string()) == "development" {
|
||||
println!("Query 'query_delete_permission' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success delete permission".into()),
|
||||
None => bail!("Failed to delete permission"),
|
||||
}
|
||||
|
||||
Ok(format!("Success delete permission with id: {}", result.id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use crate::ResourceEnum;
|
||||
use imphnen_utils::make_thing_from_enum;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
use uuid::Uuid;
|
||||
|
||||
use imphnen_entities::{PermissionsItemDto, PermissionsQueryDto};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct PermissionsSchema {
|
||||
pub id: Thing,
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
@@ -17,10 +15,7 @@ pub struct PermissionsSchema {
|
||||
impl Default for PermissionsSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::Permissions,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
id: Uuid::new_v4(),
|
||||
name: String::new(),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
@@ -32,7 +27,7 @@ impl Default for PermissionsSchema {
|
||||
impl PermissionsSchema {
|
||||
pub fn list(&self) -> PermissionsItemDto {
|
||||
PermissionsItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
id: self.to_string(),
|
||||
name: self.name.clone(),
|
||||
created_at: self.created_at.clone(),
|
||||
updated_at: self.updated_at.clone(),
|
||||
@@ -41,7 +36,7 @@ impl PermissionsSchema {
|
||||
|
||||
pub fn from(dto: PermissionsQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.unwrap_or_else(|| make_thing_from_enum(ResourceEnum::Permissions, "unknown")),
|
||||
id: Uuid::parse_str(&dto.id.unwrap_or_default()).unwrap_or(Uuid::new_v4()),
|
||||
name: dto.name.unwrap_or_default(),
|
||||
is_deleted: false,
|
||||
created_at: dto.created_at,
|
||||
@@ -49,3 +44,9 @@ impl PermissionsSchema {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PermissionsSchema {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,123 +1,125 @@
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, PermissionsRepository, PermissionsSchema, ResourceEnum,
|
||||
ResponseListSuccessDto, ResponseSuccessDto, common_response, make_thing,
|
||||
success_list_response, success_response, validate_request,
|
||||
};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
use imphnen_utils::get_iso_date;
|
||||
|
||||
use super::{PermissionsRequestDto, PermissionsUpdateRequestDto};
|
||||
|
||||
pub struct PermissionsService;
|
||||
|
||||
impl PermissionsService {
|
||||
pub async fn get_permission_list(
|
||||
state: &AppState,
|
||||
meta: MetaRequestDto,
|
||||
) -> Response {
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.query_permission_list(meta).await {
|
||||
Ok(data) => {
|
||||
let response = ResponseListSuccessDto {
|
||||
data: data.data,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_permission_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.transformed_query_permission_by_id(id).await {
|
||||
Ok(permission) => success_response(ResponseSuccessDto { data: permission }),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_role(
|
||||
state: &AppState,
|
||||
payload: PermissionsRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.query_permission_by_name(payload.name.clone()).await {
|
||||
Ok(_role) => {
|
||||
return common_response(
|
||||
StatusCode::CONFLICT,
|
||||
"Permission name already exists",
|
||||
);
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo
|
||||
.query_create_permission(PermissionsSchema {
|
||||
name: payload.name,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_permission(
|
||||
state: &AppState,
|
||||
payload: PermissionsUpdateRequestDto,
|
||||
id: String,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = PermissionsRepository::new(state);
|
||||
|
||||
// Get current permission data first
|
||||
let thing_id = make_thing(&ResourceEnum::Permissions.to_string(), &id);
|
||||
let current_permission = match repo.query_permission_by_id(id.clone()).await {
|
||||
Ok(permission) => permission,
|
||||
Err(_) => return common_response(StatusCode::NOT_FOUND, "Permission not found"),
|
||||
};
|
||||
|
||||
let mut updated_permission = current_permission;
|
||||
updated_permission.id = thing_id;
|
||||
updated_permission.updated_at = Some(get_iso_date());
|
||||
|
||||
// Only update fields that are provided
|
||||
if let Some(name) = payload.name {
|
||||
updated_permission.name = name;
|
||||
}
|
||||
|
||||
match repo.query_update_permission(updated_permission).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => {
|
||||
if e.to_string().contains("not found") {
|
||||
common_response(StatusCode::NOT_FOUND, "Permission not found")
|
||||
} else {
|
||||
common_response(StatusCode::BAD_REQUEST, &e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_permission(state: &AppState, id: String) -> Response {
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.query_delete_permission(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => {
|
||||
if e.to_string().contains("not found") {
|
||||
common_response(StatusCode::NOT_FOUND, "Permission not found")
|
||||
} else {
|
||||
common_response(StatusCode::BAD_REQUEST, &e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, PermissionsRepository, PermissionsSchema, ResourceEnum,
|
||||
ResponseListSuccessDto, ResponseSuccessDto, common_response,
|
||||
success_list_response, success_response, validate_request,
|
||||
};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
use crate::get_iso_date;
|
||||
use imphnen_utils::make_thing;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{PermissionsRequestDto, PermissionsUpdateRequestDto};
|
||||
|
||||
pub struct PermissionsService;
|
||||
|
||||
impl PermissionsService {
|
||||
pub async fn get_permission_list(
|
||||
state: &AppState,
|
||||
meta: MetaRequestDto,
|
||||
) -> Response {
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.query_permission_list(meta).await {
|
||||
Ok(data) => {
|
||||
let response = ResponseListSuccessDto {
|
||||
data: data.data,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_permission_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.transformed_query_permission_by_id(id).await {
|
||||
Ok(permission) => success_response(ResponseSuccessDto { data: permission }),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_role(
|
||||
state: &AppState,
|
||||
payload: PermissionsRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.query_permission_by_name(payload.name.clone()).await {
|
||||
Ok(_role) => {
|
||||
return common_response(
|
||||
StatusCode::CONFLICT,
|
||||
"Permission name already exists",
|
||||
);
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo
|
||||
.query_create_permission(PermissionsSchema {
|
||||
name: payload.name,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_permission(
|
||||
state: &AppState,
|
||||
payload: PermissionsUpdateRequestDto,
|
||||
id: String,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = PermissionsRepository::new(state);
|
||||
|
||||
// Get current permission data first
|
||||
let _thing_id = make_thing(&ResourceEnum::Permissions.to_string(), &id);
|
||||
let current_permission = match repo.query_permission_by_id(id.clone()).await {
|
||||
Ok(permission) => permission,
|
||||
Err(_) => return common_response(StatusCode::NOT_FOUND, "Permission not found"),
|
||||
};
|
||||
|
||||
let mut updated_permission = current_permission;
|
||||
updated_permission.id = Uuid::parse_str(&id).unwrap_or_else(|_| Uuid::new_v4());
|
||||
updated_permission.updated_at = Some(get_iso_date());
|
||||
|
||||
// Only update fields that are provided
|
||||
if let Some(name) = payload.name {
|
||||
updated_permission.name = name;
|
||||
}
|
||||
|
||||
match repo.query_update_permission(updated_permission).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => {
|
||||
if e.to_string().contains("not found") {
|
||||
common_response(StatusCode::NOT_FOUND, "Permission not found")
|
||||
} else {
|
||||
common_response(StatusCode::BAD_REQUEST, &e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_permission(state: &AppState, id: String) -> Response {
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo.query_delete_permission(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => {
|
||||
if e.to_string().contains("not found") {
|
||||
common_response(StatusCode::NOT_FOUND, "Permission not found")
|
||||
} else {
|
||||
common_response(StatusCode::BAD_REQUEST, &e.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,49 +1,49 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
|
||||
pub mod roles_controller;
|
||||
pub mod roles_dto;
|
||||
pub mod roles_enum;
|
||||
pub mod roles_repository;
|
||||
pub mod roles_schema;
|
||||
pub mod roles_service;
|
||||
|
||||
// Export only essential types and functions from each submodule
|
||||
pub use roles_controller::{
|
||||
get_role_list,
|
||||
get_role_by_id,
|
||||
post_create_role,
|
||||
put_update_role,
|
||||
delete_role
|
||||
};
|
||||
|
||||
pub use roles_dto::{
|
||||
RolesRequestCreateDto,
|
||||
RolesRequestUpdateDto,
|
||||
RolesDetailItemDto,
|
||||
RolesListItemDto,
|
||||
RolesDetailQueryDto,
|
||||
};
|
||||
|
||||
pub use roles_enum::RolesEnum;
|
||||
pub use roles_repository::RolesRepository;
|
||||
pub use roles_schema::RolesSchema;
|
||||
|
||||
pub fn roles_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_role_list))
|
||||
.route("/detail/{id}", get(get_role_by_id))
|
||||
.route("/create", post(post_create_role))
|
||||
.route("/update/{id}", put(put_update_role))
|
||||
.route("/delete/{id}", delete(delete_role))
|
||||
}
|
||||
|
||||
// Minimal admin router to satisfy test expectations at /v1/roles/admin
|
||||
pub fn admin_roles_router() -> Router {
|
||||
use roles_controller as controller;
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(controller::get_role_list))
|
||||
.route("/detail/{id}", axum::routing::get(controller::get_role_by_id))
|
||||
}
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
|
||||
pub mod roles_controller;
|
||||
pub mod roles_dto;
|
||||
pub mod roles_enum;
|
||||
pub mod roles_repository;
|
||||
pub mod roles_schema;
|
||||
pub mod roles_service;
|
||||
|
||||
// Export only essential types and functions from each submodule
|
||||
pub use roles_controller::{
|
||||
get_role_list,
|
||||
get_role_by_id,
|
||||
post_create_role,
|
||||
put_update_role,
|
||||
delete_role
|
||||
};
|
||||
|
||||
pub use roles_dto::{
|
||||
RolesRequestCreateDto,
|
||||
RolesRequestUpdateDto,
|
||||
RolesDetailItemDto,
|
||||
RolesListItemDto,
|
||||
RolesDetailQueryDto,
|
||||
};
|
||||
|
||||
pub use roles_enum::RolesEnum;
|
||||
pub use roles_repository::RolesRepository;
|
||||
pub use roles_schema::RolesSchema;
|
||||
|
||||
pub fn roles_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_role_list))
|
||||
.route("/detail/{id}", get(get_role_by_id))
|
||||
.route("/create", post(post_create_role))
|
||||
.route("/update/{id}", put(put_update_role))
|
||||
.route("/delete/{id}", delete(delete_role))
|
||||
}
|
||||
|
||||
// Minimal admin router to satisfy test expectations at /v1/roles/admin
|
||||
pub fn admin_roles_router() -> Router {
|
||||
use roles_controller as controller;
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(controller::get_role_list))
|
||||
.route("/detail/{id}", axum::routing::get(controller::get_role_by_id))
|
||||
}
|
||||
|
||||
@@ -1,167 +1,167 @@
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Query},
|
||||
response::IntoResponse,
|
||||
};
|
||||
|
||||
use super::{
|
||||
RolesDetailItemDto, RolesListItemDto, RolesRequestCreateDto, RolesRequestUpdateDto,
|
||||
};
|
||||
use crate::{
|
||||
AppState, MessageResponseDto, MetaRequestDto, PermissionsEnum,
|
||||
ResponseListSuccessDto, ResponseSuccessDto, permissions_guard,
|
||||
v1::roles_service::RolesService,
|
||||
};
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get role list", body = ResponseListSuccessDto<Vec<RolesListItemDto>>)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn get_role_list(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadListRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::get_role_list(&state, meta).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/detail/{id}",
|
||||
params(("id" = String, Path, description = "Role ID")),
|
||||
responses(
|
||||
(status = 200, description = "Get role by ID", body = ResponseSuccessDto<RolesDetailItemDto>)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn get_role_by_id(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadDetailRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::get_role_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/create",
|
||||
request_body = RolesRequestCreateDto,
|
||||
responses(
|
||||
(status = 201, description = "Create new role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn post_create_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<RolesRequestCreateDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::CreateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::create_role(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/update/{id}",
|
||||
request_body = RolesRequestUpdateDto,
|
||||
responses(
|
||||
(status = 200, description = "Update role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn put_update_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<RolesRequestUpdateDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::UpdateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::update_role(&state, id, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Delete role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn delete_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::DeleteRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::delete_role(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
use axum::{
|
||||
Extension, Json,
|
||||
extract::{Path, Query},
|
||||
response::IntoResponse,
|
||||
};
|
||||
|
||||
use super::{
|
||||
RolesDetailItemDto, RolesListItemDto, RolesRequestCreateDto, RolesRequestUpdateDto,
|
||||
};
|
||||
use crate::{
|
||||
AppState, MessageResponseDto, MetaRequestDto, PermissionsEnum,
|
||||
ResponseListSuccessDto, ResponseSuccessDto, permissions_guard,
|
||||
v1::roles_service::RolesService,
|
||||
};
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get role list", body = ResponseListSuccessDto<Vec<RolesListItemDto>>)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn get_role_list(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadListRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::get_role_list(&state, meta).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/detail/{id}",
|
||||
params(("id" = String, Path, description = "Role ID")),
|
||||
responses(
|
||||
(status = 200, description = "Get role by ID", body = ResponseSuccessDto<RolesDetailItemDto>)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn get_role_by_id(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadDetailRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::get_role_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/create",
|
||||
request_body = RolesRequestCreateDto,
|
||||
responses(
|
||||
(status = 201, description = "Create new role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn post_create_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<RolesRequestCreateDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::CreateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::create_role(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/update/{id}",
|
||||
request_body = RolesRequestUpdateDto,
|
||||
responses(
|
||||
(status = 200, description = "Update role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn put_update_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<RolesRequestUpdateDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::UpdateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::update_role(&state, id, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Delete role", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Roles"
|
||||
)]
|
||||
pub async fn delete_role(
|
||||
headers: axum::http::HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::DeleteRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => RolesService::delete_role(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
use imphnen_entities::{PermissionsItemDto, PermissionsQueryDto};
|
||||
use imphnen_entities::{PermissionsItemDto, PermissionsQueryDto, PermissionsEnum};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use uuid::Uuid;
|
||||
use validator::Validate;
|
||||
use strum::IntoEnumIterator;
|
||||
|
||||
use super::RolesSchema;
|
||||
use imphnen_entities::seaorm::auth::roles::Model as RolesModel;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct RolesRequestUpdateDto {
|
||||
@@ -32,35 +36,54 @@ pub struct RolesListItemDto {
|
||||
pub struct RolesDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
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 RolesDetailItemDto {
|
||||
pub fn from(dto: &RolesDetailQueryDto) -> Self {
|
||||
impl From<&RolesModel> for RolesDetailItemDto {
|
||||
fn from(model: &RolesModel) -> Self {
|
||||
let schema = RolesSchema::from(model);
|
||||
|
||||
let mut permissions_dto = vec![];
|
||||
if let Some(serde_json::Value::Array(perms)) = &model.permissions {
|
||||
for p in perms {
|
||||
if let Some(p_str) = p.as_str() {
|
||||
// Find matching enum
|
||||
for enum_val in PermissionsEnum::iter() {
|
||||
if enum_val.to_string() == p_str {
|
||||
permissions_dto.push(PermissionsItemDto {
|
||||
id: enum_val.id(),
|
||||
name: p_str.to_string(),
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
id: dto.id.id.to_raw(),
|
||||
name: dto.name.clone(),
|
||||
is_deleted: dto.is_deleted,
|
||||
permissions: dto
|
||||
.permissions
|
||||
.as_ref()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter_map(|p| p.as_ref())
|
||||
.map(PermissionsItemDto::from)
|
||||
.collect(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
id: schema.id.to_string(),
|
||||
name: schema.name.clone(),
|
||||
description: schema.description.clone(),
|
||||
is_system_role: schema.is_system_role,
|
||||
is_default: schema.is_default,
|
||||
permissions: permissions_dto,
|
||||
created_at: Some(schema.created_at.clone()),
|
||||
updated_at: Some(schema.updated_at.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RolesDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub permissions: Option<Vec<Option<PermissionsQueryDto>>>,
|
||||
pub is_deleted: bool,
|
||||
@@ -71,7 +94,7 @@ pub struct RolesDetailQueryDto {
|
||||
impl Default for RolesDetailQueryDto {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: Thing::from(("".to_string(), surrealdb::sql::Id::Number(0))),
|
||||
id: Uuid::new_v4(),
|
||||
name: String::new(),
|
||||
permissions: None,
|
||||
is_deleted: false,
|
||||
@@ -80,3 +103,9 @@ impl Default for RolesDetailQueryDto {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RolesDetailQueryDto {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RolesEnum {
|
||||
Admin,
|
||||
Administrator, // Added Administrator role
|
||||
User,
|
||||
Staff,
|
||||
Mentor, // Added Mentor role
|
||||
}
|
||||
|
||||
impl fmt::Display for RolesEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let roles_str = match self {
|
||||
RolesEnum::Admin => "Admin",
|
||||
RolesEnum::Administrator => "Administrator", // Added Administrator role
|
||||
RolesEnum::User => "User",
|
||||
RolesEnum::Staff => "Staff",
|
||||
RolesEnum::Mentor => "Mentor", // Added Mentor role
|
||||
};
|
||||
write!(f, "{roles_str}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_roles_enum_display() {
|
||||
assert_eq!(format!("{}", RolesEnum::Admin), "Admin");
|
||||
assert_eq!(format!("{}", RolesEnum::Administrator), "Administrator");
|
||||
assert_eq!(format!("{}", RolesEnum::User), "User");
|
||||
assert_eq!(format!("{}", RolesEnum::Staff), "Staff");
|
||||
assert_eq!(format!("{}", RolesEnum::Mentor), "Mentor");
|
||||
}
|
||||
}
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RolesEnum {
|
||||
Admin,
|
||||
Administrator, // Added Administrator role
|
||||
User,
|
||||
Staff,
|
||||
Mentor, // Added Mentor role
|
||||
}
|
||||
|
||||
impl fmt::Display for RolesEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let roles_str = match self {
|
||||
RolesEnum::Admin => "Admin",
|
||||
RolesEnum::Administrator => "Administrator", // Added Administrator role
|
||||
RolesEnum::User => "User",
|
||||
RolesEnum::Staff => "Staff",
|
||||
RolesEnum::Mentor => "Mentor", // Added Mentor role
|
||||
};
|
||||
write!(f, "{roles_str}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_roles_enum_display() {
|
||||
assert_eq!(format!("{}", RolesEnum::Admin), "Admin");
|
||||
assert_eq!(format!("{}", RolesEnum::Administrator), "Administrator");
|
||||
assert_eq!(format!("{}", RolesEnum::User), "User");
|
||||
assert_eq!(format!("{}", RolesEnum::Staff), "Staff");
|
||||
assert_eq!(format!("{}", RolesEnum::Mentor), "Mentor");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,202 +1,241 @@
|
||||
use super::{
|
||||
RolesDetailItemDto, RolesDetailQueryDto, RolesListItemDto, RolesRequestCreateDto,
|
||||
RolesRequestUpdateDto, RolesSchema,
|
||||
};
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto, get_id, make_thing,
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_utils::{DetailQueryBuilder, QueryListBuilder};
|
||||
use serde_json;
|
||||
use std::time::Instant;
|
||||
use surrealdb::Uuid;
|
||||
use surrealdb::sql::Thing;
|
||||
use tracing::instrument;
|
||||
|
||||
pub struct RolesRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> RolesRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, meta), err)]
|
||||
pub async fn query_role_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<RolesListItemDto>>> {
|
||||
let now = Instant::now();
|
||||
let result: ResponseListSuccessDto<Vec<RolesSchema>> = QueryListBuilder::new(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Roles.to_string(),
|
||||
&meta,
|
||||
)
|
||||
.search_field("name")
|
||||
.build()
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_role_list' took: {elapsed:.2?}");
|
||||
}
|
||||
let data = result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|role| RolesSchema::list(&role))
|
||||
.collect();
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
#[instrument(skip(self, name), err)]
|
||||
pub async fn query_role_by_name(
|
||||
&self,
|
||||
name: String,
|
||||
) -> Result<RolesDetailItemDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Roles.to_string())
|
||||
.with_where("name", Some(name.clone()))
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch("permissions");
|
||||
let sql = builder.build();
|
||||
let mut response = builder.apply_bindings(db.query(sql)).await?;
|
||||
|
||||
let result_vec: Vec<RolesDetailQueryDto> = response.take(0).map_err(|e| {
|
||||
anyhow::anyhow!("Failed to take result from response: {:?}", e)
|
||||
})?;
|
||||
|
||||
let role = result_vec
|
||||
.into_iter()
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("Role not found"))?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_role_by_name' took: {elapsed:.2?}");
|
||||
}
|
||||
Ok(RolesDetailItemDto::from(&role))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_role_by_id(&self, id: String) -> Result<RolesDetailItemDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let thing_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Roles.to_string())
|
||||
.with_id(&id)
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch("permissions");
|
||||
|
||||
let sql = builder.build();
|
||||
let sql_debug = sql.to_string(); // Move this line here
|
||||
let result: Option<RolesDetailQueryDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_role_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
let role = match result {
|
||||
Some(r) if !r.is_deleted => r,
|
||||
_ => bail!("Role not found sql: {} id: {}", sql_debug, thing_id),
|
||||
};
|
||||
Ok(RolesDetailItemDto::from(&role))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, payload), err)]
|
||||
pub async fn query_create_role(
|
||||
&self,
|
||||
payload: RolesRequestCreateDto,
|
||||
) -> Result<RolesDetailItemDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let role_id = Uuid::new_v4().to_string();
|
||||
let permission_things: Vec<Thing> = payload
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
|
||||
.collect();
|
||||
let role = RolesSchema {
|
||||
id: make_thing(&ResourceEnum::Roles.to_string(), &role_id),
|
||||
name: payload.name,
|
||||
is_deleted: false,
|
||||
permissions: permission_things,
|
||||
created_at: Some(crate::get_iso_date()),
|
||||
updated_at: Some(crate::get_iso_date()),
|
||||
};
|
||||
let _: Option<RolesSchema> = db
|
||||
.create((&ResourceEnum::Roles.to_string(), role_id.clone()))
|
||||
.content(role)
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_role' took: {elapsed:.2?}");
|
||||
}
|
||||
// After successful creation, fetch the created role
|
||||
self.query_role_by_id(role_id).await
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id, data), err)]
|
||||
pub async fn query_update_role(
|
||||
&self,
|
||||
id: String,
|
||||
data: RolesRequestUpdateDto,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let existing = self.query_role_by_id(id.clone()).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Role already deleted");
|
||||
}
|
||||
let merged = RolesSchema::update(data, id.clone(), existing);
|
||||
let record: Option<RolesSchema> =
|
||||
db.update(get_id(&merged.id)?).content(merged).await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_role' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success update role".into()),
|
||||
None => bail!("Failed to update role"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_role(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let role_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
|
||||
let role = self.query_role_by_id(role_id.id.to_raw()).await?;
|
||||
if role.is_deleted {
|
||||
bail!("Role already deleted");
|
||||
}
|
||||
let record_key = get_id(&role_id)?;
|
||||
let record: Option<RolesSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_role' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success delete role".into()),
|
||||
None => bail!("Failed to delete role"),
|
||||
}
|
||||
}
|
||||
}
|
||||
use super::{
|
||||
RolesDetailItemDto, RolesListItemDto, RolesRequestCreateDto,
|
||||
RolesRequestUpdateDto, RolesSchema,
|
||||
};
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use imphnen_entities::seaorm::auth::roles::{Entity as RolesEntity, Column as RolesColumn};
|
||||
use sea_orm::{EntityTrait, QueryFilter, QueryOrder, PaginatorTrait, ActiveModelTrait, ActiveValue, DatabaseConnection, ColumnTrait, QuerySelect, Order};
|
||||
use serde_json;
|
||||
use std::time::Instant;
|
||||
use uuid::Uuid;
|
||||
use tracing::instrument;
|
||||
|
||||
pub struct RolesRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> RolesRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
fn db(&self) -> &DatabaseConnection {
|
||||
&self.state.postgres_connection.conn
|
||||
}
|
||||
|
||||
#[instrument(skip(self, meta), err)]
|
||||
pub async fn query_role_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<RolesListItemDto>>> {
|
||||
let now = Instant::now();
|
||||
|
||||
// Build SeaORM query
|
||||
let mut query = RolesEntity::find()
|
||||
.filter(RolesColumn::DeletedAt.is_null());
|
||||
|
||||
// Apply search filter
|
||||
if let Some(search) = &meta.search {
|
||||
query = query.filter(RolesColumn::Name.contains(search));
|
||||
}
|
||||
|
||||
// Apply sorting
|
||||
let sort_column = match meta.sort_by.as_deref() {
|
||||
Some("name") => RolesColumn::Name,
|
||||
Some("created_at") => RolesColumn::CreatedAt,
|
||||
_ => RolesColumn::CreatedAt,
|
||||
};
|
||||
|
||||
query = match meta.order.as_deref() {
|
||||
Some("desc") => query.order_by(sort_column, Order::Desc),
|
||||
_ => query.order_by(sort_column, Order::Asc),
|
||||
};
|
||||
|
||||
// Get total count
|
||||
let total_count = query.clone().count(self.db()).await?;
|
||||
|
||||
// Apply pagination
|
||||
let page = meta.page.unwrap_or(1);
|
||||
let per_page = meta.per_page.unwrap_or(10);
|
||||
let offset = (page - 1) * per_page;
|
||||
|
||||
let roles = query
|
||||
.offset(offset)
|
||||
.limit(per_page)
|
||||
.all(self.db())
|
||||
.await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_role_list' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let data = roles
|
||||
.into_iter()
|
||||
.map(|role| {
|
||||
let schema = RolesSchema::from(&role);
|
||||
schema.list()
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: Some(imphnen_entities::MetaResponseDto {
|
||||
total: Some(total_count),
|
||||
page: Some(page),
|
||||
per_page: Some(per_page),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
#[instrument(skip(self, name), err)]
|
||||
pub async fn query_role_by_name(
|
||||
&self,
|
||||
name: String,
|
||||
) -> Result<RolesDetailItemDto> {
|
||||
let now = Instant::now();
|
||||
|
||||
let role = RolesEntity::find()
|
||||
.filter(RolesColumn::Name.eq(name))
|
||||
.filter(RolesColumn::DeletedAt.is_null())
|
||||
.one(self.db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Role not found"))?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_role_by_name' took: {elapsed:.2?}");
|
||||
}
|
||||
Ok(RolesDetailItemDto::from(&role))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_role_by_id(&self, id: String) -> Result<RolesDetailItemDto> {
|
||||
let now = Instant::now();
|
||||
|
||||
let role_id = Uuid::parse_str(&id)
|
||||
.map_err(|_| anyhow::anyhow!("Invalid role ID"))?;
|
||||
|
||||
let role = RolesEntity::find_by_id(role_id)
|
||||
.filter(RolesColumn::DeletedAt.is_null())
|
||||
.one(self.db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("Role not found"))?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_role_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
Ok(RolesDetailItemDto::from(&role))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, payload), err)]
|
||||
pub async fn query_create_role(
|
||||
&self,
|
||||
payload: RolesRequestCreateDto,
|
||||
) -> Result<RolesDetailItemDto> {
|
||||
let now = Instant::now();
|
||||
|
||||
let role_id = Uuid::new_v4();
|
||||
let permissions_json = serde_json::to_value(&payload.permissions)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to serialize permissions: {}", e))?;
|
||||
|
||||
let active_model = imphnen_entities::seaorm::auth::roles::ActiveModel {
|
||||
id: ActiveValue::Set(role_id),
|
||||
name: ActiveValue::Set(payload.name),
|
||||
description: ActiveValue::Set("".to_string()), // Default description
|
||||
is_system_role: ActiveValue::Set(false),
|
||||
is_default: ActiveValue::Set(false),
|
||||
permissions: ActiveValue::Set(Some(permissions_json)),
|
||||
created_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
updated_at: ActiveValue::Set(chrono::Utc::now()),
|
||||
deleted_at: ActiveValue::NotSet,
|
||||
};
|
||||
|
||||
let created_role = active_model.insert(self.db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_role' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
// Return the created role
|
||||
Ok(RolesDetailItemDto::from(&created_role))
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id, data), err)]
|
||||
pub async fn query_update_role(
|
||||
&self,
|
||||
id: String,
|
||||
data: RolesRequestUpdateDto,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let role_id = Uuid::parse_str(&id)
|
||||
.map_err(|_| anyhow::anyhow!("Invalid role ID"))?;
|
||||
|
||||
let mut active_model = imphnen_entities::seaorm::auth::roles::ActiveModel {
|
||||
id: ActiveValue::Unchanged(role_id),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(name) = data.name {
|
||||
active_model.name = ActiveValue::Set(name);
|
||||
}
|
||||
|
||||
if let Some(permissions) = data.permissions {
|
||||
let permissions_json = serde_json::to_value(&permissions)
|
||||
.map_err(|e| anyhow::anyhow!("Failed to serialize permissions: {}", e))?;
|
||||
active_model.permissions = ActiveValue::Set(Some(permissions_json));
|
||||
}
|
||||
|
||||
active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
let _updated_role = active_model.update(self.db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_role' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success update role".into())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_delete_role(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let role_id = Uuid::parse_str(&id)
|
||||
.map_err(|_| anyhow::anyhow!("Invalid role ID"))?;
|
||||
|
||||
let active_model = imphnen_entities::seaorm::auth::roles::ActiveModel {
|
||||
id: ActiveValue::Unchanged(role_id),
|
||||
deleted_at: ActiveValue::Set(Some(chrono::Utc::now())),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let _updated_role = active_model.update(self.db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_role' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success delete role".into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,127 +1,50 @@
|
||||
use super::{
|
||||
RolesDetailItemDto, RolesDetailQueryDto, RolesListItemDto, RolesRequestCreateDto,
|
||||
RolesRequestUpdateDto,
|
||||
};
|
||||
use crate::ResourceEnum;
|
||||
use imphnen_utils::{get_iso_date, make_thing_from_enum};
|
||||
use super::RolesListItemDto;
|
||||
use imphnen_entities::seaorm::auth::roles::Model as RolesModel;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RolesSchema {
|
||||
pub id: Thing,
|
||||
pub id: Uuid,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub permissions: Vec<Thing>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
pub description: String,
|
||||
pub is_system_role: bool,
|
||||
pub is_default: bool,
|
||||
pub permissions: Vec<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub deleted_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for RolesSchema {
|
||||
fn default() -> Self {
|
||||
RolesSchema {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::Roles,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
permissions: vec![make_thing_from_enum(
|
||||
ResourceEnum::Permissions,
|
||||
&Uuid::new_v4().to_string(),
|
||||
)],
|
||||
name: String::new(),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
impl From<&RolesModel> for RolesSchema {
|
||||
fn from(model: &RolesModel) -> Self {
|
||||
let permissions = model.permissions
|
||||
.as_ref()
|
||||
.and_then(|p| serde_json::from_value(p.clone()).ok())
|
||||
.unwrap_or_default();
|
||||
|
||||
Self {
|
||||
id: model.id,
|
||||
name: model.name.clone(),
|
||||
description: model.description.clone(),
|
||||
is_system_role: model.is_system_role,
|
||||
is_default: model.is_default,
|
||||
permissions,
|
||||
created_at: model.created_at.to_rfc3339(),
|
||||
updated_at: model.updated_at.to_rfc3339(),
|
||||
deleted_at: model.deleted_at.map(|dt| dt.to_rfc3339()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RolesSchema {
|
||||
pub fn from(dto: RolesDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
name: dto.name,
|
||||
permissions: dto
|
||||
.permissions
|
||||
.as_ref()
|
||||
.unwrap_or(&vec![])
|
||||
.iter()
|
||||
.filter_map(|perm| {
|
||||
perm.as_ref().and_then(|p| p.id.as_ref().map(|id| make_thing_from_enum(ResourceEnum::Permissions, &id.id.to_raw())))
|
||||
})
|
||||
.collect(),
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create(dto: RolesRequestCreateDto) -> Self {
|
||||
let permissions: Vec<Thing> = dto
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|id| make_thing_from_enum(ResourceEnum::Permissions, &id))
|
||||
.collect();
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::Roles,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
name: dto.name,
|
||||
permissions,
|
||||
is_deleted: false,
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(
|
||||
dto: RolesRequestUpdateDto,
|
||||
id: String,
|
||||
existing: RolesDetailItemDto,
|
||||
) -> Self {
|
||||
let name = dto.name.unwrap_or(existing.name);
|
||||
let permissions: Vec<Thing> =
|
||||
match (dto.permissions, dto.overwrite.unwrap_or(false)) {
|
||||
(Some(new_ids), true) => new_ids
|
||||
.iter()
|
||||
.map(|id| make_thing_from_enum(ResourceEnum::Permissions, id))
|
||||
.collect(),
|
||||
(Some(new_ids), false) => {
|
||||
let mut all_ids: HashSet<String> =
|
||||
existing.permissions.iter().map(|p| p.id.clone()).collect();
|
||||
for id in new_ids {
|
||||
all_ids.insert(id);
|
||||
}
|
||||
all_ids
|
||||
.into_iter()
|
||||
.map(|id| make_thing_from_enum(ResourceEnum::Permissions, &id))
|
||||
.collect()
|
||||
},
|
||||
(None, _) => existing
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|p| make_thing_from_enum(ResourceEnum::Permissions, &p.id))
|
||||
.collect(),
|
||||
};
|
||||
Self {
|
||||
id: make_thing_from_enum(ResourceEnum::Roles, &id),
|
||||
name,
|
||||
permissions,
|
||||
is_deleted: existing.is_deleted,
|
||||
created_at: existing.created_at,
|
||||
updated_at: Some(get_iso_date()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn list(&self) -> RolesListItemDto {
|
||||
RolesListItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
id: self.id.to_string(),
|
||||
name: self.name.clone(),
|
||||
permissions_count: self.permissions.len(),
|
||||
created_at: self.created_at.clone(),
|
||||
updated_at: self.updated_at.clone(),
|
||||
created_at: Some(self.created_at.clone()),
|
||||
updated_at: Some(self.updated_at.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,113 +1,113 @@
|
||||
use super::{RolesRepository, RolesRequestCreateDto, RolesRequestUpdateDto};
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
common_response, success_list_response, success_response, validate_request,
|
||||
};
|
||||
use imphnen_utils::success_created_response;
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
|
||||
pub struct RolesService;
|
||||
|
||||
impl RolesService {
|
||||
pub async fn get_role_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_list(meta).await {
|
||||
Ok(data) => {
|
||||
let response = ResponseListSuccessDto {
|
||||
data: data.data,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_role_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_id(id).await {
|
||||
Ok(role) => success_response(ResponseSuccessDto { data: role }),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_role(
|
||||
state: &AppState,
|
||||
payload: RolesRequestCreateDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_name(payload.name.clone()).await {
|
||||
Ok(_role) => {
|
||||
return common_response(StatusCode::CONFLICT, "Role name already exists");
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo.query_create_role(payload).await {
|
||||
Ok(created_role) => success_created_response(ResponseSuccessDto { data: created_role }),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_role(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
payload: RolesRequestUpdateDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = RolesRepository::new(state);
|
||||
let existing_role = match repo.query_role_by_id(id.clone()).await {
|
||||
Ok(role) => role,
|
||||
Err(err) if err.to_string().contains("not found") => {
|
||||
return common_response(StatusCode::NOT_FOUND, "Role not found");
|
||||
}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
};
|
||||
if let Some(new_name) = payload.name.clone() {
|
||||
match repo.query_role_by_name(new_name.clone()).await {
|
||||
Ok(role_with_same_name) => {
|
||||
if role_with_same_name.id != existing_role.id {
|
||||
return common_response(
|
||||
StatusCode::CONFLICT,
|
||||
"Role name already exists",
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
match repo.query_update_role(id, payload).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_role(state: &AppState, id: String) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_id(id.clone()).await {
|
||||
Ok(_) => {}
|
||||
Err(err) if err.to_string().contains("not found") => {
|
||||
return common_response(StatusCode::NOT_FOUND, "Role not found");
|
||||
}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo.query_delete_role(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
use super::{RolesRepository, RolesRequestCreateDto, RolesRequestUpdateDto};
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
common_response, success_list_response, success_response, validate_request,
|
||||
};
|
||||
use crate::success_created_response;
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
|
||||
pub struct RolesService;
|
||||
|
||||
impl RolesService {
|
||||
pub async fn get_role_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_list(meta).await {
|
||||
Ok(data) => {
|
||||
let response = ResponseListSuccessDto {
|
||||
data: data.data,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_role_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_id(id).await {
|
||||
Ok(role) => success_response(ResponseSuccessDto { data: role }),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_role(
|
||||
state: &AppState,
|
||||
payload: RolesRequestCreateDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_name(payload.name.clone()).await {
|
||||
Ok(_role) => {
|
||||
return common_response(StatusCode::CONFLICT, "Role name already exists");
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo.query_create_role(payload).await {
|
||||
Ok(created_role) => success_created_response(ResponseSuccessDto { data: created_role }),
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_role(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
payload: RolesRequestUpdateDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = RolesRepository::new(state);
|
||||
let existing_role = match repo.query_role_by_id(id.clone()).await {
|
||||
Ok(role) => role,
|
||||
Err(err) if err.to_string().contains("not found") => {
|
||||
return common_response(StatusCode::NOT_FOUND, "Role not found");
|
||||
}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
};
|
||||
if let Some(new_name) = payload.name.clone() {
|
||||
match repo.query_role_by_name(new_name.clone()).await {
|
||||
Ok(role_with_same_name) => {
|
||||
if role_with_same_name.id != existing_role.id {
|
||||
return common_response(
|
||||
StatusCode::CONFLICT,
|
||||
"Role name already exists",
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) if err.to_string().contains("not found") => {}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
match repo.query_update_role(id, payload).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_role(state: &AppState, id: String) -> Response {
|
||||
let repo = RolesRepository::new(state);
|
||||
match repo.query_role_by_id(id.clone()).await {
|
||||
Ok(_) => {}
|
||||
Err(err) if err.to_string().contains("not found") => {
|
||||
return common_response(StatusCode::NOT_FOUND, "Role not found");
|
||||
}
|
||||
Err(e) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
|
||||
}
|
||||
}
|
||||
match repo.query_delete_role(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
use crate::{AppState, MetaRequestDto};
|
||||
use crate::{
|
||||
MessageResponseDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
TeamsCreateRequestDto, TeamsUpdateRequestDto, TeamInviteRequestDto,
|
||||
TeamMemberDto, AdminTeamsListItemDto, AdminTeamsDetailItemDto, PermissionsEnum
|
||||
};
|
||||
use axum::response::Response;
|
||||
use axum::extract::Path;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, Json};
|
||||
use super::teams_service::{TeamsServiceTrait, TeamsService};
|
||||
use axum::Router;
|
||||
|
||||
/// Helper function for admin endpoints requiring specific permissions
|
||||
async fn with_admin_perms<F, Fut>(
|
||||
headers: HeaderMap,
|
||||
state: Extension<AppState>,
|
||||
f: F,
|
||||
) -> Response
|
||||
where
|
||||
F: FnOnce(crate::Claims, AppState) -> Fut,
|
||||
Fut: std::future::Future<Output = Response> + Send,
|
||||
{
|
||||
match crate::permissions_guard(headers, state, vec![PermissionsEnum::ManageAllTeams]).await {
|
||||
Ok((claims, state)) => f(claims, state).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/",
|
||||
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 all teams (admin)", body = ResponseListSuccessDto<Vec<AdminTeamsListItemDto>>)
|
||||
),
|
||||
tag = "Admin - Teams"
|
||||
)]
|
||||
pub async fn get_all_teams(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
axum::extract::Query(meta): axum::extract::Query<MetaRequestDto>,
|
||||
) -> Response {
|
||||
with_admin_perms(headers, Extension(state), move |_claims, state| {
|
||||
TeamsService::get_admin_team_list(&state, meta)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get team by ID (admin)", body = ResponseSuccessDto<AdminTeamsDetailItemDto>)
|
||||
),
|
||||
tag = "Admin - Teams"
|
||||
)]
|
||||
pub async fn get_team_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
with_admin_perms(headers, Extension(state), move |_claims, state| {
|
||||
TeamsService::get_admin_team_by_id(&state, id)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/{id}/members",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get team members (admin)", body = ResponseSuccessDto<Vec<TeamMemberDto>>)
|
||||
),
|
||||
tag = "Admin - Teams"
|
||||
)]
|
||||
pub async fn get_team_members(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
with_admin_perms(headers, Extension(state), move |_claims, state| {
|
||||
TeamsService::get_admin_team_members(&state, id)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/create",
|
||||
request_body = TeamsCreateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Create team (admin)", body = ResponseSuccessDto<serde_json::Value>)
|
||||
),
|
||||
tag = "Admin - Teams"
|
||||
)]
|
||||
pub async fn create_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<TeamsCreateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
with_admin_perms(headers, Extension(state), move |claims, state| {
|
||||
TeamsService::create_team(&state, claims, payload)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
request_body = TeamsUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Update team (admin)", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Admin - Teams"
|
||||
)]
|
||||
pub async fn update_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<TeamsUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
with_admin_perms(headers, Extension(state), move |claims, state| {
|
||||
// Admin update should bypass leader-only restriction
|
||||
TeamsService::update_team_admin(&state, claims, id, payload)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/delete/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Delete team (admin)", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Admin - Teams"
|
||||
)]
|
||||
pub async fn delete_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
with_admin_perms(headers, Extension(state), move |claims, state| {
|
||||
TeamsService::delete_team_admin(&state, claims, id)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/{id}/invite",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
request_body = TeamInviteRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Invite team members (admin)", body = ResponseSuccessDto<serde_json::Value>)
|
||||
),
|
||||
tag = "Admin - Teams"
|
||||
)]
|
||||
pub async fn invite_team_members(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(team_id): Path<String>,
|
||||
Json(payload): Json<TeamInviteRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
with_admin_perms(headers, Extension(state), move |claims, state| {
|
||||
TeamsService::invite_team_members_admin(&state, claims, team_id, payload)
|
||||
}).await
|
||||
}
|
||||
|
||||
pub fn admin_teams_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(get_all_teams))
|
||||
.route("/detail/{id}", axum::routing::get(get_team_by_id))
|
||||
.route("/{id}/members", axum::routing::get(get_team_members))
|
||||
.route("/create", axum::routing::post(create_team))
|
||||
.route("/update/{id}", axum::routing::put(update_team))
|
||||
.route("/delete/{id}", axum::routing::delete(delete_team))
|
||||
.route("/{id}/invite", axum::routing::post(invite_team_members))
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
pub mod admin_teams_controller;
|
||||
pub mod teams_controller;
|
||||
pub mod teams_dto;
|
||||
pub mod teams_repository;
|
||||
pub mod teams_schema;
|
||||
pub mod teams_service;
|
||||
|
||||
use axum::Router;
|
||||
|
||||
// Export only essential types and functions from each submodule
|
||||
pub use admin_teams_controller::{
|
||||
admin_teams_router,
|
||||
get_all_teams as admin_get_all_teams,
|
||||
get_team_by_id as admin_get_team_by_id,
|
||||
get_team_members as admin_get_team_members,
|
||||
create_team as admin_create_team,
|
||||
update_team as admin_update_team,
|
||||
delete_team as admin_delete_team,
|
||||
invite_team_members as admin_invite_team_members
|
||||
};
|
||||
|
||||
pub use teams_controller::{
|
||||
teams_router as user_teams_router,
|
||||
get_team_list,
|
||||
get_team_by_id as user_get_team_by_id,
|
||||
get_team_members as user_get_team_members
|
||||
};
|
||||
|
||||
pub use teams_dto::{
|
||||
TeamsCreateRequestDto,
|
||||
TeamsUpdateRequestDto,
|
||||
TeamInviteRequestDto,
|
||||
TeamMemberDto,
|
||||
TeamsListItemDto,
|
||||
TeamsDetailItemDto,
|
||||
PublicTeamsListItemDto,
|
||||
PublicTeamsDetailItemDto,
|
||||
AdminTeamsListItemDto,
|
||||
AdminTeamsDetailItemDto,
|
||||
TeamAcceptInvitationRequestDto,
|
||||
TeamsSearchQueryDto,
|
||||
TeamsDetailQueryDto,
|
||||
TeamsListQueryDto,
|
||||
TeamMembersQueryDto,
|
||||
TeamInvitationsQueryDto,
|
||||
MemberTeamsDetailItemDto,
|
||||
AddTeamMemberRequestDto,
|
||||
UpdateMemberRoleRequestDto,
|
||||
TeamInvitationListDto,
|
||||
MyInvitationDto
|
||||
};
|
||||
|
||||
pub use teams_repository::TeamsRepository;
|
||||
pub use teams_schema::{TeamsSchema, TeamMembersSchema, TeamInvitationsSchema};
|
||||
|
||||
pub fn teams_router() -> Router {
|
||||
Router::new()
|
||||
// Public routes
|
||||
.merge(teams_controller::teams_router())
|
||||
// Admin routes - prefixed with /admin to avoid route conflicts
|
||||
.nest("/admin", admin_teams_controller::admin_teams_router())
|
||||
}
|
||||
@@ -1,672 +0,0 @@
|
||||
use crate::{AppState, MetaRequestDto};
|
||||
use crate::{
|
||||
MessageResponseDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
TeamsCreateRequestDto, TeamsDetailItemDto, TeamsListItemDto, permissions_guard,
|
||||
TeamsUpdateRequestDto, TeamInviteRequestDto, TeamAcceptInvitationRequestDto,
|
||||
TeamMemberDto, TeamsSearchQueryDto, PublicTeamsListItemDto, PublicTeamsDetailItemDto,
|
||||
AdminTeamsListItemDto, AdminTeamsDetailItemDto, PermissionsEnum,
|
||||
AddTeamMemberRequestDto, UpdateMemberRoleRequestDto,
|
||||
TeamInvitationListDto, MyInvitationDto
|
||||
};
|
||||
use super::super::teams::{TeamsRepository, TeamMembersSchema};
|
||||
use axum::response::Response;
|
||||
use axum::extract::Path;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, Json};
|
||||
use super::teams_service::{TeamsServiceTrait, TeamsService};
|
||||
use axum::Router;
|
||||
|
||||
// Helper function for endpoints requiring authentication without specific permissions
|
||||
async fn authenticated<F, Fut>(
|
||||
headers: HeaderMap,
|
||||
state: Extension<AppState>,
|
||||
f: F,
|
||||
) -> Response
|
||||
where
|
||||
F: FnOnce(crate::Claims, AppState) -> Fut,
|
||||
Fut: std::future::Future<Output = Response> + Send,
|
||||
{
|
||||
match permissions_guard(headers, state, vec![]).await {
|
||||
Ok((claims, state)) => f(claims, state).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function for endpoints requiring specific permissions
|
||||
async fn with_perms<F, Fut>(
|
||||
headers: HeaderMap,
|
||||
state: Extension<AppState>,
|
||||
perms: Vec<PermissionsEnum>,
|
||||
f: F,
|
||||
) -> Response
|
||||
where
|
||||
F: FnOnce(crate::Claims, AppState) -> Fut,
|
||||
Fut: std::future::Future<Output = Response> + Send,
|
||||
{
|
||||
match permissions_guard(headers, state, perms).await {
|
||||
Ok((claims, state)) => f(claims, state).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams",
|
||||
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 team list", body = ResponseListSuccessDto<Vec<TeamsListItemDto>>),
|
||||
(status = 200, description = "Get public team list", body = ResponseListSuccessDto<Vec<PublicTeamsListItemDto>>)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn get_team_list(
|
||||
Extension(state): Extension<AppState>,
|
||||
axum::extract::Query(meta): axum::extract::Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
TeamsService::get_public_team_list(&state, meta).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/teams/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get team by ID", body = ResponseSuccessDto<TeamsDetailItemDto>),
|
||||
(status = 200, description = "Get public team by ID", body = ResponseSuccessDto<PublicTeamsDetailItemDto>)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn get_team_by_id(
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
TeamsService::get_public_team_by_id(&state, id).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/create",
|
||||
request_body = TeamsCreateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Create new team", body = ResponseSuccessDto<serde_json::Value>)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn post_create_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<TeamsCreateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::create_team(&state, claims, payload)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
request_body = TeamsUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Update team", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn put_update_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<TeamsUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
|
||||
// Try to treat this request as an admin first; if the caller has ManageAllTeams
|
||||
// permission, route to the admin update. Otherwise fall back to normal authenticated
|
||||
// update which enforces leader-only rules.
|
||||
let state_clone = state.clone();
|
||||
match crate::permissions_guard(headers.clone(), axum::Extension(state_clone.clone()), vec![PermissionsEnum::ManageAllTeams]).await {
|
||||
Ok((claims, state)) => {
|
||||
// Caller is admin
|
||||
TeamsService::update_team_admin(&state, claims, id, payload).await
|
||||
}
|
||||
Err(_) => {
|
||||
// Not admin - proceed with normal authenticated flow
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::update_team(&state, claims, id, payload)).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/{id}/members/create",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
request_body = AddTeamMemberRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[AUTH] Add member to team successfully", body = ResponseSuccessDto<String>),
|
||||
(status = 401, description = "[AUTH] Unauthorized"),
|
||||
(status = 403, description = "[AUTH] Only team leader or members can add"),
|
||||
(status = 404, description = "[AUTH] Team not found")
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn post_add_team_member(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(team_id): Path<String>,
|
||||
Json(payload): Json<AddTeamMemberRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
// Determine caller and whether they have admin permissions
|
||||
let state_clone = state.clone();
|
||||
let is_admin = crate::permissions_guard(headers.clone(), axum::Extension(state_clone.clone()), vec![PermissionsEnum::ManageAllTeams]).await.is_ok();
|
||||
|
||||
// Authenticate the caller (will return 401 if no token)
|
||||
let auth = permissions_guard(headers, axum::Extension(state.clone()), vec![/* no specific perms */]).await;
|
||||
let (claims, state) = match auth {
|
||||
Ok((c, s)) => (c, s),
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
// Permission: admins can add anyone; otherwise only team leader or existing member can add
|
||||
let repo = TeamsRepository::new(&state);
|
||||
let thing_id = imphnen_utils::make_thing_from_enum(imphnen_libs::ResourceEnum::Teams, &team_id);
|
||||
let team = match repo.query_team_by_id(&thing_id).await {
|
||||
Ok(t) => t,
|
||||
Err(_) => return crate::common_response(axum::http::StatusCode::NOT_FOUND, "Team not found"),
|
||||
};
|
||||
|
||||
if !is_admin {
|
||||
let user_thing = imphnen_utils::make_thing_from_enum(imphnen_libs::ResourceEnum::Users, &claims.user_id);
|
||||
let is_member = repo.query_is_team_member(&thing_id, &user_thing).await.unwrap_or(false);
|
||||
let is_leader = team.leader_id.id.to_raw() == claims.user_id;
|
||||
if !is_member && !is_leader {
|
||||
return crate::common_response(axum::http::StatusCode::FORBIDDEN, "Only team leader or members can add a member");
|
||||
}
|
||||
}
|
||||
|
||||
// Build member schema and add via repository
|
||||
let member_schema = TeamMembersSchema::create(team_id.clone(), payload.user_id.clone(), payload.role.clone());
|
||||
match repo.query_add_team_member(member_schema).await {
|
||||
Ok(msg) => crate::success_response(crate::ResponseSuccessDto { data: msg }),
|
||||
Err(e) => crate::common_response(axum::http::StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/{id}/members/delete/{user_id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID"),
|
||||
("user_id" = String, Path, description = "User ID to remove")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[AUTH] Member removed successfully", body = ResponseSuccessDto<String>),
|
||||
(status = 401, description = "[AUTH] Unauthorized"),
|
||||
(status = 403, description = "[AUTH] Only team leader can remove members"),
|
||||
(status = 404, description = "[AUTH] Team not found")
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn delete_remove_team_member(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path((team_id, user_id)): Path<(String, String)>,
|
||||
) -> impl IntoResponse {
|
||||
let state_clone = state.clone();
|
||||
let is_admin = crate::permissions_guard(headers.clone(), axum::Extension(state_clone.clone()), vec![PermissionsEnum::ManageAllTeams]).await.is_ok();
|
||||
|
||||
let auth = permissions_guard(headers, axum::Extension(state.clone()), vec![]).await;
|
||||
let (claims, state) = match auth {
|
||||
Ok((c, s)) => (c, s),
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
let repo = TeamsRepository::new(&state);
|
||||
let thing_id = imphnen_utils::make_thing_from_enum(imphnen_libs::ResourceEnum::Teams, &team_id);
|
||||
let team = match repo.query_team_by_id(&thing_id).await {
|
||||
Ok(t) => t,
|
||||
Err(_) => return crate::common_response(axum::http::StatusCode::NOT_FOUND, "Team not found"),
|
||||
};
|
||||
|
||||
if !is_admin {
|
||||
// Only leader can remove members
|
||||
if team.leader_id.id.to_raw() != claims.user_id {
|
||||
return crate::common_response(axum::http::StatusCode::FORBIDDEN, "Only team leader can remove members");
|
||||
}
|
||||
}
|
||||
|
||||
let user_thing = imphnen_utils::make_thing_from_enum(imphnen_libs::ResourceEnum::Users, &user_id);
|
||||
match repo.query_remove_team_member(&thing_id, &user_thing).await {
|
||||
Ok(msg) => crate::success_response(crate::ResponseSuccessDto { data: msg }),
|
||||
Err(e) => crate::common_response(axum::http::StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/{id}/members/update/{user_id}/role",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID"),
|
||||
("user_id" = String, Path, description = "User ID")
|
||||
),
|
||||
request_body = UpdateMemberRoleRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[AUTH] Member role updated successfully", body = ResponseSuccessDto<String>),
|
||||
(status = 401, description = "[AUTH] Unauthorized"),
|
||||
(status = 403, description = "[AUTH] Only team leader can update roles"),
|
||||
(status = 404, description = "[AUTH] Team or member not found")
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn put_update_member_role(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path((team_id, user_id)): Path<(String, String)>,
|
||||
Json(payload): Json<UpdateMemberRoleRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
let state_clone = state.clone();
|
||||
let is_admin = crate::permissions_guard(headers.clone(), axum::Extension(state_clone.clone()), vec![PermissionsEnum::ManageAllTeams]).await.is_ok();
|
||||
|
||||
let auth = permissions_guard(headers, axum::Extension(state.clone()), vec![]).await;
|
||||
let (claims, state) = match auth {
|
||||
Ok((c, s)) => (c, s),
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
let repo = TeamsRepository::new(&state);
|
||||
let thing_id = imphnen_utils::make_thing_from_enum(imphnen_libs::ResourceEnum::Teams, &team_id);
|
||||
let team = match repo.query_team_by_id(&thing_id).await {
|
||||
Ok(t) => t,
|
||||
Err(_) => return crate::common_response(axum::http::StatusCode::NOT_FOUND, "Team not found"),
|
||||
};
|
||||
|
||||
if !is_admin {
|
||||
// Only leader can update roles
|
||||
if team.leader_id.id.to_raw() != claims.user_id {
|
||||
return crate::common_response(axum::http::StatusCode::FORBIDDEN, "Only team leader can update member roles");
|
||||
}
|
||||
}
|
||||
|
||||
let user_thing = imphnen_utils::make_thing_from_enum(imphnen_libs::ResourceEnum::Users, &user_id);
|
||||
match repo.query_update_team_member_role(&thing_id, &user_thing, &payload.role).await {
|
||||
Ok(_) => crate::success_response(crate::ResponseSuccessDto {
|
||||
data: format!("Member role updated to: {}", payload.role)
|
||||
}),
|
||||
Err(e) => crate::common_response(axum::http::StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/delete/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Delete team", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn delete_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::delete_team(&state, claims, id)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/{id}/invite",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
request_body = TeamInviteRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Invite team members", body = ResponseSuccessDto<serde_json::Value>)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn post_invite_team_members(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(team_id): Path<String>,
|
||||
Json(payload): Json<TeamInviteRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::invite_team_members(&state, claims, team_id, payload)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/accept/{token}",
|
||||
params(
|
||||
("token" = String, Path, description = "Invitation token")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Accept team invitation", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn post_accept_invitation(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(token): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
let accept_dto = TeamAcceptInvitationRequestDto { token };
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::accept_invitation(&state, claims, accept_dto)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/teams/search",
|
||||
params(
|
||||
("query" = Option<String>, Query, description = "Search query"),
|
||||
("open" = Option<bool>, Query, description = "Filter by open teams"),
|
||||
("skills" = Option<Vec<String>>, Query, description = "Filter by required skills"),
|
||||
("location" = Option<String>, Query, description = "Filter by location"),
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Search teams", body = ResponseListSuccessDto<Vec<PublicTeamsListItemDto>>)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn get_public_team_search(
|
||||
Extension(state): Extension<AppState>,
|
||||
axum::extract::Query(search_params): axum::extract::Query<TeamsSearchQueryDto>,
|
||||
) -> impl IntoResponse {
|
||||
TeamsService::search_teams(&state, search_params).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/{id}/members",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get team members", body = ResponseSuccessDto<Vec<TeamMemberDto>>)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn get_team_members(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::get_team_members(&state, claims, id)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/{id}/leave",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Leave specific team", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn post_leave_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::leave_team(&state, claims, id)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/leave-me",
|
||||
responses(
|
||||
(status = 200, description = "Leave current team", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn post_leave_current_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), |claims, state| TeamsService::leave_current_team(&state, claims)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/me",
|
||||
responses(
|
||||
(status = 200, description = "[AUTH] Get my team", body = ResponseSuccessDto<PublicTeamsDetailItemDto>),
|
||||
(status = 401, description = "[AUTH] Unauthorized"),
|
||||
(status = 404, description = "[AUTH] User is not a member of any team")
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn get_my_team(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), |claims, state| TeamsService::get_my_team(&state, claims)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/{id}/invitations",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[AUTH] Get team invitations", body = ResponseSuccessDto<Vec<TeamInvitationListDto>>),
|
||||
(status = 401, description = "[AUTH] Unauthorized"),
|
||||
(status = 403, description = "[AUTH] Only team leader can view invitations"),
|
||||
(status = 404, description = "[AUTH] Team not found")
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn get_team_invitations(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(team_id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::get_team_invitations(&state, claims, team_id)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/invitations/delete/{token}",
|
||||
params(
|
||||
("token" = String, Path, description = "Invitation token")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[AUTH] Invitation cancelled", body = ResponseSuccessDto<String>),
|
||||
(status = 401, description = "[AUTH] Unauthorized"),
|
||||
(status = 403, description = "[AUTH] Only team leader can cancel invitations"),
|
||||
(status = 404, description = "[AUTH] Invitation not found")
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn delete_invitation(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(token): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), move |claims, state| TeamsService::cancel_invitation(&state, claims, token)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/me/invitations",
|
||||
responses(
|
||||
(status = 200, description = "[AUTH] Get my pending invitations", body = ResponseSuccessDto<Vec<MyInvitationDto>>),
|
||||
(status = 401, description = "[AUTH] Unauthorized")
|
||||
),
|
||||
tag = "Teams"
|
||||
)]
|
||||
pub async fn get_my_invitations(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
authenticated(headers, Extension(state), |claims, state| TeamsService::get_my_invitations(&state, claims)).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/admin",
|
||||
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 admin team list", body = ResponseListSuccessDto<Vec<AdminTeamsListItemDto>>)
|
||||
),
|
||||
tag = "Teams - Admin"
|
||||
)]
|
||||
pub async fn get_admin_team_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
axum::extract::Query(meta): axum::extract::Query<MetaRequestDto>,
|
||||
) -> Response {
|
||||
let state = state;
|
||||
with_perms(headers, axum::Extension(state), vec![PermissionsEnum::ReadListTeams], move |_claims, state| {
|
||||
TeamsService::get_admin_team_list(&state, meta)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/admin/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get admin team by ID", body = ResponseSuccessDto<AdminTeamsDetailItemDto>)
|
||||
),
|
||||
tag = "Teams - Admin"
|
||||
)]
|
||||
pub async fn get_admin_team_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
let state = state;
|
||||
with_perms(headers, axum::Extension(state), vec![PermissionsEnum::ReadDetailTeams], move |_claims, state| {
|
||||
TeamsService::get_admin_team_by_id(&state, id)
|
||||
}).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/teams/admin/{id}/members",
|
||||
params(
|
||||
("id" = String, Path, description = "Team ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Get admin team members", body = ResponseSuccessDto<Vec<TeamMemberDto>>)
|
||||
),
|
||||
tag = "Teams - Admin"
|
||||
)]
|
||||
pub async fn get_admin_team_members(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> Response {
|
||||
let state = state;
|
||||
with_perms(headers, axum::Extension(state), vec![PermissionsEnum::ReadDetailTeams], move |_claims, state| {
|
||||
TeamsService::get_admin_team_members(&state, id)
|
||||
}).await
|
||||
}
|
||||
|
||||
pub fn teams_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(get_team_list))
|
||||
.route("/detail/{id}", axum::routing::get(get_team_by_id))
|
||||
.route("/create", axum::routing::post(post_create_team))
|
||||
.route("/update/{id}", axum::routing::put(put_update_team))
|
||||
.route("/delete/{id}", axum::routing::delete(delete_team))
|
||||
.route("/{id}/invite", axum::routing::post(post_invite_team_members))
|
||||
.route("/accept/{token}", axum::routing::post(post_accept_invitation))
|
||||
.route("/search", axum::routing::get(get_public_team_search))
|
||||
.route("/{id}/members", axum::routing::get(get_team_members))
|
||||
.route("/{id}/members/create", axum::routing::post(post_add_team_member))
|
||||
.route("/{id}/members/delete/{user_id}", axum::routing::delete(delete_remove_team_member))
|
||||
.route("/{id}/members/update/{user_id}/role", axum::routing::put(put_update_member_role))
|
||||
.route("/{id}/invitations", axum::routing::get(get_team_invitations))
|
||||
.route("/invitations/delete/{token}", axum::routing::delete(delete_invitation))
|
||||
.route("/{id}/leave", axum::routing::post(post_leave_team))
|
||||
.route("/leave-me", axum::routing::post(post_leave_current_team))
|
||||
.route("/me", axum::routing::get(get_my_team))
|
||||
.route("/me/invitations", axum::routing::get(get_my_invitations))
|
||||
}
|
||||
@@ -1,529 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
use std::borrow::Cow;
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
|
||||
// Custom validator for Vec<String> of emails. We use a custom validator because
|
||||
// the `each = true` attribute is not supported by the project's validator
|
||||
// crate version. This keeps validation at the DTO level as required.
|
||||
lazy_static! {
|
||||
static ref EMAIL_RE: Regex = Regex::new(r"^[^@\s]+@[^@\s]+\.[^@\s]+$").unwrap();
|
||||
}
|
||||
|
||||
fn validate_member_emails(emails: &Vec<String>) -> Result<(), ValidationError> {
|
||||
for email in emails {
|
||||
if !EMAIL_RE.is_match(email) {
|
||||
let mut err = ValidationError::new("invalid_email");
|
||||
err.message = Some(Cow::from("Invalid email"));
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
use imphnen_entities::users::UsersDetailQueryDto;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct TeamsCreateRequestDto {
|
||||
#[validate(length(min = 3, max = 100, message = "Team name must be between 3 and 100 characters"))]
|
||||
pub name: String,
|
||||
|
||||
#[validate(length(max = 500, message = "Description cannot exceed 500 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_open: Option<bool>,
|
||||
|
||||
#[validate(range(min = 2, max = 50, message = "Max members must be between 2 and 50"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_members: Option<i32>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
|
||||
#[validate(length(max = 100, message = "Location cannot exceed 100 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub location: Option<String>,
|
||||
|
||||
#[validate(url(message = "Invalid avatar URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
|
||||
#[validate(url(message = "Invalid website URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub website_url: Option<String>,
|
||||
|
||||
#[validate(url(message = "Invalid GitHub URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
|
||||
#[serde(default)]
|
||||
#[validate(custom(function = "validate_member_emails", message = "Invalid email in member_emails"))]
|
||||
pub member_emails: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct TeamsUpdateRequestDto {
|
||||
#[validate(length(min = 3, max = 100, message = "Team name must be between 3 and 100 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
|
||||
#[validate(length(max = 500, message = "Description cannot exceed 500 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_open: Option<bool>,
|
||||
|
||||
#[validate(range(min = 2, max = 50, message = "Max members must be between 2 and 50"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_members: Option<i32>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
|
||||
#[validate(length(max = 100, message = "Location cannot exceed 100 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub location: Option<String>,
|
||||
|
||||
#[validate(url(message = "Invalid avatar URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
|
||||
#[validate(url(message = "Invalid website URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub website_url: Option<String>,
|
||||
|
||||
#[validate(url(message = "Invalid GitHub URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct TeamInviteRequestDto {
|
||||
#[validate(length(min = 1, message = "Member emails cannot be empty"))]
|
||||
#[validate(custom(function = "validate_member_emails", message = "Invalid email in member_emails"))]
|
||||
pub member_emails: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TeamAcceptInvitationRequestDto {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TeamsDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader: TeamMemberDto,
|
||||
pub is_open: bool,
|
||||
pub max_members: Option<i32>,
|
||||
pub current_member_count: i32,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub members: Option<Vec<TeamMemberDto>>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MemberTeamsDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader: TeamMemberDto,
|
||||
pub is_open: bool,
|
||||
pub max_members: Option<i32>,
|
||||
pub current_member_count: i32,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub members: Vec<TeamMemberDto>, // Always include members for authenticated users
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TeamsListItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader: TeamMemberDto,
|
||||
pub is_open: bool,
|
||||
pub current_member_count: i32,
|
||||
pub max_members: Option<i32>,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct PublicTeamsListItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub is_open: bool,
|
||||
pub current_member_count: i32,
|
||||
pub max_members: Option<i32>,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct PublicTeamsDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub is_open: bool,
|
||||
pub max_members: Option<i32>,
|
||||
pub current_member_count: i32,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TeamMemberDto {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub fullname: String,
|
||||
pub email: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub role: String,
|
||||
pub skills: Option<Vec<String>>,
|
||||
pub joined_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TeamInvitationDto {
|
||||
pub id: String,
|
||||
pub team_id: String,
|
||||
pub team_name: String,
|
||||
pub email: String,
|
||||
pub inviter_name: String,
|
||||
pub status: String,
|
||||
pub expires_at: String,
|
||||
pub invited_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TeamsDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader_id: Thing,
|
||||
pub is_open: bool,
|
||||
pub max_members: Option<i32>,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TeamsListQueryDto {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader_id: Thing,
|
||||
pub leader: Option<UsersDetailQueryDto>,
|
||||
pub is_open: bool,
|
||||
pub max_members: Option<i32>,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TeamMembersQueryDto {
|
||||
pub id: Thing,
|
||||
pub team_id: Thing,
|
||||
pub user_id: Thing,
|
||||
pub role: String,
|
||||
pub joined_at: String,
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TeamInvitationsQueryDto {
|
||||
pub id: Thing,
|
||||
pub team_id: Thing,
|
||||
pub email: String,
|
||||
pub inviter_id: Thing,
|
||||
pub invite_code: String,
|
||||
pub expires_at: String,
|
||||
pub status: String,
|
||||
pub invited_at: String,
|
||||
pub accepted_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TeamsSearchQueryDto {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub query: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub open: Option<bool>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub skills: Option<Vec<String>>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub location: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub page: Option<i64>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub per_page: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AdminTeamsListItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader: TeamMemberDto,
|
||||
pub is_open: bool,
|
||||
pub current_member_count: i32,
|
||||
pub max_members: Option<i32>,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AdminTeamsDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader: TeamMemberDto,
|
||||
pub is_open: bool,
|
||||
pub max_members: Option<i32>,
|
||||
pub current_member_count: i32,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub members: Vec<TeamMemberDto>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl TeamsDetailQueryDto {
|
||||
pub fn into_detail_dto(self) -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl TeamsListItemDto {
|
||||
pub fn into_list_item_dto(self) -> Self {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn into_admin_list_dto(self) -> AdminTeamsListItemDto {
|
||||
AdminTeamsListItemDto {
|
||||
id: self.id,
|
||||
name: self.name,
|
||||
description: self.description,
|
||||
leader: self.leader,
|
||||
is_open: self.is_open,
|
||||
current_member_count: self.current_member_count,
|
||||
max_members: self.max_members,
|
||||
skills_required: self.skills_required,
|
||||
location: self.location,
|
||||
avatar: self.avatar,
|
||||
website_url: None,
|
||||
github_url: None,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
created_at: self.created_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TeamsListQueryDto {
|
||||
pub fn into_list_item_dto(self) -> TeamsListItemDto {
|
||||
let leader_dto = if let Some(leader_user) = self.leader {
|
||||
TeamMemberDto {
|
||||
id: String::new(),
|
||||
user_id: leader_user.id.id.to_raw(),
|
||||
fullname: leader_user.fullname,
|
||||
email: Some(leader_user.email),
|
||||
avatar: leader_user.avatar,
|
||||
role: "leader".to_string(),
|
||||
skills: leader_user.skills,
|
||||
joined_at: self.created_at.clone(),
|
||||
}
|
||||
} else {
|
||||
TeamMemberDto {
|
||||
id: String::new(),
|
||||
user_id: self.leader_id.id.to_raw(),
|
||||
fullname: String::new(),
|
||||
email: None,
|
||||
avatar: None,
|
||||
role: "leader".to_string(),
|
||||
skills: None,
|
||||
joined_at: self.created_at.clone(),
|
||||
}
|
||||
};
|
||||
|
||||
TeamsListItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
name: self.name,
|
||||
description: self.description,
|
||||
leader: leader_dto,
|
||||
is_open: self.is_open,
|
||||
current_member_count: 1,
|
||||
max_members: self.max_members,
|
||||
skills_required: self.skills_required,
|
||||
location: self.location,
|
||||
avatar: self.avatar,
|
||||
created_at: self.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_admin_list_dto(self) -> AdminTeamsListItemDto {
|
||||
AdminTeamsListItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
name: self.name,
|
||||
description: self.description,
|
||||
leader: TeamMemberDto {
|
||||
id: String::new(),
|
||||
user_id: self.leader_id.id.to_raw(),
|
||||
fullname: String::new(),
|
||||
email: None,
|
||||
avatar: None,
|
||||
role: "leader".to_string(),
|
||||
skills: None,
|
||||
joined_at: self.created_at.clone(),
|
||||
},
|
||||
is_open: self.is_open,
|
||||
current_member_count: 1, // Placeholder; adjust based on actual member count
|
||||
max_members: self.max_members,
|
||||
skills_required: self.skills_required,
|
||||
location: self.location,
|
||||
avatar: self.avatar,
|
||||
website_url: None,
|
||||
github_url: None,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
created_at: self.created_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TeamsDetailQueryDto {
|
||||
pub fn into_admin_detail_dto(self, members: Vec<TeamMemberDto>) -> AdminTeamsDetailItemDto {
|
||||
AdminTeamsDetailItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
name: self.name,
|
||||
description: self.description,
|
||||
leader: TeamMemberDto {
|
||||
id: String::new(),
|
||||
user_id: self.leader_id.id.to_raw(),
|
||||
fullname: String::new(),
|
||||
email: None,
|
||||
avatar: None,
|
||||
role: "leader".to_string(),
|
||||
skills: None,
|
||||
joined_at: self.created_at.clone(),
|
||||
},
|
||||
is_open: self.is_open,
|
||||
current_member_count: members.len() as i32 + 1,
|
||||
max_members: self.max_members,
|
||||
skills_required: self.skills_required,
|
||||
location: self.location,
|
||||
avatar: self.avatar,
|
||||
website_url: self.website_url,
|
||||
github_url: self.github_url,
|
||||
members,
|
||||
is_active: self.is_active,
|
||||
is_deleted: self.is_deleted,
|
||||
created_at: self.created_at,
|
||||
updated_at: self.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Additional DTOs for Team Member Management
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AddTeamMemberRequestDto {
|
||||
#[validate(length(min = 1, message = "User ID is required"))]
|
||||
pub user_id: String,
|
||||
|
||||
#[validate(length(max = 50, message = "Role cannot exceed 50 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub role: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct UpdateMemberRoleRequestDto {
|
||||
#[validate(length(min = 1, max = 50, message = "Role must be between 1 and 50 characters"))]
|
||||
pub role: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct TeamInvitationListDto {
|
||||
pub id: String,
|
||||
pub team_id: String,
|
||||
pub team_name: String,
|
||||
pub email: String,
|
||||
pub inviter_id: String,
|
||||
pub inviter_name: String,
|
||||
pub status: String,
|
||||
pub invite_code: String,
|
||||
pub expires_at: String,
|
||||
pub invited_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct MyInvitationDto {
|
||||
pub id: String,
|
||||
pub team_id: String,
|
||||
pub team_name: String,
|
||||
pub team_description: Option<String>,
|
||||
pub team_avatar: Option<String>,
|
||||
pub inviter_name: String,
|
||||
pub invite_code: String,
|
||||
pub status: String,
|
||||
pub expires_at: String,
|
||||
pub invited_at: String,
|
||||
}
|
||||
|
||||
// (previous custom validator removed; using validator::email(each = true) attribute)
|
||||
|
||||
@@ -1,532 +0,0 @@
|
||||
use super::{
|
||||
TeamsDetailQueryDto, TeamsListQueryDto, TeamsListItemDto, TeamsSchema,
|
||||
TeamMembersSchema, TeamInvitationsSchema, TeamMembersQueryDto, TeamInvitationsQueryDto,
|
||||
TeamsSearchQueryDto
|
||||
};
|
||||
use imphnen_libs::{
|
||||
AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto
|
||||
};
|
||||
use imphnen_utils::{
|
||||
get_id, DetailQueryBuilder, QueryListBuilder, make_thing_from_enum,
|
||||
build_multi_thing_condition, execute_safe_update_query,
|
||||
};
|
||||
use surrealdb::sql::Thing;
|
||||
use anyhow::{Result, bail};
|
||||
use serde_json;
|
||||
use std::time::Instant;
|
||||
|
||||
pub struct TeamsRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> TeamsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_team_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<TeamsListItemDto>>> {
|
||||
let now = Instant::now();
|
||||
let result: ResponseListSuccessDto<Vec<TeamsListQueryDto>> =
|
||||
QueryListBuilder::new(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Teams.to_string(),
|
||||
&meta,
|
||||
)
|
||||
.with_condition("is_deleted = false AND is_active = true")
|
||||
.search_field("name")
|
||||
.select_fields(vec!["*"])
|
||||
.fetch_fields(vec![])
|
||||
.build()
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_team_list' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let data = result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|dto| dto.into_list_item_dto())
|
||||
.collect();
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_team_by_id(&self, id: &Thing) -> Result<TeamsDetailQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Teams.to_string())
|
||||
.with_id(id.id.to_raw())
|
||||
.with_select_fields(vec!["*"]);
|
||||
let sql = builder.build();
|
||||
let result: Option<TeamsDetailQueryDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_team_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let Some(team) = result else {
|
||||
bail!("Team not found");
|
||||
};
|
||||
if team.is_deleted {
|
||||
bail!("Team not found");
|
||||
}
|
||||
Ok(team)
|
||||
}
|
||||
|
||||
pub async fn query_create_team(&self, data: TeamsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<TeamsSchema> = db
|
||||
.create(ResourceEnum::Teams.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_team' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(saved) => {
|
||||
// Return the created team id as part of the message so callers can parse it in tests
|
||||
let id = saved.id.id.to_raw();
|
||||
Ok(format!("Success create team {}", id))
|
||||
}
|
||||
None => bail!("Failed to create team"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_update_team(&self, data: TeamsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(&data.id)?;
|
||||
let existing = self.query_team_by_id(&data.id).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Team already deleted");
|
||||
}
|
||||
let merged = TeamsSchema {
|
||||
created_at: existing.created_at,
|
||||
..data.clone()
|
||||
};
|
||||
let record: Option<TeamsSchema> = db.update(record_key).merge(merged).await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_team' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success update team".into()),
|
||||
None => bail!("Failed to update team"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_team(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let team = self.query_team_by_id(&make_thing_from_enum(ResourceEnum::Teams, &id)).await?;
|
||||
if team.is_deleted {
|
||||
bail!("Team not found");
|
||||
}
|
||||
let record_key = get_id(&team.id)?;
|
||||
let record: Option<TeamsSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_team' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success delete team".into()),
|
||||
None => bail!("Failed to delete team"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_add_team_member(&self, data: TeamMembersSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<TeamMembersSchema> = db
|
||||
.create(ResourceEnum::TeamMembers.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_add_team_member' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(saved_member) => {
|
||||
println!("Member saved with ID: {:?}", saved_member.id);
|
||||
Ok("Success add team member".into())
|
||||
},
|
||||
None => bail!("Failed to add team member"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_team_members(&self, team_id: &Thing) -> Result<Vec<TeamMembersQueryDto>> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::TeamMembers.to_string())
|
||||
.with_thing_equals("team_id", team_id)
|
||||
.with_condition("is_active = true")
|
||||
.with_select_fields(vec!["*"]);
|
||||
|
||||
let sql = builder.build();
|
||||
let mut result = db.query(sql).await?;
|
||||
|
||||
let members: Vec<TeamMembersQueryDto> = match result.take(0) {
|
||||
Ok(members) => members,
|
||||
Err(e) => {
|
||||
println!("Error getting team members: {:?}", e);
|
||||
vec![]
|
||||
}
|
||||
};
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_team_members' returned {} members", members.len());
|
||||
println!("Query 'query_team_members' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(members)
|
||||
}
|
||||
|
||||
pub async fn query_teams_by_user(&self, user_id: &Thing) -> Result<Vec<TeamsDetailQueryDto>> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let sql = format!(
|
||||
"SELECT team.* FROM {} membership
|
||||
INNER JOIN {} team ON membership.team_id = team.id
|
||||
WHERE membership.user_id = $user_id
|
||||
AND membership.is_active = true
|
||||
AND team.is_deleted = false
|
||||
AND team.is_active = true",
|
||||
ResourceEnum::TeamMembers,
|
||||
ResourceEnum::Teams
|
||||
);
|
||||
let mut result = db.query(sql).bind(("user_id", user_id.id.to_raw())).await?;
|
||||
let teams: Vec<TeamsDetailQueryDto> = result.take(0)?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_teams' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(teams)
|
||||
}
|
||||
|
||||
pub async fn query_is_team_member(&self, team_id: &Thing, user_id: &Thing) -> Result<bool> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
// Use direct SQL query for more control over the team member check
|
||||
let sql = format!(
|
||||
"SELECT COUNT() AS count FROM {}
|
||||
WHERE team_id = $team_id
|
||||
AND user_id = $user_id
|
||||
AND is_active = true",
|
||||
ResourceEnum::TeamMembers
|
||||
);
|
||||
|
||||
let mut result = db.query(sql)
|
||||
.bind(("team_id", team_id.id.to_raw()))
|
||||
.bind(("user_id", user_id.id.to_raw()))
|
||||
.await?;
|
||||
|
||||
// Use a simpler approach to get the count
|
||||
let count = match result.take(0) {
|
||||
Ok(Some(surrealdb::sql::Value::Number(num))) => num.to_int(),
|
||||
_ => 0,
|
||||
};
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_is_team_member' found {} matching members", count);
|
||||
println!("Query 'query_is_team_member' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(count > 0)
|
||||
}
|
||||
|
||||
pub async fn query_create_invitation(&self, data: TeamInvitationsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<TeamInvitationsSchema> = db
|
||||
.create(ResourceEnum::TeamInvitations.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_invitation' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success create invitation".into()),
|
||||
None => bail!("Failed to create invitation"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_invitation_by_token(&self, token: &str) -> Result<TeamInvitationsQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let sql = format!(
|
||||
"SELECT * FROM {} WHERE invite_code = $invite_code AND status = 'pending' LIMIT 1",
|
||||
ResourceEnum::TeamInvitations
|
||||
);
|
||||
let mut result = db.query(sql).bind(("invite_code", token.to_string())).await?;
|
||||
let invitation: Option<TeamInvitationsQueryDto> = result.take(0)?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_invitation_by_token' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
invitation.ok_or_else(|| anyhow::anyhow!("Invitation not found"))
|
||||
}
|
||||
|
||||
pub async fn query_update_invitation(&self, data: TeamInvitationsSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(&data.id)?;
|
||||
let record: Option<TeamInvitationsSchema> = db.update(record_key).merge(data).await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_invitation' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success update invitation".into()),
|
||||
None => bail!("Failed to update invitation"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_search_teams(
|
||||
&self,
|
||||
search_params: TeamsSearchQueryDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<TeamsListItemDto>>> {
|
||||
let now = Instant::now();
|
||||
let page = search_params.page.unwrap_or(1);
|
||||
let per_page = search_params.per_page.unwrap_or(10);
|
||||
|
||||
let mut conditions = vec!["is_deleted = false".to_string(), "is_active = true".to_string()];
|
||||
|
||||
if let Some(open) = search_params.open
|
||||
&& open {
|
||||
conditions.push("is_open = true".to_string());
|
||||
}
|
||||
|
||||
if let Some(location) = &search_params.location {
|
||||
conditions.push(format!("location CONTAINS '{}'", location));
|
||||
}
|
||||
|
||||
let mut query_conditions = conditions.join(" AND ");
|
||||
|
||||
if let Some(query) = &search_params.query {
|
||||
query_conditions = format!("({}) AND (name CONTAINS '{}' OR description CONTAINS '{}')", query_conditions, query, query);
|
||||
}
|
||||
|
||||
if let Some(skills) = &search_params.skills {
|
||||
for skill in skills.iter() {
|
||||
query_conditions = format!("{} AND skills_required CONTAINS '{}'", query_conditions, skill);
|
||||
}
|
||||
}
|
||||
|
||||
let meta = MetaRequestDto {
|
||||
page: Some(page.try_into().unwrap()),
|
||||
per_page: Some(per_page.try_into().unwrap()),
|
||||
search: None, // Don't use built-in search since we're doing custom filtering
|
||||
sort_by: Some("created_at".to_string()),
|
||||
order: Some("DESC".to_string()),
|
||||
filter: None,
|
||||
filter_by: None,
|
||||
};
|
||||
|
||||
let result: ResponseListSuccessDto<Vec<TeamsListQueryDto>> = QueryListBuilder::new(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Teams.to_string(),
|
||||
&meta,
|
||||
)
|
||||
.with_condition(&query_conditions)
|
||||
.select_fields(vec!["*"])
|
||||
.build()
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_search_teams' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let data = result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|dto| dto.into_list_item_dto())
|
||||
.collect();
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_remove_team_member(&self, team_id: &Thing, user_id: &Thing) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let conditions = build_multi_thing_condition(&[("team_id", team_id), ("user_id", user_id)]);
|
||||
let sql = format!(
|
||||
"UPDATE {} SET is_active = false WHERE {}",
|
||||
ResourceEnum::TeamMembers,
|
||||
conditions
|
||||
);
|
||||
|
||||
execute_safe_update_query(db, sql).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_remove_team_member' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success remove team member".into())
|
||||
}
|
||||
|
||||
pub async fn query_update_team_member_role(&self, team_id: &Thing, user_id: &Thing, role: &str) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let conditions = build_multi_thing_condition(&[("team_id", team_id), ("user_id", user_id)]);
|
||||
let sql = format!(
|
||||
"UPDATE {} SET role = '{}' WHERE {} AND is_active = true",
|
||||
ResourceEnum::TeamMembers,
|
||||
role,
|
||||
conditions
|
||||
);
|
||||
|
||||
execute_safe_update_query(db, sql).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_team_member_role' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success update team member role".into())
|
||||
}
|
||||
|
||||
pub async fn query_team_invitations(&self, team_id: &Thing) -> Result<Vec<TeamInvitationsQueryDto>> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let team_id_clone = team_id.clone();
|
||||
|
||||
let sql = format!(
|
||||
"SELECT * FROM {} WHERE team_id = $team_id AND status = 'pending' ORDER BY invited_at DESC",
|
||||
ResourceEnum::TeamInvitations
|
||||
);
|
||||
|
||||
let mut result = db.query(&sql).bind(("team_id", team_id_clone)).await?;
|
||||
let invitations: Vec<TeamInvitationsQueryDto> = result.take(0)?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_team_invitations' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(invitations)
|
||||
}
|
||||
|
||||
pub async fn query_user_invitations(&self, email: &str) -> Result<Vec<TeamInvitationsQueryDto>> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let sql = format!(
|
||||
"SELECT * FROM {} WHERE email = '{}' AND status = 'pending' ORDER BY invited_at DESC",
|
||||
ResourceEnum::TeamInvitations,
|
||||
email
|
||||
);
|
||||
|
||||
let mut result = db.query(&sql).await?;
|
||||
let invitations: Vec<TeamInvitationsQueryDto> = result.take(0)?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_invitations' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(invitations)
|
||||
}
|
||||
|
||||
pub async fn query_delete_invitation(&self, token: &str) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let sql = format!(
|
||||
"UPDATE {} SET status = 'cancelled' WHERE invite_code = '{}'",
|
||||
ResourceEnum::TeamInvitations,
|
||||
token
|
||||
);
|
||||
|
||||
execute_safe_update_query(db, sql).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_invitation' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Invitation cancelled successfully".into())
|
||||
}
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
use super::{TeamsCreateRequestDto, TeamsUpdateRequestDto};
|
||||
use imphnen_libs::ResourceEnum;
|
||||
use imphnen_utils::{get_iso_date, make_thing_from_enum};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
use chrono::{DateTime, Utc, Duration};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TeamsSchema {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub leader_id: Thing,
|
||||
pub is_open: bool,
|
||||
pub max_members: Option<i32>,
|
||||
pub skills_required: Option<Vec<String>>,
|
||||
pub location: Option<String>,
|
||||
pub avatar: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TeamMembersSchema {
|
||||
pub id: Thing,
|
||||
pub team_id: Thing,
|
||||
pub user_id: Thing,
|
||||
pub role: String,
|
||||
pub joined_at: String,
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TeamInvitationsSchema {
|
||||
pub id: Thing,
|
||||
pub team_id: Thing,
|
||||
pub email: String,
|
||||
pub inviter_id: Thing,
|
||||
pub invite_code: String, // Renamed from 'token' to avoid SurrealDB protected field conflict
|
||||
pub expires_at: DateTime<Utc>,
|
||||
pub status: String,
|
||||
pub invited_at: String,
|
||||
pub accepted_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for TeamsSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::Teams,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
name: String::new(),
|
||||
description: None,
|
||||
leader_id: make_thing_from_enum(
|
||||
ResourceEnum::Users,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
is_open: false,
|
||||
max_members: None,
|
||||
skills_required: None,
|
||||
location: None,
|
||||
avatar: None,
|
||||
website_url: None,
|
||||
github_url: None,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TeamMembersSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::TeamMembers,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
team_id: make_thing_from_enum(
|
||||
ResourceEnum::Teams,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
user_id: make_thing_from_enum(
|
||||
ResourceEnum::Users,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
role: "member".to_string(),
|
||||
joined_at: get_iso_date(),
|
||||
is_active: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TeamInvitationsSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::TeamInvitations,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
team_id: make_thing_from_enum(
|
||||
ResourceEnum::Teams,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
email: String::new(),
|
||||
inviter_id: make_thing_from_enum(
|
||||
ResourceEnum::Users,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
invite_code: String::new(), // Renamed from 'token'
|
||||
expires_at: Utc::now() + Duration::hours(72),
|
||||
status: "pending".to_string(),
|
||||
invited_at: get_iso_date(),
|
||||
accepted_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TeamsSchema {
|
||||
pub fn create(dto: TeamsCreateRequestDto, leader_id: String) -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::Teams,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
name: dto.name,
|
||||
description: dto.description,
|
||||
leader_id: make_thing_from_enum(ResourceEnum::Users, &leader_id),
|
||||
is_open: dto.is_open.unwrap_or(false),
|
||||
max_members: dto.max_members,
|
||||
skills_required: dto.skills_required,
|
||||
location: dto.location,
|
||||
avatar: dto.avatar,
|
||||
website_url: dto.website_url,
|
||||
github_url: dto.github_url,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(self, dto: TeamsUpdateRequestDto) -> Self {
|
||||
Self {
|
||||
name: dto.name.unwrap_or(self.name),
|
||||
description: dto.description.or(self.description),
|
||||
is_open: dto.is_open.unwrap_or(self.is_open),
|
||||
max_members: dto.max_members.or(self.max_members),
|
||||
skills_required: dto.skills_required.or(self.skills_required),
|
||||
location: dto.location.or(self.location),
|
||||
avatar: dto.avatar.or(self.avatar),
|
||||
website_url: dto.website_url.or(self.website_url),
|
||||
github_url: dto.github_url.or(self.github_url),
|
||||
updated_at: get_iso_date(),
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TeamMembersSchema {
|
||||
pub fn create(team_id: String, user_id: String, role: Option<String>) -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::TeamMembers,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
team_id: make_thing_from_enum(ResourceEnum::Teams, &team_id),
|
||||
user_id: make_thing_from_enum(ResourceEnum::Users, &user_id),
|
||||
role: role.unwrap_or("member".to_string()),
|
||||
joined_at: get_iso_date(),
|
||||
is_active: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TeamInvitationsSchema {
|
||||
pub fn create(team_id: String, email: String, inviter_id: String, invite_code: String) -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::TeamInvitations,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
team_id: make_thing_from_enum(ResourceEnum::Teams, &team_id),
|
||||
email,
|
||||
inviter_id: make_thing_from_enum(ResourceEnum::Users, &inviter_id),
|
||||
invite_code, // Renamed from 'token'
|
||||
expires_at: Utc::now() + Duration::hours(72),
|
||||
status: "pending".to_string(),
|
||||
invited_at: get_iso_date(),
|
||||
accepted_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn accept(mut self) -> Self {
|
||||
self.status = "accepted".to_string();
|
||||
self.accepted_at = Some(get_iso_date());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn is_expired(&self) -> bool {
|
||||
Utc::now() > self.expires_at
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,57 +1,57 @@
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
|
||||
pub mod users_controller;
|
||||
pub mod users_dto;
|
||||
pub mod users_repository;
|
||||
pub mod users_schema;
|
||||
pub mod users_service;
|
||||
|
||||
// Export only essential types and functions from each submodule
|
||||
pub use users_controller::{
|
||||
get_user_list,
|
||||
get_user_by_id,
|
||||
get_user_me,
|
||||
post_create_user,
|
||||
put_update_user,
|
||||
put_update_user_me,
|
||||
delete_user,
|
||||
patch_user_active_status,
|
||||
upload_file
|
||||
};
|
||||
|
||||
pub use users_dto::{
|
||||
UsersActiveInactiveRequestDto,
|
||||
UsersCreateRequestDto,
|
||||
UsersUpdateRequestDto,
|
||||
UsersSetNewPasswordRequestDto,
|
||||
UsersDetailItemDto,
|
||||
UsersListItemDto,
|
||||
UsersListQueryDto,
|
||||
};
|
||||
|
||||
pub use users_repository::UsersRepository;
|
||||
pub use users_schema::UsersSchema;
|
||||
|
||||
pub fn users_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_user_list))
|
||||
.route("/activate/{id}", put(patch_user_active_status))
|
||||
.route("/create", post(post_create_user))
|
||||
.route("/me", get(get_user_me))
|
||||
.route("/delete/{id}", delete(delete_user))
|
||||
.route("/detail/{id}", get(get_user_by_id))
|
||||
.route("/update/{id}", put(put_update_user))
|
||||
.route("/update/me", put(put_update_user_me))
|
||||
.route("/upload", post(upload_file))
|
||||
}
|
||||
|
||||
// Minimal admin router to satisfy test expectations at /v1/users/admin
|
||||
pub fn admin_users_router() -> Router {
|
||||
use users_controller as controller;
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(controller::get_user_list))
|
||||
.route("/detail/{id}", axum::routing::get(controller::get_user_by_id))
|
||||
}
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{delete, get, post, put},
|
||||
};
|
||||
|
||||
pub mod users_controller;
|
||||
pub mod users_dto;
|
||||
pub mod users_repository;
|
||||
pub mod users_schema;
|
||||
pub mod users_service;
|
||||
|
||||
// Export only essential types and functions from each submodule
|
||||
pub use users_controller::{
|
||||
get_user_list,
|
||||
get_user_by_id,
|
||||
get_user_me,
|
||||
post_create_user,
|
||||
put_update_user,
|
||||
put_update_user_me,
|
||||
delete_user,
|
||||
patch_user_active_status,
|
||||
upload_file
|
||||
};
|
||||
|
||||
pub use users_dto::{
|
||||
UsersActiveInactiveRequestDto,
|
||||
UsersCreateRequestDto,
|
||||
UsersUpdateRequestDto,
|
||||
UsersSetNewPasswordRequestDto,
|
||||
UsersDetailItemDto,
|
||||
UsersListItemDto,
|
||||
UsersListQueryDto,
|
||||
};
|
||||
|
||||
pub use users_repository::UsersRepository;
|
||||
pub use users_schema::UsersSchema;
|
||||
|
||||
pub fn users_router() -> Router {
|
||||
Router::new()
|
||||
.route("/", get(get_user_list))
|
||||
.route("/activate/{id}", put(patch_user_active_status))
|
||||
.route("/create", post(post_create_user))
|
||||
.route("/me", get(get_user_me))
|
||||
.route("/delete/{id}", delete(delete_user))
|
||||
.route("/detail/{id}", get(get_user_by_id))
|
||||
.route("/update/{id}", put(put_update_user))
|
||||
.route("/update/me", put(put_update_user_me))
|
||||
.route("/upload", post(upload_file))
|
||||
}
|
||||
|
||||
// Minimal admin router to satisfy test expectations at /v1/users/admin
|
||||
pub fn admin_users_router() -> Router {
|
||||
use users_controller as controller;
|
||||
Router::new()
|
||||
.route("/", axum::routing::get(controller::get_user_list))
|
||||
.route("/detail/{id}", axum::routing::get(controller::get_user_by_id))
|
||||
}
|
||||
|
||||
@@ -1,302 +1,302 @@
|
||||
use crate::{AppState, MetaRequestDto};
|
||||
use crate::{
|
||||
MessageResponseDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
UsersCreateRequestDto, UsersDetailItemDto, permissions_guard,
|
||||
};
|
||||
use axum::extract::{Path, Multipart};
|
||||
use axum::http::HeaderMap;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, Json};
|
||||
use utoipa::ToSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
UsersActiveInactiveRequestDto, UsersListItemDto, UsersUpdateRequestDto,
|
||||
};
|
||||
use crate::v1::users::users_service::{UsersServiceTrait, UsersService};
|
||||
|
||||
#[derive(Serialize, Deserialize, ToSchema)]
|
||||
#[schema(description = "File upload form data for multipart/form-data")]
|
||||
pub struct FileUploadSchema {
|
||||
/// Binary file data to upload
|
||||
#[schema(format = "binary")]
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user list", body = ResponseListSuccessDto<Vec<UsersListItemDto>>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
axum::extract::Query(meta): axum::extract::Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadListUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::get_user_list(&state, meta).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "User ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadDetailUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::get_user_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/me",
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(headers, Extension(state), vec![]).await {
|
||||
Ok((claims, state)) => UsersService::get_user_me(claims, &state).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/create",
|
||||
request_body = UsersCreateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Create new user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn post_create_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<UsersCreateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::CreateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::create_user(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "User ID")
|
||||
),
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Update user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::UpdateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::update_user(&state, id, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/update/me",
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[USER] Update current user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(headers.clone(), Extension(state), vec![]).await {
|
||||
Ok((claims, state)) => UsersService::update_user_me(claims, &state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/activate/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "User ID")
|
||||
),
|
||||
request_body = UsersActiveInactiveRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Set user active status", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn patch_user_active_status(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersActiveInactiveRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ActivateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::set_user_active_status(&state, id, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Soft delete user", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn delete_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::DeleteUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::delete_user(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/upload",
|
||||
request_body(
|
||||
content = FileUploadSchema,
|
||||
description = "Upload file with multipart form data. Only 'file' field is required - file type will be detected automatically from the uploaded file.",
|
||||
content_type = "multipart/form-data"
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Upload file successfully", body = ResponseSuccessDto<serde_json::Value>),
|
||||
(status = 400, description = "[USER] Bad request"),
|
||||
(status = 401, description = "[USER] Unauthorized"),
|
||||
(status = 500, description = "[USER] Internal server error")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn upload_file(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
multipart: Multipart,
|
||||
) -> impl IntoResponse {
|
||||
// Check authentication first
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![], // No specific permission needed, just authentication
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((claims, state)) => {
|
||||
// Extract user ID from user data
|
||||
let user_id = claims.user_id.clone(); // Use claims.user_id directly
|
||||
|
||||
// Process upload - don't use match here since it returns Response directly
|
||||
UsersService::upload_file(&state, user_id, multipart).await
|
||||
},
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
use crate::{AppState, MetaRequestDto};
|
||||
use crate::{
|
||||
MessageResponseDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
UsersCreateRequestDto, UsersDetailItemDto, permissions_guard,
|
||||
};
|
||||
use axum::extract::{Path, Multipart};
|
||||
use axum::http::HeaderMap;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, Json};
|
||||
use utoipa::ToSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
UsersActiveInactiveRequestDto, UsersListItemDto, UsersUpdateRequestDto,
|
||||
};
|
||||
use crate::v1::users::users_service::{UsersServiceTrait, UsersService};
|
||||
|
||||
#[derive(Serialize, Deserialize, ToSchema)]
|
||||
#[schema(description = "File upload form data for multipart/form-data")]
|
||||
pub struct FileUploadSchema {
|
||||
/// Binary file data to upload
|
||||
#[schema(format = "binary")]
|
||||
pub file: String,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
("per_page" = Option<i64>, Query, description = "Items per page"),
|
||||
("search" = Option<String>, Query, description = "Search keyword"),
|
||||
("sort_by" = Option<String>, Query, description = "Sort by field"),
|
||||
("order" = Option<String>, Query, description = "Order ASC or DESC"),
|
||||
("filter" = Option<String>, Query, description = "Filter value"),
|
||||
("filter_by" = Option<String>, Query, description = "Field to filter by"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user list", body = ResponseListSuccessDto<Vec<UsersListItemDto>>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
axum::extract::Query(meta): axum::extract::Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadListUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::get_user_list(&state, meta).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "User ID")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_by_id(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ReadDetailUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::get_user_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/me",
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(headers, Extension(state), vec![]).await {
|
||||
Ok((claims, state)) => UsersService::get_user_me(claims, &state).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/create",
|
||||
request_body = UsersCreateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Create new user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn post_create_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<UsersCreateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::CreateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::create_user(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/update/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "User ID")
|
||||
),
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Update user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::UpdateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::update_user(&state, id, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/update/me",
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[USER] Update current user", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn put_update_user_me(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(headers.clone(), Extension(state), vec![]).await {
|
||||
Ok((claims, state)) => UsersService::update_user_me(claims, &state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/activate/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "User ID")
|
||||
),
|
||||
request_body = UsersActiveInactiveRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Set user active status", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn patch_user_active_status(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(payload): Json<UsersActiveInactiveRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::ActivateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::set_user_active_status(&state, id, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "[ADMIN] Soft delete user", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn delete_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![PermissionsEnum::DeleteUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((_claims, state)) => UsersService::delete_user(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/upload",
|
||||
request_body(
|
||||
content = FileUploadSchema,
|
||||
description = "Upload file with multipart form data. Only 'file' field is required - file type will be detected automatically from the uploaded file.",
|
||||
content_type = "multipart/form-data"
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "[USER] Upload file successfully", body = ResponseSuccessDto<serde_json::Value>),
|
||||
(status = 400, description = "[USER] Bad request"),
|
||||
(status = 401, description = "[USER] Unauthorized"),
|
||||
(status = 500, description = "[USER] Internal server error")
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn upload_file(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
multipart: Multipart,
|
||||
) -> impl IntoResponse {
|
||||
// Check authentication first
|
||||
match permissions_guard(
|
||||
headers,
|
||||
Extension(state),
|
||||
vec![], // No specific permission needed, just authentication
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok((claims, state)) => {
|
||||
// Extract user ID from user data
|
||||
let user_id = claims.user_id.clone(); // Use claims.user_id directly
|
||||
|
||||
// Process upload - don't use match here since it returns Response directly
|
||||
UsersService::upload_file(&state, user_id, multipart).await
|
||||
},
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,315 +1,193 @@
|
||||
use imphnen_entities::{ExperienceDto, EducationDto, UsersDetailQueryDto, RolesDetailQueryDto, RolesDetailItemDto};
|
||||
use lazy_static::lazy_static;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
use crate::UsersSchema; // Import UsersSchema
|
||||
|
||||
lazy_static! {
|
||||
static ref PASSWORD_REGEX: regex::Regex =
|
||||
regex::Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersActiveInactiveRequestDto {
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersSetNewPasswordRequestDto {
|
||||
pub password: String,
|
||||
pub old_password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct UsersCreateRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(regex(
|
||||
path = "*PASSWORD_REGEX",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
pub fullname: String,
|
||||
|
||||
#[validate(length(
|
||||
min = 10,
|
||||
message = "Phone number at least have 10 character"
|
||||
))]
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub role_id: String,
|
||||
pub avatar: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct UsersUpdateRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub email: Option<String>,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub password: Option<String>,
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fullname: Option<String>,
|
||||
#[validate(length(min = 2, message = "Legal name at least have 2 character"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
#[validate(length(
|
||||
min = 10,
|
||||
message = "Phone number at least have 10 character"
|
||||
))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_number: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_for_verification: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_active: Option<bool>,
|
||||
#[validate(length(min = 1, message = "Gender is required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gender: Option<String>,
|
||||
#[validate(length(min = 1, message = "Birthdate is required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub birthdate: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub domicile: Option<String>,
|
||||
#[validate(length(min = 50, message = "Bio must be at least 50 characters"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bio: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_education: Option<String>,
|
||||
#[validate(url(message = "Invalid LinkedIn URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linkedin_url: Option<String>,
|
||||
#[validate(url(message = "Invalid GitHub URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
#[validate(url(message = "Invalid CV URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cv_url: Option<String>,
|
||||
#[validate(url(message = "Invalid portfolio URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub portfolio_url: Option<String>,
|
||||
#[validate(url(message = "Invalid website URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub website_url: Option<String>,
|
||||
#[validate(url(message = "Invalid Twitter URL"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub twitter_url: Option<String>,
|
||||
#[validate(length(min = 1, message = "Avatar is required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub role_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub location: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub skills: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub experience: Option<Vec<ExperienceDto>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub education: Option<Vec<EducationDto>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub career_status: Option<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 phone_number: String,
|
||||
pub phone_for_verification: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub gender: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
pub domicile: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub last_education: Option<String>,
|
||||
pub linkedin_url: Option<String>,
|
||||
pub github_url: Option<String>,
|
||||
pub cv_url: Option<String>,
|
||||
pub portfolio_url: Option<String>,
|
||||
pub website_url: Option<String>,
|
||||
pub twitter_url: Option<String>,
|
||||
pub location: Option<String>,
|
||||
pub skills: Option<Vec<String>>,
|
||||
pub experience: Option<Vec<ExperienceDto>>,
|
||||
pub education: Option<Vec<EducationDto>>,
|
||||
pub career_status: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl UsersDetailItemDto {
|
||||
pub fn from(dto: &UsersDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.id.to_raw(),
|
||||
role: RolesDetailItemDto::from(&dto.role),
|
||||
fullname: dto.fullname.clone(),
|
||||
legal_name: dto.legal_name.clone(),
|
||||
email: dto.email.clone(),
|
||||
avatar: dto.avatar.clone(),
|
||||
phone_number: dto.phone_number.clone(),
|
||||
phone_for_verification: dto.phone_for_verification.clone(),
|
||||
is_active: dto.is_active,
|
||||
gender: dto.gender.clone(),
|
||||
birthdate: dto.birthdate.clone(),
|
||||
domicile: dto.domicile.clone(),
|
||||
bio: dto.bio.clone(),
|
||||
last_education: dto.last_education.clone(),
|
||||
linkedin_url: dto.linkedin_url.clone(),
|
||||
github_url: dto.github_url.clone(),
|
||||
cv_url: dto.cv_url.clone(),
|
||||
portfolio_url: dto.portfolio_url.clone(),
|
||||
website_url: dto.website_url.clone(),
|
||||
twitter_url: dto.twitter_url.clone(),
|
||||
location: dto.location.clone(),
|
||||
skills: dto.skills.clone(),
|
||||
experience: dto.experience.clone(),
|
||||
education: dto.education.clone(),
|
||||
career_status: dto.career_status.clone(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_schema(schema: &UsersSchema) -> Self {
|
||||
Self {
|
||||
id: schema.id.id.to_raw(),
|
||||
role: RolesDetailItemDto::default(), // Placeholder, role needs to be fetched
|
||||
fullname: schema.fullname.clone(),
|
||||
legal_name: schema.legal_name.clone(),
|
||||
email: schema.email.clone(),
|
||||
avatar: schema.avatar.clone(),
|
||||
phone_number: schema.phone_number.clone(),
|
||||
phone_for_verification: schema.phone_for_verification.clone(),
|
||||
is_active: schema.is_active,
|
||||
gender: schema.gender.clone(),
|
||||
birthdate: schema.birthdate.clone(),
|
||||
domicile: schema.domicile.clone(),
|
||||
bio: schema.bio.clone(),
|
||||
last_education: schema.last_education.clone(),
|
||||
linkedin_url: schema.linkedin_url.clone(),
|
||||
github_url: schema.github_url.clone(),
|
||||
cv_url: schema.cv_url.clone(),
|
||||
portfolio_url: schema.portfolio_url.clone(),
|
||||
website_url: schema.website_url.clone(),
|
||||
twitter_url: schema.twitter_url.clone(),
|
||||
location: schema.location.clone(),
|
||||
skills: schema.skills.clone(),
|
||||
experience: schema.experience.clone(),
|
||||
education: schema.education.clone(),
|
||||
career_status: schema.career_status.clone(),
|
||||
created_at: schema.created_at.clone(),
|
||||
updated_at: schema.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersListItemDto {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersListQueryDto {
|
||||
pub id: Thing,
|
||||
pub role: RolesDetailQueryDto,
|
||||
pub fullname: String,
|
||||
pub email: String, // Corrected from pub pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl UsersListQueryDto {
|
||||
pub fn from(self) -> UsersListItemDto {
|
||||
UsersListItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
role: self.role.name,
|
||||
fullname: self.fullname,
|
||||
email: self.email,
|
||||
avatar: self.avatar,
|
||||
phone_number: self.phone_number,
|
||||
is_active: self.is_active,
|
||||
created_at: self.created_at,
|
||||
updated_at: self.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl From<&UsersDetailItemDto> for UsersDetailQueryDto {
|
||||
fn from(dto: &UsersDetailItemDto) -> Self {
|
||||
Self {
|
||||
id: crate::make_thing(&imphnen_libs::ResourceEnum::Users.to_string(), &dto.id),
|
||||
fullname: dto.fullname.clone(),
|
||||
legal_name: dto.legal_name.clone(),
|
||||
email: dto.email.clone(),
|
||||
avatar: dto.avatar.clone(),
|
||||
phone_number: dto.phone_number.clone(),
|
||||
phone_for_verification: dto.phone_for_verification.clone(),
|
||||
is_active: dto.is_active,
|
||||
is_deleted: false,
|
||||
gender: dto.gender.clone(),
|
||||
birthdate: dto.birthdate.clone(),
|
||||
domicile: dto.domicile.clone(),
|
||||
bio: dto.bio.clone(),
|
||||
last_education: dto.last_education.clone(),
|
||||
linkedin_url: dto.linkedin_url.clone(),
|
||||
github_url: dto.github_url.clone(),
|
||||
cv_url: dto.cv_url.clone(),
|
||||
portfolio_url: dto.portfolio_url.clone(),
|
||||
website_url: dto.website_url.clone(),
|
||||
twitter_url: dto.twitter_url.clone(),
|
||||
location: dto.location.clone(),
|
||||
skills: dto.skills.clone(),
|
||||
experience: dto.experience.clone(),
|
||||
education: dto.education.clone(),
|
||||
career_status: dto.career_status.clone(),
|
||||
password: String::new(),
|
||||
role: RolesDetailQueryDto::default(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
mentor_id: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UsersDetailItemDto {
|
||||
pub fn extract_permissions_from_user_role(&self) -> Vec<String> {
|
||||
self.role.permissions.iter().map(|p| p.name.clone()).collect()
|
||||
}
|
||||
use imphnen_entities::{UsersDetailQueryDto, RolesDetailQueryDto, RolesDetailItemDto, users::UserProfileExtensionDto};
|
||||
use lazy_static::lazy_static;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
use crate::UsersSchema; // Import UsersSchema
|
||||
|
||||
lazy_static! {
|
||||
static ref PASSWORD_REGEX: regex::Regex =
|
||||
regex::Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersActiveInactiveRequestDto {
|
||||
pub is_active: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersSetNewPasswordRequestDto {
|
||||
pub password: String,
|
||||
pub old_password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct UsersCreateRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(regex(
|
||||
path = "*PASSWORD_REGEX",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
pub fullname: String,
|
||||
|
||||
pub is_active: bool,
|
||||
pub role_id: String,
|
||||
pub avatar: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct UsersUpdateRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub email: Option<String>,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub password: Option<String>,
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub fullname: Option<String>,
|
||||
#[validate(length(min = 2, message = "Legal name at least have 2 character"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub is_active: Option<bool>,
|
||||
#[validate(length(min = 1, message = "Avatar is required"))]
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub role_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct UsersDetailItemDto {
|
||||
pub id: String,
|
||||
pub role: RolesDetailItemDto,
|
||||
pub fullname: String,
|
||||
pub legal_name: Option<String>,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl UsersDetailItemDto {
|
||||
pub fn from(dto: &UsersDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id.clone(),
|
||||
role: RolesDetailItemDto::from(&dto.role),
|
||||
fullname: dto.fullname.clone(),
|
||||
legal_name: dto.legal_name.clone(),
|
||||
email: dto.email.clone(),
|
||||
avatar: dto.avatar.clone(),
|
||||
is_active: dto.is_active,
|
||||
profile_extension: dto.profile_extension.clone(),
|
||||
created_at: dto.created_at.clone(),
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_schema(schema: &UsersSchema) -> Self {
|
||||
Self {
|
||||
id: schema.id.clone(),
|
||||
role: RolesDetailItemDto::default(), // Placeholder, role needs to be fetched
|
||||
fullname: schema.fullname.clone().unwrap_or_default(),
|
||||
legal_name: schema.legal_name.clone(),
|
||||
email: schema.email.clone().unwrap_or_default(),
|
||||
avatar: schema.avatar.clone(),
|
||||
is_active: schema.is_active,
|
||||
profile_extension: schema.profile_extension.clone(),
|
||||
created_at: schema.created_at.clone(),
|
||||
updated_at: schema.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersListItemDto {
|
||||
pub id: String,
|
||||
pub role: String,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersListQueryDto {
|
||||
pub id: String,
|
||||
pub role: RolesDetailQueryDto,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl UsersListQueryDto {
|
||||
pub fn from(self) -> UsersListItemDto {
|
||||
UsersListItemDto {
|
||||
id: self.id,
|
||||
role: self.role.name,
|
||||
fullname: self.fullname,
|
||||
email: self.email,
|
||||
avatar: self.avatar,
|
||||
is_active: self.is_active,
|
||||
created_at: self.created_at,
|
||||
updated_at: self.updated_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl From<&UsersDetailItemDto> for UsersDetailQueryDto {
|
||||
fn from(dto: &UsersDetailItemDto) -> Self {
|
||||
let mut s = UsersDetailQueryDto::default();
|
||||
s.id = dto.id.clone();
|
||||
s.fullname = dto.fullname.clone();
|
||||
s.legal_name = dto.legal_name.clone();
|
||||
s.email = dto.email.clone();
|
||||
s.avatar = dto.avatar.clone();
|
||||
s.is_active = dto.is_active;
|
||||
s.is_deleted = false;
|
||||
s.profile_extension = dto.profile_extension.clone();
|
||||
s.password = String::new();
|
||||
s.role = RolesDetailQueryDto::default();
|
||||
s.created_at = dto.created_at.clone();
|
||||
s.updated_at = dto.updated_at.clone();
|
||||
s.mentor_id = None;
|
||||
s.from_profile_extension()
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
impl UsersDetailItemDto {
|
||||
pub fn extract_permissions_from_user_role(&self) -> Vec<String> {
|
||||
self.role.permissions.iter().map(|p| p.name.clone()).collect()
|
||||
}
|
||||
}
|
||||
@@ -1,234 +1,374 @@
|
||||
use imphnen_entities::UsersDetailQueryDto;
|
||||
use super::{UsersListItemDto, UsersListQueryDto, UsersSchema};
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto, get_id, make_thing,
|
||||
};
|
||||
use surrealdb::sql::Thing;
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_utils::{DetailQueryBuilder, QueryListBuilder, make_thing_from_enum};
|
||||
use serde_json;
|
||||
use std::time::Instant;
|
||||
use surrealdb::{Surreal, engine::remote::ws::Client};
|
||||
|
||||
|
||||
|
||||
|
||||
pub struct UsersRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
pub async fn update_partial_schema(
|
||||
db: &Surreal<Client>,
|
||||
table: &str,
|
||||
id: &str,
|
||||
patch: UsersSchema,
|
||||
) -> Result<String> {
|
||||
let thing = make_thing(table, id);
|
||||
let record_key = get_id(&thing)?;
|
||||
let result: Option<UsersSchema> = db.update(record_key).merge(patch).await?;
|
||||
match result {
|
||||
Some(_) => Ok("Success update".into()),
|
||||
None => bail!("Failed to update"),
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> UsersRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_user_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<UsersListItemDto>>> {
|
||||
let now = Instant::now();
|
||||
let result: ResponseListSuccessDto<Vec<UsersListQueryDto>> =
|
||||
QueryListBuilder::new(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&meta,
|
||||
)
|
||||
.with_condition("is_deleted = false")
|
||||
.search_field("fullname")
|
||||
.select_fields(vec!["*"])
|
||||
.fetch_fields(vec!["role", "role.permissions"])
|
||||
.build()
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_list' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let data = result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(UsersListQueryDto::from)
|
||||
.collect();
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_user_by_email(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersDetailQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Users.to_string())
|
||||
.with_where("email", Some(email.clone()))
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch("role")
|
||||
.with_fetch("role.permissions");
|
||||
let sql = builder.build();
|
||||
// Some SurrealDB queries may return multiple rows (e.g., duplicates).
|
||||
// Safely take all rows and pick the first valid user (not deleted and with a valid role).
|
||||
let rows: Vec<UsersDetailQueryDto> = builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
let user_opt: Option<UsersDetailQueryDto> = rows
|
||||
.into_iter()
|
||||
.find(|u| !u.is_deleted && !u.role.is_deleted && u.role.updated_at.is_some());
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_by_email' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let Some(user) = user_opt else {
|
||||
bail!("User not found");
|
||||
};
|
||||
if user.is_deleted {
|
||||
bail!("User not found");
|
||||
}
|
||||
if user.role.updated_at.is_none() || user.role.is_deleted {
|
||||
bail!("User not found");
|
||||
}
|
||||
Ok(UsersDetailQueryDto::from(user))
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
pub async fn query_user_by_id(&self, id: &Thing) -> Result<UsersDetailQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::Users.to_string())
|
||||
.with_id(id.id.to_raw())
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch("role")
|
||||
.with_fetch("role.permissions");
|
||||
let sql = builder.build();
|
||||
let result: Option<UsersDetailQueryDto> =
|
||||
builder.apply_bindings(db.query(sql)).await?.take(0)?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
let Some(user) = result else {
|
||||
bail!("User not found in database");
|
||||
};
|
||||
if user.is_deleted {
|
||||
bail!("User not found");
|
||||
}
|
||||
if user.role.is_deleted {
|
||||
bail!("User's role has been deleted");
|
||||
}
|
||||
Ok(UsersDetailQueryDto::from(user))
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_create_user(&self, data: UsersSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<UsersSchema> = db
|
||||
.create(ResourceEnum::Users.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_user' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success create user".into()),
|
||||
None => bail!("Failed to create user"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(&data.id)?;
|
||||
let existing = self.query_user_by_id(&data.id).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("User already deleted");
|
||||
}
|
||||
let role_thing = if data.role == existing.role.id {
|
||||
existing.role.id.clone()
|
||||
} else {
|
||||
data.role.clone()
|
||||
};
|
||||
let merged = UsersSchema {
|
||||
password: existing.password,
|
||||
created_at: existing.created_at,
|
||||
role: role_thing,
|
||||
..data.clone()
|
||||
};
|
||||
let record: Option<UsersSchema> = db.update(record_key).merge(merged).await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_user' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success update user".into()),
|
||||
None => bail!("Failed to update user"),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_delete_user(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let user = self.query_user_by_id(&make_thing_from_enum(ResourceEnum::Users, &id)).await?;
|
||||
if user.is_deleted {
|
||||
bail!("User not found");
|
||||
}
|
||||
let record_key = get_id(&user.id)?;
|
||||
let record: Option<UsersSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.await?;
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_user' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success delete user".into()),
|
||||
None => bail!("Failed to delete user"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use imphnen_entities::{
|
||||
UsersDetailQueryDto,
|
||||
seaorm::auth::users::{Entity as UsersEntity, ActiveModel as UserActiveModel, Column as UserColumn},
|
||||
seaorm::auth::roles::{Entity as RolesEntity},
|
||||
RolesDetailQueryDto,
|
||||
PermissionsQueryDto // Import this
|
||||
};
|
||||
use crate::{
|
||||
UsersSchema,
|
||||
AppState,
|
||||
MetaRequestDto,
|
||||
ResponseListSuccessDto,
|
||||
MetaResponseDto
|
||||
};
|
||||
use super::users_dto::UsersListItemDto;
|
||||
use sea_orm::{
|
||||
EntityTrait,
|
||||
QueryFilter,
|
||||
PaginatorTrait,
|
||||
ActiveModelTrait,
|
||||
ActiveValue,
|
||||
DatabaseConnection,
|
||||
ColumnTrait,
|
||||
};
|
||||
use anyhow::{Result, bail, anyhow};
|
||||
use uuid::Uuid;
|
||||
use chrono::Utc;
|
||||
use std::time::Instant;
|
||||
|
||||
pub struct UsersRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> UsersRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
fn db(&self) -> &DatabaseConnection {
|
||||
&self.state.postgres_connection.conn
|
||||
}
|
||||
|
||||
pub async fn query_user_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<UsersListItemDto>>> {
|
||||
let now = Instant::now();
|
||||
|
||||
// Build the query
|
||||
let query = UsersEntity::find()
|
||||
.filter(UserColumn::DeletedAt.is_null())
|
||||
.filter(UserColumn::IsActive.eq(true));
|
||||
|
||||
// Apply search if provided
|
||||
// if let Some(search) = &meta.search {
|
||||
// query = query.filter(
|
||||
// UserColumn::Email.contains(search)
|
||||
// .or(UserColumn::Username.contains(search))
|
||||
// .or(UserColumn::FirstName.contains(search))
|
||||
// .or(UserColumn::LastName.contains(search))
|
||||
// );
|
||||
// } // Re-add search capability once query building is fixed
|
||||
|
||||
// Apply ordering
|
||||
// query = query.order_by(UserColumn::CreatedAt, sea_orm::Order::Desc); // Re-add ordering
|
||||
|
||||
// Apply pagination
|
||||
let page = meta.page.unwrap_or(1);
|
||||
let per_page = meta.per_page.unwrap_or(10);
|
||||
let paginator = query.paginate(self.db(), per_page);
|
||||
let users = paginator.fetch_page(page - 1).await?;
|
||||
|
||||
// Optimize: Load all roles in one query
|
||||
let role_ids: Vec<Uuid> = users.iter().filter_map(|u| u.role_id).collect();
|
||||
let roles = if !role_ids.is_empty() {
|
||||
RolesEntity::find()
|
||||
.filter(imphnen_entities::seaorm::auth::roles::Column::Id.is_in(role_ids))
|
||||
.all(self.db())
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|r| (r.id, r.name))
|
||||
.collect::<std::collections::HashMap<_, _>>()
|
||||
} else {
|
||||
std::collections::HashMap::new()
|
||||
};
|
||||
|
||||
// Convert to DTOs
|
||||
let mut data: Vec<UsersListItemDto> = Vec::with_capacity(users.len());
|
||||
for user in users.into_iter() {
|
||||
let role_name = user.role_id.and_then(|rid| roles.get(&rid).cloned()).unwrap_or_default();
|
||||
data.push(UsersListItemDto {
|
||||
id: user.id.to_string(),
|
||||
role: role_name,
|
||||
fullname: format!("{} {}",
|
||||
user.first_name.as_deref().unwrap_or(""),
|
||||
user.last_name.as_deref().unwrap_or("")
|
||||
).trim().to_string(),
|
||||
email: user.email,
|
||||
avatar: user.avatar_url,
|
||||
is_active: user.is_active,
|
||||
created_at: user.created_at.to_rfc3339(),
|
||||
updated_at: user.updated_at.to_rfc3339(),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
let total = paginator.num_items().await?;
|
||||
|
||||
let meta_response = MetaResponseDto {
|
||||
page: Some(page),
|
||||
per_page: Some(per_page),
|
||||
total: Some(total),
|
||||
};
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_list' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: Some(meta_response),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_user_by_email(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersDetailQueryDto> {
|
||||
let now = Instant::now();
|
||||
|
||||
let user_and_role = UsersEntity::find()
|
||||
.filter(UserColumn::Email.eq(email))
|
||||
.filter(UserColumn::DeletedAt.is_null())
|
||||
.find_also_related(RolesEntity)
|
||||
.one(self.db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("User not found"))?;
|
||||
|
||||
let (user, role) = user_and_role;
|
||||
let role_dto = role.map_or_else(RolesDetailQueryDto::default, |r| RolesDetailQueryDto {
|
||||
id: r.id.to_string(),
|
||||
name: r.name,
|
||||
permissions: r.permissions.clone().and_then(|json| {
|
||||
serde_json::from_value::<Vec<String>>(json).ok().map(|list| {
|
||||
list.into_iter().map(|p| Some(PermissionsQueryDto {
|
||||
id: Some(p.clone()),
|
||||
name: Some(p),
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
})).collect()
|
||||
})
|
||||
}),
|
||||
is_deleted: r.deleted_at.is_some(),
|
||||
created_at: Some(r.created_at.to_rfc3339()),
|
||||
updated_at: Some(r.updated_at.to_rfc3339()),
|
||||
});
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_by_email' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
// Convert UserModel to UsersDetailQueryDto
|
||||
let mut dto = UsersDetailQueryDto::default();
|
||||
dto.id = user.id.to_string();
|
||||
dto.fullname = format!("{} {}", user.first_name.as_deref().unwrap_or(""), user.last_name.as_deref().unwrap_or("")).trim().to_string();
|
||||
dto.legal_name = None;
|
||||
dto.email = user.email;
|
||||
dto.avatar = user.avatar_url;
|
||||
dto.is_active = user.is_active;
|
||||
dto.is_deleted = user.deleted_at.is_some();
|
||||
dto.profile_extension = user.metadata.and_then(|m| serde_json::from_value(m).ok()); // Extract from metadata
|
||||
dto.password = String::new(); // Don't expose password
|
||||
dto.role = role_dto; // Use actual role DTO
|
||||
dto.created_at = user.created_at.to_rfc3339();
|
||||
dto.updated_at = user.updated_at.to_rfc3339();
|
||||
dto.mentor_id = None; // Not in model
|
||||
Ok(dto.from_profile_extension())
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_user_by_id(&self, id: &str) -> Result<UsersDetailQueryDto> {
|
||||
let now = Instant::now();
|
||||
|
||||
let user_id = Uuid::parse_str(id)?;
|
||||
let user_and_role = UsersEntity::find_by_id(user_id)
|
||||
.filter(UserColumn::DeletedAt.is_null())
|
||||
.find_also_related(RolesEntity)
|
||||
.one(self.db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("User not found in database"))?;
|
||||
|
||||
let (user, role) = user_and_role;
|
||||
let role_dto = role.map_or_else(RolesDetailQueryDto::default, |r| RolesDetailQueryDto {
|
||||
id: r.id.to_string(),
|
||||
name: r.name,
|
||||
permissions: r.permissions.clone().and_then(|json| {
|
||||
serde_json::from_value::<Vec<String>>(json).ok().map(|list| {
|
||||
list.into_iter().map(|p| Some(PermissionsQueryDto {
|
||||
id: Some(p.clone()),
|
||||
name: Some(p),
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
})).collect()
|
||||
})
|
||||
}),
|
||||
is_deleted: r.deleted_at.is_some(),
|
||||
created_at: Some(r.created_at.to_rfc3339()),
|
||||
updated_at: Some(r.updated_at.to_rfc3339()),
|
||||
});
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_user_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
// Convert UserModel to UsersDetailQueryDto
|
||||
let mut dto = UsersDetailQueryDto::default();
|
||||
dto.id = user.id.to_string();
|
||||
dto.fullname = format!("{} {}", user.first_name.as_deref().unwrap_or(""), user.last_name.as_deref().unwrap_or("")).trim().to_string();
|
||||
dto.legal_name = None;
|
||||
dto.email = user.email;
|
||||
dto.avatar = user.avatar_url;
|
||||
dto.is_active = user.is_active;
|
||||
dto.is_deleted = user.deleted_at.is_some();
|
||||
dto.profile_extension = user.metadata.and_then(|m| serde_json::from_value(m).ok()); // Extract from metadata
|
||||
dto.password = String::new(); // Don't expose password
|
||||
dto.role = role_dto; // Use actual role DTO
|
||||
dto.created_at = user.created_at.to_rfc3339();
|
||||
dto.updated_at = user.updated_at.to_rfc3339();
|
||||
dto.mentor_id = None; // Not in model
|
||||
Ok(dto.from_profile_extension())
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_create_user(&self, data: UsersSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
// Check if user already exists
|
||||
let existing_user = UsersEntity::find()
|
||||
.filter(UserColumn::Email.eq(data.email.clone()))
|
||||
.one(self.db())
|
||||
.await?;
|
||||
|
||||
if existing_user.is_some() {
|
||||
bail!("User with this email already exists");
|
||||
}
|
||||
|
||||
let email = data.email.ok_or_else(|| anyhow!("Email is required"))?;
|
||||
let password = data.password.ok_or_else(|| anyhow!("Password is required"))?;
|
||||
let full_name = data.fullname.unwrap_or_default();
|
||||
let (first_name, last_name) = full_name.split_once(' ').unwrap_or((&full_name, ""));
|
||||
|
||||
let user_active_model = UserActiveModel {
|
||||
id: ActiveValue::Set(Uuid::new_v4()),
|
||||
email: ActiveValue::Set(email.clone()),
|
||||
password_hash: ActiveValue::Set(password),
|
||||
username: ActiveValue::Set(email.clone()), // Use email as username for now
|
||||
first_name: ActiveValue::Set(Some(first_name.to_string())),
|
||||
last_name: ActiveValue::Set(Some(last_name.to_string())),
|
||||
avatar_url: ActiveValue::Set(data.avatar),
|
||||
is_verified: ActiveValue::Set(false),
|
||||
is_active: ActiveValue::Set(data.is_active),
|
||||
metadata: ActiveValue::Set(data.profile_extension.map(|p| serde_json::to_value(p).unwrap_or_default())), // Save profile_extension to metadata
|
||||
created_at: ActiveValue::Set(Utc::now()),
|
||||
updated_at: ActiveValue::Set(Utc::now()),
|
||||
deleted_at: ActiveValue::Set(None),
|
||||
role_id: ActiveValue::Set(data.role_id), // Add this line
|
||||
};
|
||||
|
||||
let _result = UsersEntity::insert(user_active_model).exec(self.db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_create_user' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Successfully created user".into())
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let user_id = Uuid::parse_str(&data.id)?;
|
||||
let existing = self.query_user_by_id(&data.id).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("User already deleted");
|
||||
}
|
||||
|
||||
let mut user_active_model: UserActiveModel = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("User not found"))?
|
||||
.into();
|
||||
|
||||
let email = data.email.ok_or_else(|| anyhow!("Email is required"))?;
|
||||
let full_name = data.fullname.unwrap_or_default();
|
||||
let (first_name, last_name) = full_name.split_once(' ').unwrap_or((&full_name, ""));
|
||||
|
||||
// Update fields
|
||||
user_active_model.email = ActiveValue::Set(email);
|
||||
user_active_model.first_name = ActiveValue::Set(Some(first_name.to_string()));
|
||||
user_active_model.last_name = ActiveValue::Set(Some(last_name.to_string()));
|
||||
user_active_model.avatar_url = ActiveValue::Set(data.avatar);
|
||||
user_active_model.is_active = ActiveValue::Set(data.is_active);
|
||||
user_active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
if data.role_id.is_some() { // Conditionally update role_id
|
||||
user_active_model.role_id = ActiveValue::Set(data.role_id);
|
||||
}
|
||||
if data.profile_extension.is_some() { // Conditionally update profile_extension
|
||||
user_active_model.metadata = ActiveValue::Set(data.profile_extension.map(|p| serde_json::to_value(p).unwrap_or_default()));
|
||||
}
|
||||
|
||||
let _result = user_active_model.update(self.db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_update_user' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success update user".into())
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_delete_user(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
|
||||
let user_id = Uuid::parse_str(&id)?;
|
||||
let user = self.query_user_by_id(&id).await?;
|
||||
if user.is_deleted {
|
||||
bail!("User not found");
|
||||
}
|
||||
|
||||
let mut user_active_model: UserActiveModel = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db())
|
||||
.await?
|
||||
.ok_or_else(|| anyhow::anyhow!("User not found"))?
|
||||
.into();
|
||||
|
||||
// Soft delete
|
||||
user_active_model.deleted_at = ActiveValue::Set(Some(chrono::Utc::now()));
|
||||
user_active_model.updated_at = ActiveValue::Set(chrono::Utc::now());
|
||||
|
||||
let _result = user_active_model.update(self.db()).await?;
|
||||
|
||||
let elapsed = now.elapsed();
|
||||
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_delete_user' took: {elapsed:.2?}");
|
||||
}
|
||||
|
||||
Ok("Success delete user".into())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,289 +1,156 @@
|
||||
use imphnen_entities::{UsersDetailQueryDto, ExperienceDto, EducationDto};
|
||||
use super::{UsersCreateRequestDto, UsersUpdateRequestDto};
|
||||
use imphnen_libs::{ResourceEnum, hash_password};
|
||||
use imphnen_utils::extract_id;
|
||||
use imphnen_utils::{get_iso_date, make_thing_from_enum};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{Uuid, sql::Thing};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersSchema {
|
||||
pub id: Thing,
|
||||
pub fullname: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_for_verification: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub mentor_id: Option<Thing>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub gender: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub birthdate: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub domicile: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bio: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub last_education: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub linkedin_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub github_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cv_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub portfolio_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub website_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub twitter_url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub location: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub skills: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub experience: Option<Vec<ExperienceDto>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub education: Option<Vec<EducationDto>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub career_status: Option<String>,
|
||||
pub role: Thing,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl Default for UsersSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::Users,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
fullname: String::new(),
|
||||
legal_name: None,
|
||||
email: String::new(),
|
||||
password: hash_password("").unwrap(),
|
||||
avatar: None,
|
||||
phone_number: String::new(),
|
||||
phone_for_verification: None,
|
||||
is_active: false,
|
||||
is_deleted: false,
|
||||
mentor_id: None, // Regular users should not have a mentor_id by default
|
||||
gender: None,
|
||||
birthdate: None,
|
||||
domicile: None,
|
||||
bio: None,
|
||||
last_education: None,
|
||||
linkedin_url: None,
|
||||
github_url: None,
|
||||
cv_url: None,
|
||||
portfolio_url: None,
|
||||
website_url: None,
|
||||
twitter_url: None,
|
||||
location: None,
|
||||
skills: None,
|
||||
experience: None,
|
||||
education: None,
|
||||
career_status: None,
|
||||
role: make_thing_from_enum(
|
||||
ResourceEnum::Roles,
|
||||
"5713cb37-dc02-4e87-8048-d7a41d352059",
|
||||
),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UsersSchema {
|
||||
pub fn from(dto: UsersDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
fullname: dto.fullname,
|
||||
legal_name: dto.legal_name,
|
||||
email: dto.email,
|
||||
avatar: dto.avatar,
|
||||
phone_number: dto.phone_number,
|
||||
phone_for_verification: dto.phone_for_verification,
|
||||
is_active: dto.is_active,
|
||||
is_deleted: dto.is_deleted,
|
||||
mentor_id: dto.mentor_id, // Use the actual mentor_id from the DTO, could be None
|
||||
gender: dto.gender,
|
||||
birthdate: dto.birthdate,
|
||||
domicile: dto.domicile,
|
||||
bio: dto.bio,
|
||||
last_education: dto.last_education,
|
||||
linkedin_url: dto.linkedin_url,
|
||||
github_url: dto.github_url,
|
||||
cv_url: dto.cv_url,
|
||||
portfolio_url: dto.portfolio_url,
|
||||
website_url: dto.website_url,
|
||||
twitter_url: dto.twitter_url,
|
||||
location: dto.location,
|
||||
skills: dto.skills,
|
||||
experience: dto.experience,
|
||||
education: dto.education,
|
||||
career_status: dto.career_status,
|
||||
password: dto.password,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
role: make_thing_from_enum(ResourceEnum::Roles, &extract_id(&dto.role.id)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(_user: UsersUpdateRequestDto, id: String) -> Self {
|
||||
Self {
|
||||
id: make_thing_from_enum(ResourceEnum::Users, &id),
|
||||
updated_at: get_iso_date(),
|
||||
// Set defaults for required fields - these should be overridden by actual data from DB
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn partial_update(current_user: UsersDetailQueryDto, user: UsersUpdateRequestDto) -> Self {
|
||||
let mut schema = Self::from(current_user);
|
||||
schema.updated_at = get_iso_date();
|
||||
|
||||
// Only update fields that are provided (Some)
|
||||
if let Some(fullname) = user.fullname {
|
||||
schema.fullname = fullname;
|
||||
}
|
||||
if let Some(email) = user.email {
|
||||
schema.email = email;
|
||||
}
|
||||
if let Some(password) = user.password {
|
||||
schema.password = hash_password(&password).unwrap_or(password);
|
||||
}
|
||||
if let Some(phone_number) = user.phone_number {
|
||||
schema.phone_number = phone_number;
|
||||
}
|
||||
if let Some(is_active) = user.is_active {
|
||||
schema.is_active = is_active;
|
||||
}
|
||||
if let Some(role_id) = user.role_id {
|
||||
schema.role = make_thing_from_enum(ResourceEnum::Roles, &role_id);
|
||||
}
|
||||
|
||||
// Optional fields - only update if provided
|
||||
if let Some(legal_name) = user.legal_name {
|
||||
schema.legal_name = Some(legal_name);
|
||||
}
|
||||
if let Some(phone_for_verification) = user.phone_for_verification {
|
||||
schema.phone_for_verification = Some(phone_for_verification);
|
||||
}
|
||||
if let Some(gender) = user.gender {
|
||||
schema.gender = Some(gender);
|
||||
}
|
||||
if let Some(birthdate) = user.birthdate {
|
||||
schema.birthdate = Some(birthdate);
|
||||
}
|
||||
if let Some(domicile) = user.domicile {
|
||||
schema.domicile = Some(domicile);
|
||||
}
|
||||
if let Some(bio) = user.bio {
|
||||
schema.bio = Some(bio);
|
||||
}
|
||||
if let Some(last_education) = user.last_education {
|
||||
schema.last_education = Some(last_education);
|
||||
}
|
||||
if let Some(linkedin_url) = user.linkedin_url {
|
||||
schema.linkedin_url = Some(linkedin_url);
|
||||
}
|
||||
if let Some(github_url) = user.github_url {
|
||||
schema.github_url = Some(github_url);
|
||||
}
|
||||
if let Some(cv_url) = user.cv_url {
|
||||
schema.cv_url = Some(cv_url);
|
||||
}
|
||||
if let Some(portfolio_url) = user.portfolio_url {
|
||||
schema.portfolio_url = Some(portfolio_url);
|
||||
}
|
||||
if let Some(website_url) = user.website_url {
|
||||
schema.website_url = Some(website_url);
|
||||
}
|
||||
if let Some(twitter_url) = user.twitter_url {
|
||||
schema.twitter_url = Some(twitter_url);
|
||||
}
|
||||
if let Some(location) = user.location {
|
||||
schema.location = Some(location);
|
||||
}
|
||||
if let Some(skills) = user.skills {
|
||||
schema.skills = Some(skills);
|
||||
}
|
||||
if let Some(experience) = user.experience {
|
||||
schema.experience = Some(experience);
|
||||
}
|
||||
if let Some(education) = user.education {
|
||||
schema.education = Some(education);
|
||||
}
|
||||
if let Some(career_status) = user.career_status {
|
||||
schema.career_status = Some(career_status);
|
||||
}
|
||||
if let Some(avatar) = user.avatar {
|
||||
schema.avatar = Some(avatar);
|
||||
}
|
||||
|
||||
schema
|
||||
}
|
||||
|
||||
pub fn create(user: UsersCreateRequestDto) -> Self {
|
||||
let password = hash_password(&user.password).unwrap();
|
||||
Self {
|
||||
id: make_thing_from_enum(
|
||||
ResourceEnum::Users,
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
fullname: user.fullname,
|
||||
legal_name: Some("".to_string()),
|
||||
email: user.email,
|
||||
password,
|
||||
phone_number: user.phone_number.clone(),
|
||||
phone_for_verification: Some(user.phone_number.clone()),
|
||||
is_active: user.is_active,
|
||||
mentor_id: None, // Regular users should not have a mentor_id by default
|
||||
gender: Some("".to_string()),
|
||||
birthdate: Some("".to_string()),
|
||||
domicile: Some("".to_string()),
|
||||
bio: Some("".to_string()),
|
||||
last_education: Some("".to_string()),
|
||||
linkedin_url: Some("".to_string()),
|
||||
github_url: Some("".to_string()),
|
||||
cv_url: Some("".to_string()),
|
||||
portfolio_url: Some("".to_string()),
|
||||
website_url: Some("".to_string()),
|
||||
twitter_url: Some("".to_string()),
|
||||
location: Some("".to_string()),
|
||||
skills: Some(vec![]),
|
||||
experience: Some(vec![]),
|
||||
education: Some(vec![]),
|
||||
career_status: Some("".to_string()),
|
||||
avatar: user.avatar.or(Some("https://via.placeholder.com/150".to_string())),
|
||||
is_deleted: false,
|
||||
role: make_thing_from_enum(ResourceEnum::Roles, &user.role_id),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn patch_password(dto: UsersDetailQueryDto, password: String) -> Self {
|
||||
Self {
|
||||
password,
|
||||
id: dto.id.clone(),
|
||||
..Self::from(dto)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_mentor_id(mut self, mentor_id: Option<String>) -> Self {
|
||||
self.mentor_id = mentor_id.map(|id| make_thing_from_enum(ResourceEnum::Users, &id));
|
||||
self.updated_at = get_iso_date();
|
||||
self
|
||||
}
|
||||
}
|
||||
use imphnen_entities::{UsersDetailQueryDto, users::UserProfileExtensionDto};
|
||||
use super::{UsersCreateRequestDto, UsersUpdateRequestDto};
|
||||
use imphnen_libs::hash_password; // Keep hash_password
|
||||
use imphnen_utils::generate_date::get_iso_date; // Keep get_iso_date
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid; // Keep Uuid
|
||||
use anyhow::Result;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersSchema {
|
||||
pub id: String,
|
||||
pub fullname: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub legal_name: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub password: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub avatar: Option<String>,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub mentor_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub profile_extension: Option<UserProfileExtensionDto>,
|
||||
pub role_id: Option<Uuid>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl Default for UsersSchema {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
fullname: None,
|
||||
legal_name: None,
|
||||
email: None,
|
||||
password: None,
|
||||
avatar: None,
|
||||
is_active: false,
|
||||
is_deleted: false,
|
||||
mentor_id: None,
|
||||
profile_extension: None,
|
||||
role_id: None,
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UsersSchema {
|
||||
pub fn from(dto: UsersDetailQueryDto) -> Self {
|
||||
Self {
|
||||
id: dto.id,
|
||||
fullname: Some(dto.fullname),
|
||||
legal_name: dto.legal_name,
|
||||
email: Some(dto.email),
|
||||
avatar: dto.avatar,
|
||||
is_active: dto.is_active,
|
||||
is_deleted: dto.is_deleted,
|
||||
mentor_id: dto.mentor_id,
|
||||
profile_extension: dto.profile_extension,
|
||||
password: Some(dto.password),
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
role_id: Uuid::parse_str(&dto.role.id).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create(dto: UsersCreateRequestDto) -> Result<Self> {
|
||||
let password_hash = hash_password(&dto.password).map_err(|e| anyhow::anyhow!("Hash password failed: {}", e))?;
|
||||
Ok(Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
email: Some(dto.email),
|
||||
password: Some(password_hash),
|
||||
fullname: Some(dto.fullname),
|
||||
is_active: dto.is_active,
|
||||
role_id: Some(Uuid::parse_str(&dto.role_id)?),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update(_user: UsersUpdateRequestDto, id: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
updated_at: get_iso_date(),
|
||||
created_at: String::new(),
|
||||
fullname: None,
|
||||
legal_name: None,
|
||||
email: None,
|
||||
password: None,
|
||||
avatar: None,
|
||||
is_active: false,
|
||||
is_deleted: false,
|
||||
mentor_id: None,
|
||||
profile_extension: None,
|
||||
role_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn partial_update(current_user: UsersDetailQueryDto, user: UsersUpdateRequestDto) -> Self {
|
||||
let mut schema = Self::from(current_user);
|
||||
schema.updated_at = get_iso_date();
|
||||
|
||||
// Only update fields that are provided (Some)
|
||||
if let Some(fullname) = user.fullname {
|
||||
schema.fullname = Some(fullname);
|
||||
}
|
||||
if let Some(email) = user.email {
|
||||
schema.email = Some(email);
|
||||
}
|
||||
if let Some(password) = user.password {
|
||||
schema.password = Some(hash_password(&password).unwrap_or(password));
|
||||
}
|
||||
if let Some(is_active) = user.is_active {
|
||||
schema.is_active = is_active;
|
||||
}
|
||||
if let Some(role_id) = user.role_id {
|
||||
schema.role_id = Uuid::parse_str(&role_id).ok();
|
||||
}
|
||||
|
||||
schema.legal_name = user.legal_name;
|
||||
schema.avatar = user.avatar;
|
||||
schema.profile_extension = user.profile_extension;
|
||||
|
||||
schema
|
||||
}
|
||||
|
||||
pub fn patch_password(dto: UsersDetailQueryDto, password: String) -> Self {
|
||||
Self {
|
||||
password: Some(password),
|
||||
id: dto.id.clone(),
|
||||
fullname: Some(dto.fullname),
|
||||
legal_name: dto.legal_name,
|
||||
email: Some(dto.email),
|
||||
avatar: dto.avatar,
|
||||
is_active: dto.is_active,
|
||||
is_deleted: dto.is_deleted,
|
||||
mentor_id: dto.mentor_id,
|
||||
profile_extension: dto.profile_extension,
|
||||
created_at: dto.created_at,
|
||||
updated_at: dto.updated_at,
|
||||
role_id: Uuid::parse_str(&dto.role.id).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_mentor_id(mut self, mentor_id: Option<String>) -> Self {
|
||||
self.mentor_id = mentor_id; // Removed make_thing_from_enum
|
||||
self.updated_at = get_iso_date();
|
||||
self
|
||||
}
|
||||
|
||||
/// Convert role string to Uuid for database operations
|
||||
pub fn get_role_id(&self) -> Result<Option<Uuid>> {
|
||||
Ok(self.role_id) // Removed parsing from `role` field
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,18 +2,18 @@ use super::{
|
||||
UsersActiveInactiveRequestDto, UsersCreateRequestDto,
|
||||
UsersSetNewPasswordRequestDto, UsersUpdateRequestDto,
|
||||
};
|
||||
use imphnen_entities::UsersDetailQueryDto;
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, UsersRepository, UsersSchema,
|
||||
ResponseSuccessDto, common_response, success_list_response,
|
||||
success_response, validate_request,
|
||||
};
|
||||
use imphnen_utils::{errors::AppError, error_response};
|
||||
use imphnen_utils::success_created_response;
|
||||
use imphnen_utils::{errors::AppError, response_format::error_response};
|
||||
use imphnen_utils::response_format::success_created_response;
|
||||
use axum::{http::StatusCode, response::Response, extract::Multipart};
|
||||
use imphnen_libs::{ResourceEnum, hash_password, verify_password, MinioConfig, FileType, decode_base64_file, extract_content_type_from_data_url, create_minio_service_from_config};
|
||||
use imphnen_libs::{hash_password, verify_password, MinioConfig, FileType, decode_base64_file, extract_content_type_from_data_url, create_minio_service_from_config};
|
||||
use imphnen_utils::make_thing_from_enum;
|
||||
use uuid::Uuid;
|
||||
|
||||
use std::pin::Pin;
|
||||
use std::future::Future;
|
||||
use anyhow::Result;
|
||||
@@ -22,8 +22,6 @@ use tracing::info;
|
||||
use tracing::error;
|
||||
use crate::v1::users::users_dto::{UsersDetailItemDto as UserDto, UsersCreateRequestDto as CreateUserDto};
|
||||
use serde_json::json;
|
||||
use async_trait::async_trait;
|
||||
use imphnen_libs::UserLookupService;
|
||||
|
||||
|
||||
pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
@@ -37,7 +35,6 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
fn update_user_password(state: &AppState, email: String, payload: UsersSetNewPasswordRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>>;
|
||||
fn get_user_by_mentor_id(state: &AppState, mentor_id: String) -> Pin<Box<dyn Future<Output = Response> + Send>>;
|
||||
fn delete_user(state: &AppState, id: String) -> Pin<Box<dyn Future<Output = Response> + Send>>;
|
||||
fn get_user_by_id_internal(&self, id: &surrealdb::sql::Thing, state: &AppState) -> Pin<Box<dyn Future<Output = Result<UsersDetailQueryDto>> + Send>>;
|
||||
|
||||
fn get_user_by_email(&self, email: &str, state: &AppState) -> Pin<Box<dyn Future<Output = Result<Option<UserDto>>> + Send>>;
|
||||
fn create_user_by_dto(&self, new_user: CreateUserDto, state: &AppState) -> Pin<Box<dyn Future<Output = Result<UserDto>> + Send>>;
|
||||
@@ -53,14 +50,6 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
|
||||
|
||||
impl UsersServiceTrait for UsersService {
|
||||
fn get_user_by_id_internal(&self, id: &surrealdb::sql::Thing, state: &AppState) -> Pin<Box<dyn Future<Output = Result<UsersDetailQueryDto>> + Send>> {
|
||||
let id = id.to_owned();
|
||||
let state = state.to_owned();
|
||||
Box::pin(async move {
|
||||
let repo = crate::UsersRepository::new(&state);
|
||||
repo.query_user_by_id(&id).await
|
||||
})
|
||||
}
|
||||
fn get_user_list(state: &AppState, meta: MetaRequestDto) -> Pin<Box<dyn Future<Output = Response> + Send>> {
|
||||
let state = state.to_owned();
|
||||
Box::pin(async move {
|
||||
@@ -86,7 +75,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
return error_response(AppError::BadRequestError("Invalid User ID format".into()));
|
||||
}
|
||||
let repo = UsersRepository::new(&state);
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Users, &id);
|
||||
let thing_id = make_thing_from_enum("users", &id);
|
||||
match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: UserDto::from(&user), // Corrected to use UserDto::from by reference
|
||||
@@ -102,7 +91,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
let state = state.to_owned();
|
||||
Box::pin(async move {
|
||||
let repo = UsersRepository::new(&state);
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Users, &claims.user_id);
|
||||
let thing_id = make_thing_from_enum("users", &claims.user_id);
|
||||
match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: UserDto::from(&user),
|
||||
@@ -130,7 +119,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
{
|
||||
return error_response(AppError::ConflictError("User already exists".into()));
|
||||
}
|
||||
match repo.query_create_user(UsersSchema::create(new_user.clone())).await {
|
||||
match repo.query_create_user(UsersSchema::create(new_user.clone()).expect("Failed to create user schema")).await {
|
||||
Ok(_msg) => {
|
||||
// After successful creation, fetch the created user
|
||||
match repo.query_user_by_email(new_user.email).await {
|
||||
@@ -164,7 +153,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
}
|
||||
|
||||
// Get current user data first
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Users, &id);
|
||||
let thing_id = make_thing_from_enum("users", &id);
|
||||
let current_user = match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) => user,
|
||||
Err(_) => return error_response(AppError::NotFoundError("User not found".into())),
|
||||
@@ -188,7 +177,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
Box::pin(async move {
|
||||
let repo = UsersRepository::new(&state);
|
||||
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Users, &claims.user_id);
|
||||
let thing_id = make_thing_from_enum("users", &claims.user_id);
|
||||
let user_data = match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) => user,
|
||||
Err(_) => return common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||
@@ -218,7 +207,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
return error_response(AppError::BadRequestError("Invalid User ID format".into()));
|
||||
}
|
||||
let repo = UsersRepository::new(&state);
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Users, &id);
|
||||
let thing_id = make_thing_from_enum("users", &id);
|
||||
match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) if !user.is_deleted => {
|
||||
let patch = UsersSchema {
|
||||
@@ -268,7 +257,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
};
|
||||
let patch = UsersSchema {
|
||||
id: user.id.clone(),
|
||||
password: new_password,
|
||||
password: Some(new_password),
|
||||
..Default::default()
|
||||
};
|
||||
match repo.query_update_user(patch).await {
|
||||
@@ -286,7 +275,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
let mentor_id = mentor_id.to_owned();
|
||||
Box::pin(async move {
|
||||
let repo = UsersRepository::new(&state);
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Mentors, &mentor_id);
|
||||
let thing_id = make_thing_from_enum("mentors", &mentor_id);
|
||||
match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: UserDto::from(&user), // Corrected to use UserDto::from by reference
|
||||
@@ -305,7 +294,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
return error_response(AppError::BadRequestError("Invalid User ID format".into()));
|
||||
}
|
||||
let repo = UsersRepository::new(&state);
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Users, &id);
|
||||
let thing_id = make_thing_from_enum("users", &id);
|
||||
if repo.query_user_by_id(&thing_id).await.is_err() {
|
||||
return error_response(AppError::NotFoundError("User not found".into()));
|
||||
}
|
||||
@@ -343,13 +332,12 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
};
|
||||
|
||||
let user_schema = UsersSchema {
|
||||
email: new_user.email,
|
||||
password: hashed_password,
|
||||
fullname: new_user.fullname,
|
||||
phone_number: new_user.phone_number,
|
||||
email: Some(new_user.email),
|
||||
password: Some(hashed_password),
|
||||
fullname: Some(new_user.fullname),
|
||||
is_active: new_user.is_active,
|
||||
avatar: new_user.avatar,
|
||||
role: make_thing_from_enum(ResourceEnum::Roles, &new_user.role_id),
|
||||
role_id: Some(Uuid::parse_str(&new_user.role_id).unwrap_or(Uuid::new_v4())),
|
||||
..Default::default()
|
||||
};
|
||||
match repo.query_create_user(user_schema).await {
|
||||
@@ -427,10 +415,10 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
|
||||
// Get actual user data from database using user_id (which is a UUID)
|
||||
let repo = UsersRepository::new(&state);
|
||||
let thing_id = make_thing_from_enum(ResourceEnum::Users, &user_id);
|
||||
let thing_id = make_thing_from_enum("users", &user_id);
|
||||
let user_data = match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) => {
|
||||
info!("Found user in DB. User ID: {}, Email: {}", user.id.id.to_raw(), user.email);
|
||||
info!("Found user in DB. User ID: {}, Email: {}", user.to_string(), user.email);
|
||||
user
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -441,7 +429,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
);
|
||||
}
|
||||
};
|
||||
let actual_user_id = user_data.id.id.to_raw();
|
||||
let actual_user_id = user_data.to_string();
|
||||
let user_email = user_data.email;
|
||||
|
||||
let mut file_data: Option<Vec<u8>> = None;
|
||||
@@ -558,7 +546,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
error!("File type '{:?}' does not match content type '{}'.", file_type, content_type);
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
&format!("File type '{:?}' does not match content type '{}'", file_type, content_type),
|
||||
&format!("File type '{file_type:?}' does not match content type '{content_type}'"),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -582,8 +570,8 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
.replace(".", "_");
|
||||
info!("Sanitized user ID for folder path: {}", sanitized_user_id);
|
||||
|
||||
let folder = format!("{}/{}", file_type.as_folder(), sanitized_user_id);
|
||||
info!("Upload folder: {}", folder);
|
||||
let folder = format!("{}/{sanitized_user_id}", file_type.as_folder());
|
||||
info!("Upload folder: {folder}");
|
||||
|
||||
// Upload file to MinIO with deduplication
|
||||
info!("Attempting to upload file to MinIO.");
|
||||
@@ -615,7 +603,7 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
error!("Failed to upload file to MinIO: {}", e);
|
||||
common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&format!("Upload failed: {}", e),
|
||||
&format!("Upload failed: {e}"),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -623,14 +611,3 @@ pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UserLookupService for UsersService {
|
||||
async fn get_user_by_id_internal(
|
||||
&self,
|
||||
thing_id: &surrealdb::sql::Thing,
|
||||
state: &imphnen_libs::AppState,
|
||||
) -> Result<imphnen_entities::UsersDetailQueryDto, anyhow::Error> {
|
||||
let repo = crate::UsersRepository::new(state);
|
||||
repo.query_user_by_id(thing_id).await.map_err(|e| anyhow::anyhow!(e))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user