chore: normalize code
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "imphnen-iam"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
imphnen-libs = { version = "0.1.0", path = "../imphnen-libs" }
|
||||
imphnen-utils = { version = "0.1.0", path = "../imphnen-utils" }
|
||||
imphnen-entities = { version = "0.1.0", path = "../imphnen-entities" }
|
||||
axum.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
utoipa.workspace = true
|
||||
lazy_static.workspace = true
|
||||
regex.workspace = true
|
||||
validator.workspace = true
|
||||
axum-test.workspace = true
|
||||
surrealdb.workspace = true
|
||||
rand.workspace = true
|
||||
tokio.workspace = true
|
||||
chrono.workspace = true
|
||||
anyhow.workspace = true
|
||||
tower-http.workspace = true
|
||||
utoipa-swagger-ui.workspace = true
|
||||
@@ -0,0 +1,34 @@
|
||||
use ::surrealdb::Uuid;
|
||||
use imphnen_entities::*;
|
||||
use imphnen_libs::*;
|
||||
use imphnen_utils::*;
|
||||
|
||||
pub mod v1;
|
||||
|
||||
pub use imphnen_entities::*;
|
||||
pub use imphnen_libs::*;
|
||||
pub use imphnen_utils::*;
|
||||
pub use v1::*;
|
||||
|
||||
pub fn create_test_user(
|
||||
email: &str,
|
||||
fullname: &str,
|
||||
is_active: bool,
|
||||
role_id: &str,
|
||||
) -> UsersSchema {
|
||||
UsersSchema {
|
||||
id: make_thing("app_users", &Uuid::new_v4().to_string()),
|
||||
email: email.to_string(),
|
||||
fullname: format!("Randomize {} {}", fullname, rand::random::<u32>()),
|
||||
password: hash_password("secret").unwrap(),
|
||||
is_deleted: false,
|
||||
avatar: None,
|
||||
phone_number: "081234567890".to_string(),
|
||||
is_active,
|
||||
gender: None,
|
||||
birthdate: None,
|
||||
role: make_thing("app_roles", role_id),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto, AuthService, AuthVerifyEmailRequestDto,
|
||||
};
|
||||
use crate::{v1::AuthLoginResponsetDto, AppState};
|
||||
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
|
||||
use axum::{response::IntoResponse, Extension, Json};
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "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/register",
|
||||
request_body = AuthRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Register successful", body = MessageResponseDto),
|
||||
(status = 401, description = "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 = "Verify email successful", body = MessageResponseDto),
|
||||
(status = 401, description = "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 = "Resend otp successful", body = MessageResponseDto),
|
||||
(status = 401, description = "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 = "Forgot password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "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 = "New password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "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 = "Refresh token request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "Refresh token request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_refresh_token(
|
||||
Json(payload): Json<AuthRefreshTokenRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_refresh_token(payload).await
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
use crate::RolesItemDto;
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
lazy_static! {
|
||||
static ref PASSWORD_REGEX: Regex = Regex::new(r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$").unwrap();
|
||||
}
|
||||
|
||||
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 AuthUserItemDto {
|
||||
pub id: String,
|
||||
pub role: RolesItemDto,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub gender: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AuthLoginResponsetDto {
|
||||
pub token: TokenDto,
|
||||
pub user: AuthUserItemDto,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
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 student_type: String,
|
||||
#[validate(length(
|
||||
min = 10,
|
||||
message = "Phone number at least have 10 character"
|
||||
))]
|
||||
pub phone_number: String,
|
||||
#[validate(length(
|
||||
max = 4,
|
||||
message = "Referal code cannot be more than 4 character"
|
||||
))]
|
||||
pub referral_code: Option<String>,
|
||||
pub referred_by: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthActiveInactiveRequestDto {
|
||||
pub is_active: bool,
|
||||
#[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 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 {
|
||||
pub token: String,
|
||||
#[validate(length(min = 1, message = "Token cannot be empty"))]
|
||||
#[validate(regex(
|
||||
path = "PASSWORD_REGEX",
|
||||
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(regex(
|
||||
path = "PASSWORD_REGEX",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use super::AuthOtpSchema;
|
||||
use crate::{make_thing, AppState, ResourceEnum, UsersItemDtoRaw};
|
||||
use anyhow::{anyhow, bail, Result};
|
||||
use chrono::{Duration, Utc};
|
||||
|
||||
pub struct AuthRepository<'a> {
|
||||
pub state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> AuthRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_store_user(&self, user: UsersItemDtoRaw) -> 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 id = make_thing(&table, &user_id);
|
||||
let _ = self
|
||||
.state
|
||||
.surrealdb_mem
|
||||
.delete::<Option<UsersItemDtoRaw>>((table.clone(), user_id.clone()))
|
||||
.await?;
|
||||
let mut user_to_store = user.clone();
|
||||
user_to_store.id = id.clone();
|
||||
let record: Option<UsersItemDtoRaw> = self
|
||||
.state
|
||||
.surrealdb_mem
|
||||
.create((table, user_id))
|
||||
.content(user_to_store)
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success store user data".to_string()),
|
||||
None => bail!("Failed store user data"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_get_stored_user(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersItemDtoRaw> {
|
||||
let user: Option<UsersItemDtoRaw> = self
|
||||
.state
|
||||
.surrealdb_mem
|
||||
.select((ResourceEnum::UsersCache.to_string(), email))
|
||||
.await?;
|
||||
match user {
|
||||
Some(u) => Ok(u),
|
||||
None => bail!("No stored user data found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_stored_user(&self, email: String) -> Result<String> {
|
||||
let record: Option<UsersItemDtoRaw> = self
|
||||
.state
|
||||
.surrealdb_mem
|
||||
.delete((ResourceEnum::UsersCache.to_string(), email))
|
||||
.await?;
|
||||
dbg!(record.clone());
|
||||
match record {
|
||||
Some(_) => Ok("Success delete stored user".to_string()),
|
||||
None => bail!("Failed delete stored user"),
|
||||
}
|
||||
}
|
||||
|
||||
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());
|
||||
let result: Option<AuthOtpSchema> = self.state.surrealdb_mem.select(key).await?;
|
||||
match result {
|
||||
Some(data) => match Utc::now() > data.expires_at {
|
||||
true => {
|
||||
let _ = self
|
||||
.state
|
||||
.surrealdb_mem
|
||||
.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: u32) -> Result<String> {
|
||||
let expires_at = Utc::now() + Duration::seconds(300);
|
||||
let table: String = ResourceEnum::OtpCache.to_string();
|
||||
let record: Option<AuthOtpSchema> = self
|
||||
.state
|
||||
.surrealdb_mem
|
||||
.create((table.as_str(), email.as_str()))
|
||||
.content(AuthOtpSchema { otp, expires_at })
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success store otp".to_string()),
|
||||
None => bail!("Failed store otp"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_stored_otp(&self, email: String) -> Result<String> {
|
||||
let record: Option<AuthOtpSchema> = self
|
||||
.state
|
||||
.surrealdb_mem
|
||||
.delete((ResourceEnum::OtpCache.to_string(), email))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete stored otp".to_string()),
|
||||
None => bail!("Failed delete stored otp"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AuthOtpSchema {
|
||||
pub otp: u32,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto,
|
||||
AuthRefreshTokenRequestDto, AuthRegisterRequestDto, AuthRepository,
|
||||
AuthResendOtpRequestDto, AuthUserItemDto, AuthVerifyEmailRequestDto, TokenDto,
|
||||
};
|
||||
use crate::{
|
||||
common_response, decode_refresh_token, encode_access_token, encode_refresh_token,
|
||||
encode_reset_password_token, extract_email_token, generate_otp, get_iso_date,
|
||||
hash_password, make_thing, send_email, success_response, validate_request,
|
||||
verify_password, AppState, Env, ResourceEnum, ResponseSuccessDto, RolesEnum,
|
||||
RolesItemDto, RolesRepository, UsersActiveInactiveSchema, UsersRepository,
|
||||
UsersSchema, UsersSetNewPasswordSchema,
|
||||
};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use surrealdb::Uuid;
|
||||
|
||||
pub struct AuthService;
|
||||
|
||||
impl AuthService {
|
||||
pub async fn mutation_login(
|
||||
payload: AuthLoginRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let user_repo = UsersRepository::new(state);
|
||||
let auth_repo = AuthRepository::new(state);
|
||||
let role_repo = RolesRepository::new(state);
|
||||
|
||||
match user_repo.query_user_by_email(payload.email.clone()).await {
|
||||
Ok(user) => {
|
||||
let is_password_correct =
|
||||
verify_password(&payload.password, &user.password).unwrap_or(false);
|
||||
|
||||
if !is_password_correct {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Email or password not correct",
|
||||
);
|
||||
}
|
||||
|
||||
if !user.is_active {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Account not active, please verify your email",
|
||||
);
|
||||
}
|
||||
|
||||
let access_token = match encode_access_token(payload.email.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate access token",
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let refresh_token = match encode_refresh_token(payload.email.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate refresh token",
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let role_response = role_repo
|
||||
.query_role_by_id(user.role.id.id.to_raw())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: AuthUserItemDto {
|
||||
id: user.id.id.to_raw(),
|
||||
fullname: user.fullname.clone(),
|
||||
email: user.email.clone(),
|
||||
is_active: user.is_active.clone(),
|
||||
avatar: user.avatar.clone(),
|
||||
phone_number: user.phone_number.clone(),
|
||||
gender: user.gender.clone(),
|
||||
birthdate: user.birthdate.clone(),
|
||||
role: RolesItemDto {
|
||||
id: role_response.id,
|
||||
name: role_response.name,
|
||||
permissions: role_response.permissions,
|
||||
created_at: role_response.created_at,
|
||||
updated_at: role_response.updated_at,
|
||||
},
|
||||
},
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if let Err(_err) = auth_repo.query_store_user(user).await {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User already login");
|
||||
}
|
||||
|
||||
success_response(response)
|
||||
}
|
||||
Err(err) => common_response(StatusCode::UNAUTHORIZED, &err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_register(
|
||||
payload: AuthRegisterRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(state);
|
||||
let auth_repo = AuthRepository::new(state);
|
||||
let role_repo = RolesRepository::new(state);
|
||||
let role = match role_repo
|
||||
.query_role_by_name(RolesEnum::User.to_string())
|
||||
.await
|
||||
{
|
||||
Ok(role) => role,
|
||||
Err(_) => return common_response(StatusCode::BAD_REQUEST, "Role Not Found"),
|
||||
};
|
||||
if user_repo
|
||||
.query_user_by_email(payload.email.clone())
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return common_response(StatusCode::BAD_REQUEST, "User already exists");
|
||||
}
|
||||
let hashed_password = match hash_password(&payload.password) {
|
||||
Ok(hash) => hash,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to hash password",
|
||||
);
|
||||
}
|
||||
};
|
||||
let new_user = AuthRegisterRequestDto {
|
||||
email: payload.email,
|
||||
password: hashed_password,
|
||||
fullname: payload.fullname,
|
||||
student_type: payload.student_type,
|
||||
phone_number: payload.phone_number,
|
||||
referral_code: payload.referral_code,
|
||||
referred_by: payload.referred_by,
|
||||
};
|
||||
let otp = generate_otp::OtpManager::generate_otp();
|
||||
match auth_repo
|
||||
.query_store_otp(new_user.email.clone(), otp.clone())
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
let message = format!("your otp code is {}", otp);
|
||||
if let Err(err) = send_email(&new_user.email, "OTP Verification", &message) {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&err.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.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(),
|
||||
);
|
||||
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(),
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
role: role_thing,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(err) => {
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_resend_otp(
|
||||
payload: AuthResendOtpRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let user_repo = UsersRepository::new(state);
|
||||
if user_repo.query_user_by_email(payload.email.clone()).await.is_err() {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User not found");
|
||||
}
|
||||
|
||||
let auth_repo = AuthRepository::new(state);
|
||||
let _ = auth_repo.query_get_stored_otp(payload.email.clone()).await;
|
||||
|
||||
let otp = generate_otp::OtpManager::generate_otp();
|
||||
let message = format!("Your OTP code is {}", otp);
|
||||
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) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
},
|
||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_refresh_token(
|
||||
payload: AuthRefreshTokenRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let email = match decode_refresh_token(&payload.refresh_token) {
|
||||
Ok(token) => token.claims.sub,
|
||||
Err(_) => {
|
||||
return common_response(StatusCode::UNAUTHORIZED, "Invalid refresh token");
|
||||
}
|
||||
};
|
||||
let access_token = match encode_access_token(email.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate access token",
|
||||
);
|
||||
}
|
||||
};
|
||||
let refresh_token = match encode_refresh_token(email.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate refresh token",
|
||||
);
|
||||
}
|
||||
};
|
||||
let response = ResponseSuccessDto {
|
||||
data: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
};
|
||||
success_response(response)
|
||||
}
|
||||
|
||||
pub async fn mutation_forgot_password(
|
||||
payload: AuthResendOtpRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(state);
|
||||
let user_result = user_repo.query_user_by_email(payload.email.clone()).await;
|
||||
let user = match user_result {
|
||||
Ok(user) => user,
|
||||
Err(err) if err.to_string().contains("User not found") => {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User not found")
|
||||
}
|
||||
Err(err) => {
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string())
|
||||
}
|
||||
};
|
||||
let token = match encode_reset_password_token(user.email) {
|
||||
Ok(token) => token,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate access token",
|
||||
)
|
||||
}
|
||||
};
|
||||
let env = Env::new();
|
||||
let fe_url = env.fe_url;
|
||||
let message = format!(
|
||||
"You have requested a password reset. Please click the link below to continue: {}/auth/reset-password?token={}",
|
||||
fe_url, token
|
||||
);
|
||||
match send_email(&payload.email, "Reset Password Request", &message) {
|
||||
Ok(_) => common_response(StatusCode::OK, "Reset Password request send"),
|
||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_verify_email(
|
||||
payload: AuthVerifyEmailRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(state);
|
||||
let auth_repo = AuthRepository::new(state);
|
||||
let email = payload.email.clone();
|
||||
match auth_repo.query_get_stored_otp(email.clone()).await {
|
||||
Ok(stored_otp) => match stored_otp == payload.otp {
|
||||
true => match user_repo
|
||||
.query_active_inactive_user(
|
||||
email.clone(),
|
||||
UsersActiveInactiveSchema { is_active: true },
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => match auth_repo.query_delete_stored_otp(email).await {
|
||||
Ok(_) => common_response(StatusCode::OK, "Email verified successfully"),
|
||||
Err(e) => {
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
}
|
||||
},
|
||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
},
|
||||
false => match auth_repo.query_delete_stored_otp(email).await {
|
||||
Ok(_) => common_response(StatusCode::BAD_REQUEST, "Failed to verify OTP"),
|
||||
Err(e) => common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&format!("Failed to delete OTP: {}", e),
|
||||
),
|
||||
},
|
||||
},
|
||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_new_password(
|
||||
payload: AuthNewPasswordRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(state);
|
||||
let email = match extract_email_token(payload.token.clone()) {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return common_response(StatusCode::BAD_REQUEST, "Invalid or missing token");
|
||||
}
|
||||
};
|
||||
let password = match hash_password(&payload.password) {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to hash password",
|
||||
);
|
||||
}
|
||||
};
|
||||
match user_repo
|
||||
.query_update_password_user(email, UsersSetNewPasswordSchema { password })
|
||||
.await
|
||||
{
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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 use auth_dto::*;
|
||||
pub use auth_repository::*;
|
||||
pub use auth_schema::*;
|
||||
pub use auth_service::*;
|
||||
|
||||
pub fn auth_router() -> Router {
|
||||
Router::new()
|
||||
.route("/forgot", post(auth_controller::post_forgot_password))
|
||||
.route("/login", post(auth_controller::post_login))
|
||||
.route("/new-password", post(auth_controller::post_new_password))
|
||||
.route("/refresh", post(auth_controller::post_refresh_token))
|
||||
.route("/register", post(auth_controller::post_register))
|
||||
.route("/send-otp", post(auth_controller::post_resend_otp))
|
||||
.route("/verify-email", post(auth_controller::post_verify_email))
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use axum::Router;
|
||||
|
||||
pub mod auth;
|
||||
pub mod permissions;
|
||||
pub mod roles;
|
||||
pub mod users;
|
||||
|
||||
pub use auth::*;
|
||||
pub use permissions::*;
|
||||
pub use roles::*;
|
||||
pub use users::*;
|
||||
|
||||
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("/roles", roles_router())
|
||||
.nest("/permissions", permissions_router())
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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;
|
||||
|
||||
pub use permissions_controller::*;
|
||||
pub use permissions_dto::*;
|
||||
pub use permissions_enum::*;
|
||||
pub use permissions_guard::*;
|
||||
pub use permissions_repository::*;
|
||||
pub use permissions_schema::*;
|
||||
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use axum::{
|
||||
extract::{Path, Query},
|
||||
response::IntoResponse,
|
||||
Extension, Json,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
v1::{
|
||||
permissions_dto::{PermissionsItemDto, PermissionsRequestDto},
|
||||
permissions_service::PermissionsService,
|
||||
},
|
||||
AppState, MessageResponseDto, MetaRequestDto, ResponseListSuccessDto,
|
||||
ResponseSuccessDto,
|
||||
};
|
||||
|
||||
use super::{permissions_guard, PermissionsEnum};
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/v1/permissions",
|
||||
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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadListPermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadDetailPermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::CreatePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => PermissionsService::create_role(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/update/{id}",
|
||||
request_body = PermissionsRequestDto,
|
||||
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<PermissionsRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::UpdatePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::DeletePermissions],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => PermissionsService::delete_permission(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
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)]
|
||||
pub struct PermissionsItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct PermissionsQueryDto {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PermissionsEnum {
|
||||
ReadListUsers,
|
||||
ReadDetailUsers,
|
||||
CreateUsers,
|
||||
DeleteUsers,
|
||||
UpdateUsers,
|
||||
ReadListRoles,
|
||||
ReadDetailRoles,
|
||||
CreateRoles,
|
||||
DeleteRoles,
|
||||
UpdateRoles,
|
||||
ReadListPermissions,
|
||||
ReadDetailPermissions,
|
||||
CreatePermissions,
|
||||
DeletePermissions,
|
||||
UpdatePermissions,
|
||||
}
|
||||
|
||||
impl fmt::Display for PermissionsEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let permission_str = match self {
|
||||
PermissionsEnum::ReadListUsers => "Read List Users",
|
||||
PermissionsEnum::ReadDetailUsers => "Read Detail Users",
|
||||
PermissionsEnum::CreateUsers => "Create Users",
|
||||
PermissionsEnum::DeleteUsers => "Delete Users",
|
||||
PermissionsEnum::UpdateUsers => "Update Users",
|
||||
PermissionsEnum::ReadListRoles => "Read List Roles",
|
||||
PermissionsEnum::ReadDetailRoles => "Read Detail Roles",
|
||||
PermissionsEnum::CreateRoles => "Create Roles",
|
||||
PermissionsEnum::DeleteRoles => "Delete Roles",
|
||||
PermissionsEnum::UpdateRoles => "Update Roles",
|
||||
PermissionsEnum::ReadListPermissions => "Read List Permissions",
|
||||
PermissionsEnum::ReadDetailPermissions => "Read Detail Permissions",
|
||||
PermissionsEnum::CreatePermissions => "Create Permissions",
|
||||
PermissionsEnum::DeletePermissions => "Delete Permissions",
|
||||
PermissionsEnum::UpdatePermissions => "Update Permissions",
|
||||
};
|
||||
write!(f, "{}", permission_str)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use super::PermissionsEnum;
|
||||
use crate::{common_response, extract_email, AppState, AuthRepository};
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
|
||||
pub async fn permissions_guard(
|
||||
headers: &HeaderMap,
|
||||
state: AppState,
|
||||
required_permissions: Vec<PermissionsEnum>,
|
||||
) -> Result<(), Response> {
|
||||
let auth_repo = AuthRepository::new(&state);
|
||||
let email = extract_email(headers).ok_or_else(|| {
|
||||
common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"Invalid or missing authorization token",
|
||||
)
|
||||
})?;
|
||||
let raw_user = auth_repo
|
||||
.query_get_stored_user(email.clone())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
common_response(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"User session expired or not found",
|
||||
)
|
||||
})?;
|
||||
let role = raw_user.role;
|
||||
let role_permissions: Vec<String> =
|
||||
role.permissions.into_iter().map(|perm| perm.name).collect();
|
||||
let has_all_permissions = required_permissions
|
||||
.iter()
|
||||
.all(|required| role_permissions.contains(&required.to_string()));
|
||||
if !has_all_permissions {
|
||||
return Err(common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"You don't have the required permissions",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
use super::{PermissionsItemDto, PermissionsItemDtoRaw, PermissionsSchema};
|
||||
use crate::{
|
||||
get_id, make_thing, query_list_with_meta, AppState, MetaRequestDto, ResourceEnum,
|
||||
ResponseListSuccessDto,
|
||||
};
|
||||
use anyhow::{bail, Result};
|
||||
use imphnen_utils::extract_id;
|
||||
|
||||
pub struct PermissionsRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> PermissionsRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_permission_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<PermissionsItemDto>>> {
|
||||
let mut conditions = vec!["is_deleted = false".into()];
|
||||
if meta.search.is_some() {
|
||||
conditions.push("string::contains(name, $search)".into());
|
||||
}
|
||||
if meta.filter_by.is_some() && meta.filter.is_some() {
|
||||
let filter_by = meta.filter_by.as_ref().unwrap();
|
||||
conditions.push(format!("{} = $filter", filter_by));
|
||||
}
|
||||
let raw_result: ResponseListSuccessDto<Vec<PermissionsItemDtoRaw>> = query_list_with_meta(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Permissions.to_string(),
|
||||
&meta,
|
||||
conditions,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let transformed_data = raw_result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|permission| PermissionsItemDto {
|
||||
id: extract_id(&permission.id),
|
||||
name: permission.name,
|
||||
created_at: permission.created_at,
|
||||
updated_at: permission.updated_at,
|
||||
})
|
||||
.collect();
|
||||
Ok(ResponseListSuccessDto {
|
||||
data: transformed_data,
|
||||
meta: raw_result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_permission_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<PermissionsSchema> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let result: Option<PermissionsSchema> = db
|
||||
.select((ResourceEnum::Permissions.to_string(), id.clone()))
|
||||
.await?;
|
||||
match result {
|
||||
Some(permission) if !permission.is_deleted => Ok(permission),
|
||||
_ => bail!("Permission not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn transformed_query_permission_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<PermissionsItemDto> {
|
||||
let raw_result = self
|
||||
.query_permission_by_id(id.clone())
|
||||
.await?;
|
||||
let transformed_data = PermissionsItemDto {
|
||||
id: extract_id(&raw_result.id),
|
||||
name: raw_result.name,
|
||||
created_at: raw_result.created_at,
|
||||
updated_at: raw_result.updated_at,
|
||||
};
|
||||
Ok(transformed_data)
|
||||
}
|
||||
|
||||
|
||||
pub async fn query_permission_by_name(
|
||||
&self,
|
||||
name: String,
|
||||
) -> Result<PermissionsSchema> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let sql = format!(
|
||||
"SELECT * FROM {} WHERE name = $name AND is_deleted = false",
|
||||
ResourceEnum::Permissions.to_string()
|
||||
);
|
||||
let result: Vec<PermissionsSchema> =
|
||||
db.query(sql).bind(("name", name.clone())).await?.take(0)?;
|
||||
if let Some(permission) = result.into_iter().next() {
|
||||
Ok(permission.into())
|
||||
} else {
|
||||
bail!("Permission not found")
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_create_permission(
|
||||
&self,
|
||||
data: PermissionsSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<PermissionsSchema> = db
|
||||
.create(ResourceEnum::Permissions.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success create permission".into()),
|
||||
None => bail!("Failed to create permission"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_update_permission(
|
||||
&self,
|
||||
data: PermissionsSchema,
|
||||
) -> Result<String> {
|
||||
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?;
|
||||
if existing.is_deleted {
|
||||
bail!("Permission already deleted");
|
||||
}
|
||||
let merged = PermissionsSchema {
|
||||
created_at: existing.created_at,
|
||||
..data.clone()
|
||||
};
|
||||
let record: Option<PermissionsSchema> =
|
||||
db.update(record_key).merge(merged).await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update permission".into()),
|
||||
None => bail!("Failed to update permission"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_permission(&self, id: String) -> Result<String> {
|
||||
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)?;
|
||||
let record: Option<PermissionsSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete permission".into()),
|
||||
None => bail!("Failed to delete permission"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
use crate::{make_thing, ResourceEnum};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{sql::Thing, Uuid};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct PermissionsSchema {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for PermissionsSchema {
|
||||
fn default() -> Self {
|
||||
PermissionsSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::Permissions.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
name: String::new(),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use crate::{
|
||||
common_response, make_thing, success_list_response, success_response,
|
||||
validate_request, AppState, MetaRequestDto, PermissionsRepository,
|
||||
PermissionsSchema, ResourceEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::Response;
|
||||
|
||||
use super::PermissionsRequestDto;
|
||||
|
||||
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: PermissionsRequestDto,
|
||||
id: String,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = PermissionsRepository::new(state);
|
||||
match repo
|
||||
.query_update_permission(PermissionsSchema {
|
||||
id: make_thing(&ResourceEnum::Permissions.to_string(), &id),
|
||||
name: payload.name,
|
||||
..Default::default()
|
||||
})
|
||||
.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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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;
|
||||
|
||||
pub use roles_controller::*;
|
||||
pub use roles_dto::*;
|
||||
pub use roles_enum::*;
|
||||
pub use roles_repository::*;
|
||||
pub use roles_schema::*;
|
||||
pub use roles_service::*;
|
||||
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use axum::{
|
||||
extract::{Path, Query},
|
||||
response::IntoResponse,
|
||||
Extension, Json,
|
||||
};
|
||||
|
||||
use super::{RolesItemDto, RolesRequestCreateDto, RolesRequestUpdateDto};
|
||||
use crate::{
|
||||
permissions_guard, v1::roles_service::RolesService, AppState, MessageResponseDto,
|
||||
MetaRequestDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
|
||||
#[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<RolesItemDto>>)
|
||||
),
|
||||
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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadListRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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<RolesItemDto>)
|
||||
),
|
||||
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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadDetailRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::CreateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::UpdateRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::DeleteRoles],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => RolesService::delete_role(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
use crate::{PermissionsItemDto, PermissionsQueryDto};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct RolesRequestDto {
|
||||
#[validate(length(min = 1, message = "Role name must not be empty"))]
|
||||
pub name: String,
|
||||
pub permissions: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct RolesListItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub permissions_count: u64,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct RolesDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub permissions: Vec<PermissionsItemDto>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RolesDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub permissions: Vec<PermissionsQueryDto>,
|
||||
pub is_deleted: bool,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RolesEnum {
|
||||
Admin,
|
||||
User,
|
||||
Student,
|
||||
Staf,
|
||||
}
|
||||
|
||||
impl fmt::Display for RolesEnum {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let roles_str = match self {
|
||||
RolesEnum::Admin => "Admin",
|
||||
RolesEnum::User => "User",
|
||||
RolesEnum::Student => "Student",
|
||||
RolesEnum::Staf => "Staf",
|
||||
};
|
||||
write!(f, "{}", roles_str)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use super::{
|
||||
RolesItemByIdDto, RolesItemByIdDtoRaw, RolesItemDto, RolesItemDtoRaw, RolesRequestCreateDto, RolesRequestUpdateDto, RolesSchema
|
||||
};
|
||||
use crate::{
|
||||
extract_id, get_id, make_thing, query_list_with_meta, AppState, MetaRequestDto,
|
||||
PermissionsItemDto, ResourceEnum, ResponseListSuccessDto,
|
||||
};
|
||||
use anyhow::{bail, Result};
|
||||
use surrealdb::sql::Thing;
|
||||
use surrealdb::Uuid;
|
||||
|
||||
pub struct RolesRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
impl<'a> RolesRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
pub async fn query_raw_role_by_id(&self, id: &str) -> Result<RolesSchema> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let role: Option<RolesSchema> =
|
||||
db.select((ResourceEnum::Roles.to_string(), id)).await?;
|
||||
match role {
|
||||
Some(r) if !r.is_deleted => Ok(r),
|
||||
_ => bail!("Role not found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_role_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<RolesItemDto>>> {
|
||||
let mut conditions = vec!["is_deleted = false".into()];
|
||||
if meta.search.is_some() {
|
||||
conditions.push("string::contains(name, $search)".into());
|
||||
}
|
||||
if meta.filter_by.is_some() && meta.filter.is_some() {
|
||||
let filter_by = meta.filter_by.as_ref().unwrap();
|
||||
conditions.push(format!("{} = $filter", filter_by));
|
||||
}
|
||||
let raw_result: ResponseListSuccessDto<Vec<RolesItemDtoRaw>> = query_list_with_meta(
|
||||
&self.state.surrealdb_ws,
|
||||
&ResourceEnum::Roles.to_string(),
|
||||
&meta,
|
||||
conditions,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let transformed_data = raw_result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|role| {
|
||||
RolesItemDto {
|
||||
name: role.name,
|
||||
created_at: role.created_at,
|
||||
updated_at: role.updated_at,
|
||||
permissions: role.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDto {
|
||||
id: extract_id(&perm.id),
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
id: extract_id(&role.id),
|
||||
|
||||
}
|
||||
})
|
||||
.collect::<Vec<RolesItemDto>>();
|
||||
let transformed_meta = raw_result.meta;
|
||||
Ok(ResponseListSuccessDto {
|
||||
data: transformed_data,
|
||||
meta: transformed_meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_role_by_name(&self, name: String) -> Result<RolesItemByIdDto> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let sql = format!(
|
||||
"SELECT *, permissions FROM {} WHERE name = $name AND is_deleted = false LIMIT 1 FETCH permissions",
|
||||
ResourceEnum::Roles.to_string()
|
||||
);
|
||||
let mut result = db.query(sql).bind(("name", name.clone())).await?;
|
||||
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
|
||||
let role = match role {
|
||||
Some(r) if !r.is_deleted => r,
|
||||
_ => bail!("Role not found"),
|
||||
};
|
||||
let permissions = role
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDto {
|
||||
id: extract_id(&perm.id),
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(RolesItemByIdDto {
|
||||
id: extract_id(&role.id),
|
||||
name: role.name,
|
||||
is_deleted: role.is_deleted,
|
||||
permissions,
|
||||
created_at: role.created_at,
|
||||
updated_at: role.updated_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_role_by_id(&self, id: String) -> Result<RolesItemByIdDto> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let query = format!(
|
||||
"SELECT *, permissions.* AS permissions
|
||||
FROM app_roles:⟨{}⟩ WHERE is_deleted = false FETCH permissions",
|
||||
id
|
||||
);
|
||||
let mut result = db.query(query).await?;
|
||||
let role: Option<RolesItemByIdDtoRaw> = result.take(0)?;
|
||||
let role = match role {
|
||||
Some(r) if !r.is_deleted => r,
|
||||
_ => bail!("Role not found"),
|
||||
};
|
||||
let permissions = role
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDto {
|
||||
id: extract_id(&perm.id),
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
Ok(RolesItemByIdDto {
|
||||
id: extract_id(&role.id),
|
||||
name: role.name,
|
||||
is_deleted: role.is_deleted,
|
||||
permissions,
|
||||
created_at: role.created_at,
|
||||
updated_at: role.updated_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_create_role(
|
||||
&self,
|
||||
payload: RolesRequestCreateDto,
|
||||
) -> Result<String> {
|
||||
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))
|
||||
.content(role)
|
||||
.await?;
|
||||
|
||||
Ok("Role with permissions created successfully".into())
|
||||
}
|
||||
|
||||
pub async fn query_update_role(
|
||||
&self,
|
||||
id: String,
|
||||
data: RolesRequestUpdateDto,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let thing_id = make_thing(&ResourceEnum::Roles.to_string(), &id);
|
||||
let existing = self.query_raw_role_by_id(&id).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("Role already deleted");
|
||||
}
|
||||
let permissions: Vec<Thing> = if let Some(permission_ids) = &data.permissions {
|
||||
permission_ids
|
||||
.iter()
|
||||
.map(|id| make_thing(&ResourceEnum::Permissions.to_string(), id))
|
||||
.collect()
|
||||
} else {
|
||||
existing
|
||||
.permissions
|
||||
.iter()
|
||||
.map(|p| make_thing(&ResourceEnum::Permissions.to_string(), &p.id.to_raw()))
|
||||
.collect()
|
||||
};
|
||||
let merged = RolesSchema {
|
||||
id: thing_id,
|
||||
name: data.name.unwrap_or(existing.name),
|
||||
permissions,
|
||||
is_deleted: existing.is_deleted,
|
||||
created_at: existing.created_at,
|
||||
updated_at: Some(crate::get_iso_date()),
|
||||
};
|
||||
let record: Option<RolesSchema> =
|
||||
db.update(get_id(&merged.id)?).content(merged).await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update role".into()),
|
||||
None => bail!("Failed to update role"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_role(&self, id: String) -> Result<String> {
|
||||
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?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete role".into()),
|
||||
None => bail!("Failed to delete role"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::{sql::Thing, Uuid};
|
||||
|
||||
use crate::{make_thing, ResourceEnum};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct RolesSchema {
|
||||
pub id: Thing,
|
||||
pub name: String,
|
||||
pub is_deleted: bool,
|
||||
pub permissions: Vec<Thing>,
|
||||
pub created_at: Option<String>,
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for RolesSchema {
|
||||
fn default() -> Self {
|
||||
RolesSchema {
|
||||
id: make_thing(
|
||||
&ResourceEnum::Roles.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
),
|
||||
permissions: vec![make_thing(
|
||||
&ResourceEnum::Permissions.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
)],
|
||||
name: String::new(),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use super::{RolesRepository, RolesRequestCreateDto, RolesRequestUpdateDto};
|
||||
use crate::{
|
||||
common_response, success_list_response, success_response, validate_request,
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
};
|
||||
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(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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;
|
||||
|
||||
pub use users_controller::*;
|
||||
pub use users_dto::*;
|
||||
pub use users_repository::*;
|
||||
pub use users_schema::*;
|
||||
pub use users_service::*;
|
||||
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
use axum::extract::{Path, Query};
|
||||
use axum::http::HeaderMap;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, Json};
|
||||
|
||||
use crate::{
|
||||
permissions_guard, MessageResponseDto, PermissionsEnum, ResponseListSuccessDto,
|
||||
ResponseSuccessDto, UsersActiveInactiveRequestDto, UsersCreateRequestDto,
|
||||
UsersDetailItemDto,
|
||||
};
|
||||
use crate::{v1::users_service::UsersService, AppState, MetaRequestDto};
|
||||
|
||||
use super::{UsersListItemDto, UsersUpdateRequestDto};
|
||||
|
||||
#[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 = "Get user list", body = ResponseListSuccessDto<Vec<UsersListItemDto>>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadListUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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 = "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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::ReadDetailUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => UsersService::get_user_by_id(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/me",
|
||||
responses(
|
||||
(status = 200, description = "Get user by ID", body = ResponseSuccessDto<UsersDetailItemDto>)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn get_user_me(
|
||||
Extension(state): Extension<AppState>,
|
||||
headers: HeaderMap,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(&headers, state.clone(), vec![]).await {
|
||||
Ok(_) => UsersService::get_user_me(headers, &state).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/create",
|
||||
request_body = UsersCreateRequestDto,
|
||||
responses(
|
||||
(status = 201, description = "Create new user", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Users"
|
||||
)]
|
||||
pub async fn post_create_user(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<UsersCreateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::CreateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => UsersService::create_user(&state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/update/{id}",
|
||||
request_body = UsersUpdateRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Update user", body = MessageResponseDto)
|
||||
),
|
||||
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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::UpdateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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 = "Update user me", body = MessageResponseDto)
|
||||
),
|
||||
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, state.clone(), vec![]).await {
|
||||
Ok(_) => UsersService::update_user_me(&state, headers, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/activate/{id}",
|
||||
request_body = UsersActiveInactiveRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "Set user active/inactive", 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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::UpdateUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => 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 = "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,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::DeleteUsers],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => UsersService::delete_user(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::{RolesDetailQueryDto, RolesItemDto};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
lazy_static! {
|
||||
static ref PASSWORD_REGEX: Regex = Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct UsersUpdateRequestDto {
|
||||
#[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(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,
|
||||
#[validate(length(min = 1, message = "Gender is required"))]
|
||||
pub gender: Option<String>,
|
||||
#[validate(length(min = 1, message = "Birthdate is required"))]
|
||||
pub birthdate: Option<String>,
|
||||
#[validate(length(min = 1, message = "Avatar is required"))]
|
||||
pub avatar: Option<String>,
|
||||
pub role_id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersDetailItemDto {
|
||||
pub id: String,
|
||||
pub role: RolesItemDto,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub gender: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
#[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,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl UsersListQueryDto {
|
||||
pub fn list_from(&self, role: String) -> UsersListItemDto {
|
||||
UsersListItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
role,
|
||||
fullname: self.fullname.clone(),
|
||||
email: self.email.clone(),
|
||||
avatar: self.avatar.clone(),
|
||||
phone_number: self.phone_number.clone(),
|
||||
is_active: self.is_active,
|
||||
created_at: self.created_at.clone(),
|
||||
updated_at: self.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersDetailQueryDto {
|
||||
pub id: Thing,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub gender: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
pub password: String,
|
||||
pub role: RolesDetailQueryDto,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
use super::{UsersDetailQueryDto, UsersListItemDto, UsersListQueryDto, UsersSchema};
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, PermissionsItemDto, PermissionsItemDtoRaw, ResourceEnum,
|
||||
ResponseListSuccessDto, RolesDetailQueryDto, extract_id, get_id, make_thing,
|
||||
query_list_with_meta,
|
||||
};
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
pub struct UsersRepository<'a> {
|
||||
state: &'a AppState,
|
||||
}
|
||||
|
||||
pub fn build_user_by_field_query(field: &str) -> String {
|
||||
format!(
|
||||
r#"
|
||||
SELECT *, role AS role
|
||||
FROM {}
|
||||
WHERE {} = $value AND is_deleted = false
|
||||
LIMIT 1
|
||||
FETCH role, role.permissions
|
||||
"#,
|
||||
ResourceEnum::Users.to_string(),
|
||||
field
|
||||
)
|
||||
}
|
||||
|
||||
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 db = &self.state.surrealdb_ws;
|
||||
|
||||
let raw_result = query_list_with_meta::<UsersListQueryDto>(
|
||||
db,
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&meta,
|
||||
vec!["is_deleted = false".into()],
|
||||
None,
|
||||
"fullname",
|
||||
Some(vec![
|
||||
"email",
|
||||
"fullname",
|
||||
"id",
|
||||
"is_active",
|
||||
"is_deleted",
|
||||
"role",
|
||||
"role.permissions",
|
||||
]),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let data = raw_result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(|schema| {
|
||||
let role = schema.clone().role.name;
|
||||
schema.list_from(role)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(ResponseListSuccessDto {
|
||||
data,
|
||||
meta: raw_result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_user_by_email(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersDetailQueryDto> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let sql = build_user_by_field_query("email");
|
||||
|
||||
let user_opt: Option<UsersDetailQueryDto> = db
|
||||
.query(sql)
|
||||
.bind(("email", email.clone()))
|
||||
.await?
|
||||
.take(0)?;
|
||||
|
||||
let Some(user) = user_opt else {
|
||||
bail!("User not found");
|
||||
};
|
||||
|
||||
if user.role.is_deleted {
|
||||
bail!("User not found");
|
||||
}
|
||||
|
||||
let permissions = user
|
||||
.role
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDtoRaw {
|
||||
id: perm.id,
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(UsersDetailQueryDto {
|
||||
id: user.id,
|
||||
fullname: user.fullname,
|
||||
email: user.email,
|
||||
avatar: user.avatar,
|
||||
phone_number: user.phone_number,
|
||||
is_active: user.is_active,
|
||||
is_deleted: user.is_deleted,
|
||||
gender: user.gender,
|
||||
birthdate: user.birthdate,
|
||||
password: user.password,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at,
|
||||
role: RolesDetailQueryDto {
|
||||
id: user.role.id,
|
||||
name: user.role.name,
|
||||
created_at: user.role.created_at,
|
||||
updated_at: user.role.updated_at,
|
||||
is_deleted: user.role.is_deleted,
|
||||
permissions,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_user_by_id(&self, id: String) -> Result<UsersDetailQueryDto> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
|
||||
let sql = build_user_by_field_query(&make_thing("app_users", &id).to_raw());
|
||||
|
||||
let user_opt: Option<UsersDetailQueryDto> = db
|
||||
.query(sql)
|
||||
.bind(("email", make_thing("app_users", &id).to_raw()))
|
||||
.await?
|
||||
.take(0)?;
|
||||
|
||||
let Some(user) = user_opt else {
|
||||
bail!("User not found");
|
||||
};
|
||||
|
||||
if user.role.is_deleted {
|
||||
bail!("User not found");
|
||||
}
|
||||
|
||||
let permissions = user
|
||||
.role
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|perm| PermissionsItemDtoRaw {
|
||||
id: perm.id,
|
||||
name: perm.name,
|
||||
created_at: perm.created_at,
|
||||
updated_at: perm.updated_at,
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(UsersDetailQueryDto {
|
||||
id: user.id,
|
||||
fullname: user.fullname,
|
||||
email: user.email,
|
||||
avatar: user.avatar,
|
||||
phone_number: user.phone_number,
|
||||
is_active: user.is_active,
|
||||
is_deleted: user.is_deleted,
|
||||
gender: user.gender,
|
||||
birthdate: user.birthdate,
|
||||
password: user.password,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at,
|
||||
role: RolesDetailQueryDto {
|
||||
id: user.role.id,
|
||||
name: user.role.name,
|
||||
created_at: user.role.created_at,
|
||||
updated_at: user.role.updated_at,
|
||||
is_deleted: user.role.is_deleted,
|
||||
permissions,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_create_user(&self, data: UsersSchema) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<UsersSchema> = db
|
||||
.create(ResourceEnum::Users.to_string())
|
||||
.content(data)
|
||||
.await?;
|
||||
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 db = &self.state.surrealdb_ws;
|
||||
let record_key = get_id(&data.id)?;
|
||||
let existing = self.query_user_by_id(data.id.id.to_raw()).await?;
|
||||
if existing.is_deleted {
|
||||
bail!("User already deleted");
|
||||
}
|
||||
let merged = UsersSchema {
|
||||
password: existing.password,
|
||||
created_at: existing.created_at,
|
||||
role: make_thing("app_roles", &existing.role.id),
|
||||
..data.clone()
|
||||
};
|
||||
let record: Option<UsersSchema> = db.update(record_key).merge(merged).await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update user".into()),
|
||||
None => bail!("Failed to update user"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_active_inactive_user(
|
||||
&self,
|
||||
email: String,
|
||||
data: UsersActiveInactiveSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let user = self.query_user_by_email(email.clone()).await?;
|
||||
if user.is_deleted {
|
||||
bail!("User already deleted");
|
||||
}
|
||||
let record_key = get_id(&user.id)?;
|
||||
let record: Option<UsersSchema> = db
|
||||
.update(record_key)
|
||||
.merge(UsersActiveInactiveSchema {
|
||||
is_active: data.is_active,
|
||||
})
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update user".into()),
|
||||
None => bail!("Failed to update user"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_active_inactive_user_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
data: UsersActiveInactiveSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<UsersSchema> = db
|
||||
.update((ResourceEnum::Users.to_string(), id))
|
||||
.merge(UsersActiveInactiveSchema {
|
||||
is_active: data.is_active,
|
||||
})
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success update user".into()),
|
||||
None => bail!("Failed to update user"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_update_password_user(
|
||||
&self,
|
||||
email: String,
|
||||
data: UsersSetNewPasswordSchema,
|
||||
) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let user = self.query_user_by_email(email).await?;
|
||||
let record: Option<UsersSetNewPasswordSchema> = db
|
||||
.update((ResourceEnum::Users.to_string(), user.id.id.to_raw()))
|
||||
.merge(UsersSetNewPasswordSchema {
|
||||
password: data.password.clone(),
|
||||
})
|
||||
.await?;
|
||||
dbg!(record.clone());
|
||||
match record {
|
||||
Some(_) => Ok("Success update password user".into()),
|
||||
None => bail!("Failed to update password user"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_delete_user(&self, id: String) -> Result<String> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let user_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
||||
let user = self.query_user_by_id(user_id.id.to_raw()).await?;
|
||||
if user.is_deleted {
|
||||
bail!("User already deleted");
|
||||
}
|
||||
let id = make_thing(&ResourceEnum::Users.to_string(), &user.id);
|
||||
let record_key = get_id(&id)?;
|
||||
let record: Option<UsersSchema> = db
|
||||
.update(record_key)
|
||||
.merge(serde_json::json!({ "is_deleted": true }))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete user".into()),
|
||||
None => bail!("Failed to delete user"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
use super::{UsersDetailItemDto, UsersListItemDto};
|
||||
use crate::RolesItemDto;
|
||||
use imphnen_utils::Crud;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UsersSchema {
|
||||
pub id: Thing,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub password: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
pub is_deleted: bool,
|
||||
pub gender: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
pub role: Thing,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl Crud<UsersListItemDto, String> for UsersSchema {
|
||||
fn list(&self, role: String) -> UsersListItemDto {
|
||||
UsersListItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
role,
|
||||
fullname: self.fullname.clone(),
|
||||
email: self.email.clone(),
|
||||
avatar: self.avatar.clone(),
|
||||
phone_number: self.phone_number.clone(),
|
||||
is_active: self.is_active,
|
||||
created_at: self.created_at.clone(),
|
||||
updated_at: self.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Crud<UsersDetailItemDto, RolesItemDto> for UsersSchema {
|
||||
fn detail(&self, role: RolesItemDto) -> UsersDetailItemDto {
|
||||
UsersDetailItemDto {
|
||||
id: self.id.id.to_raw(),
|
||||
role,
|
||||
fullname: self.fullname.clone(),
|
||||
email: self.email.clone(),
|
||||
avatar: self.avatar.clone(),
|
||||
phone_number: self.phone_number.clone(),
|
||||
is_active: self.is_active,
|
||||
gender: self.gender.clone(),
|
||||
birthdate: self.birthdate.clone(),
|
||||
created_at: self.created_at.clone(),
|
||||
updated_at: self.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UsersSchema {
|
||||
pub fn list_from(&self, role: String) -> UsersListItemDto {
|
||||
self.list(role)
|
||||
}
|
||||
|
||||
pub fn detail_from(&self, role: RolesItemDto) -> UsersDetailItemDto {
|
||||
self.detail(role)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
use crate::{
|
||||
common_response, extract_email, get_iso_date, hash_password, make_thing,
|
||||
success_list_response, success_response, validate_request, ResourceEnum,
|
||||
ResponseSuccessDto,
|
||||
};
|
||||
use crate::{
|
||||
AppState, MetaRequestDto, ResponseListSuccessDto, UsersActiveInactiveSchema,
|
||||
UsersRepository, UsersSchema, UsersSetNewPasswordSchema,
|
||||
};
|
||||
use axum::http::HeaderMap;
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
|
||||
use super::{
|
||||
UsersActiveInactiveRequestDto, UsersCreateRequestDto, UsersDetailItemDto,
|
||||
UsersUpdateRequestDto,
|
||||
};
|
||||
|
||||
pub struct UsersService;
|
||||
|
||||
impl UsersService {
|
||||
pub async fn get_user_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
match repo.query_user_list(meta).await {
|
||||
Ok(data) => {
|
||||
let response = ResponseListSuccessDto {
|
||||
data: data.data,
|
||||
meta: data.meta,
|
||||
};
|
||||
success_list_response(response)
|
||||
}
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_user_by_id(state: &AppState, id: String) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
match repo.query_user_by_id(id).await {
|
||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: UsersDetailItemDto {
|
||||
id: user.id,
|
||||
role: user.role,
|
||||
fullname: user.fullname,
|
||||
email: user.email,
|
||||
avatar: user.avatar,
|
||||
phone_number: user.phone_number,
|
||||
is_active: user.is_active,
|
||||
gender: user.gender,
|
||||
birthdate: user.birthdate,
|
||||
},
|
||||
}),
|
||||
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_user_me(headers: HeaderMap, state: &AppState) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
let email = extract_email(&headers).unwrap();
|
||||
let user = repo.query_user_by_email(email).await.unwrap();
|
||||
match repo.query_user_by_id(user.id.id.to_raw()).await {
|
||||
Ok(user) => success_response(ResponseSuccessDto {
|
||||
data: UsersDetailItemDto {
|
||||
id: user.id,
|
||||
role: user.role,
|
||||
fullname: user.fullname,
|
||||
email: user.email,
|
||||
avatar: user.avatar,
|
||||
phone_number: user.phone_number,
|
||||
is_active: user.is_active,
|
||||
gender: user.gender,
|
||||
birthdate: user.birthdate,
|
||||
},
|
||||
}),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_user(
|
||||
state: &AppState,
|
||||
new_user: UsersCreateRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&new_user) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = UsersRepository::new(state);
|
||||
if repo
|
||||
.query_user_by_email(new_user.email.clone())
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
return common_response(StatusCode::BAD_REQUEST, "User already exists");
|
||||
}
|
||||
let role_thing = make_thing(&ResourceEnum::Roles.to_string(), &new_user.role_id);
|
||||
match repo
|
||||
.query_create_user(UsersSchema {
|
||||
email: new_user.email.clone(),
|
||||
fullname: new_user.fullname.clone(),
|
||||
password: hash_password(&new_user.password).unwrap(),
|
||||
phone_number: new_user.phone_number.clone(),
|
||||
is_active: new_user.is_active.clone(),
|
||||
role: role_thing,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(msg) => common_response(StatusCode::CREATED, &msg),
|
||||
Err(err) => {
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &err.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_user(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
user: UsersUpdateRequestDto,
|
||||
) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
|
||||
if let Err((status, message)) = validate_request(&user) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
|
||||
let user_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
||||
let role_id = make_thing(&ResourceEnum::Roles.to_string(), "");
|
||||
|
||||
let updated_user = UsersSchema {
|
||||
id: user_id,
|
||||
fullname: user.fullname,
|
||||
email: user.email,
|
||||
phone_number: user.phone_number,
|
||||
is_active: user.is_active,
|
||||
gender: user.gender,
|
||||
birthdate: user.birthdate,
|
||||
avatar: user.avatar,
|
||||
role: role_id,
|
||||
updated_at: get_iso_date(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
match repo.query_update_user(updated_user).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_user_me(
|
||||
state: &AppState,
|
||||
headers: HeaderMap,
|
||||
user: UsersUpdateRequestDto,
|
||||
) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
let email = extract_email(&headers).unwrap();
|
||||
let user_data = repo.query_user_by_email(email).await.unwrap();
|
||||
if let Err((status, message)) = validate_request(&user) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_id =
|
||||
make_thing(&ResourceEnum::Users.to_string(), &user_data.id.id.to_raw());
|
||||
let role_id = make_thing(&ResourceEnum::Roles.to_string(), "");
|
||||
let updated_user = UsersSchema {
|
||||
id: user_id,
|
||||
fullname: user.fullname,
|
||||
email: user.email,
|
||||
phone_number: user.phone_number,
|
||||
|
||||
is_active: user.is_active,
|
||||
|
||||
gender: user.gender,
|
||||
birthdate: user.birthdate,
|
||||
avatar: user.avatar,
|
||||
|
||||
role: role_id,
|
||||
updated_at: get_iso_date(),
|
||||
..Default::default()
|
||||
};
|
||||
match repo.query_update_user(updated_user).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn set_user_active_status(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
status: UsersActiveInactiveRequestDto,
|
||||
) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
let thing_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
||||
match repo.query_user_by_id(thing_id.id.to_raw()).await {
|
||||
Ok(_) => match repo
|
||||
.query_active_inactive_user_by_id(
|
||||
id,
|
||||
UsersActiveInactiveSchema {
|
||||
is_active: status.is_active,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
},
|
||||
Err(err) => common_response(StatusCode::BAD_REQUEST, &err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_user_password(
|
||||
state: &AppState,
|
||||
email: String,
|
||||
new_password: UsersSetNewPasswordSchema,
|
||||
) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
match repo.query_update_password_user(email, new_password).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_user(state: &AppState, id: String) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
if repo.query_user_by_id(id.clone()).await.is_err() {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User not found");
|
||||
}
|
||||
match repo.query_delete_user(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user