feat: pagination
This commit is contained in:
@@ -19,6 +19,12 @@ impl<'a> AuthRepository<'a> {
|
||||
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<UsersSchema>>((table.clone(), user_id.clone()))
|
||||
.await?;
|
||||
|
||||
let mut user_to_store = user.clone();
|
||||
user_to_store.id = id.clone();
|
||||
let record: Option<UsersSchema> = self
|
||||
|
||||
@@ -8,8 +8,8 @@ use crate::{
|
||||
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,
|
||||
RolesRepository, UsersActiveInactiveSchema, UsersItemDto, UsersRepository,
|
||||
UsersSchema, UsersSetNewPasswordSchema,
|
||||
RolesItemDto, RolesRepository, UsersActiveInactiveSchema, UsersItemDto,
|
||||
UsersRepository, UsersSchema, UsersSetNewPasswordSchema,
|
||||
};
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use surrealdb::Uuid;
|
||||
@@ -27,6 +27,7 @@ impl AuthService {
|
||||
|
||||
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) => {
|
||||
@@ -67,6 +68,11 @@ impl AuthService {
|
||||
}
|
||||
};
|
||||
|
||||
let role_response = role_repo
|
||||
.query_role_by_id(user.role.id.to_raw())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersItemDto {
|
||||
@@ -84,6 +90,14 @@ impl AuthService {
|
||||
gender: user.gender.clone(),
|
||||
birthdate: user.birthdate.clone(),
|
||||
is_profile_completed: user.is_profile_completed.clone(),
|
||||
role: RolesItemDto {
|
||||
id: role_response.id,
|
||||
name: role_response.name,
|
||||
is_deleted: role_response.is_deleted,
|
||||
permissions: vec![],
|
||||
created_at: role_response.created_at,
|
||||
updated_at: role_response.updated_at,
|
||||
},
|
||||
},
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
@@ -92,8 +106,8 @@ impl AuthService {
|
||||
},
|
||||
};
|
||||
|
||||
if let Err(err) = auth_repo.query_store_user(user).await {
|
||||
return common_response(StatusCode::BAD_REQUEST, &err.to_string());
|
||||
if let Err(_err) = auth_repo.query_store_user(user).await {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User already login");
|
||||
}
|
||||
|
||||
success_response(response)
|
||||
@@ -109,16 +123,16 @@ impl AuthService {
|
||||
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 = role_repo
|
||||
let role = match role_repo
|
||||
.query_role_by_name(RolesEnum::Student.to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
Ok(role) => role,
|
||||
Err(_) => return common_response(StatusCode::BAD_REQUEST, "Role Not Found"),
|
||||
};
|
||||
if user_repo
|
||||
.query_user_by_email(payload.email.clone())
|
||||
.await
|
||||
@@ -126,7 +140,6 @@ impl AuthService {
|
||||
{
|
||||
return common_response(StatusCode::BAD_REQUEST, "User already exists");
|
||||
}
|
||||
|
||||
let hashed_password = match hash_password(&payload.password) {
|
||||
Ok(hash) => hash,
|
||||
Err(_) => {
|
||||
@@ -136,7 +149,6 @@ impl AuthService {
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let new_user = AuthRegisterRequestDto {
|
||||
email: payload.email,
|
||||
password: hashed_password,
|
||||
@@ -146,9 +158,7 @@ impl AuthService {
|
||||
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
|
||||
@@ -166,13 +176,11 @@ impl AuthService {
|
||||
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,
|
||||
@@ -186,8 +194,6 @@ impl AuthService {
|
||||
created_at: Some(get_iso_date()),
|
||||
updated_at: Some(get_iso_date()),
|
||||
role: role_thing,
|
||||
is_active: false,
|
||||
is_profile_completed: false,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
@@ -230,7 +236,6 @@ impl AuthService {
|
||||
return common_response(StatusCode::UNAUTHORIZED, "Invalid refresh token");
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = match encode_access_token(email.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_) => {
|
||||
@@ -240,7 +245,6 @@ impl AuthService {
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let refresh_token = match encode_refresh_token(email.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_) => {
|
||||
@@ -250,14 +254,12 @@ impl AuthService {
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let response = ResponseSuccessDto {
|
||||
data: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
};
|
||||
|
||||
success_response(response)
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,9 @@ pub async fn get_permission_list(
|
||||
#[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>)
|
||||
@@ -55,6 +58,9 @@ pub async fn get_permission_by_id(
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/create",
|
||||
request_body = PermissionsRequestDto,
|
||||
responses(
|
||||
@@ -71,6 +77,9 @@ pub async fn post_create_permission(
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/update/{id}",
|
||||
request_body = PermissionsRequestDto,
|
||||
responses(
|
||||
@@ -88,6 +97,9 @@ pub async fn put_update_permission(
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/permissions/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Delete permission", body = MessageResponseDto)
|
||||
|
||||
@@ -31,6 +31,7 @@ impl<'a> PermissionsRepository<'a> {
|
||||
&ResourceEnum::Permissions.to_string(),
|
||||
&meta,
|
||||
conditions,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ use crate::{
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
@@ -36,6 +39,9 @@ pub async fn get_role_list(
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/detail/{id}",
|
||||
params(("id" = String, Path, description = "Role ID")),
|
||||
responses(
|
||||
@@ -52,6 +58,9 @@ pub async fn get_role_by_id(
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/create",
|
||||
request_body = RolesRequestCreateDto,
|
||||
responses(
|
||||
@@ -68,6 +77,9 @@ pub async fn post_create_role(
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/update/{id}",
|
||||
request_body = RolesRequestUpdateDto,
|
||||
responses(
|
||||
@@ -85,6 +97,9 @@ pub async fn put_update_role(
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/roles/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Delete role", body = MessageResponseDto)
|
||||
|
||||
@@ -45,6 +45,7 @@ impl<'a> RolesRepository<'a> {
|
||||
&ResourceEnum::Roles.to_string(),
|
||||
&meta,
|
||||
conditions,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -12,6 +12,9 @@ use super::UsersUpdateRequestDto;
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users",
|
||||
params(
|
||||
("page" = Option<i64>, Query, description = "Page number"),
|
||||
@@ -36,6 +39,9 @@ pub async fn get_user_list(
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/detail/{id}",
|
||||
params(
|
||||
("id" = String, Path, description = "User ID")
|
||||
@@ -54,6 +60,9 @@ pub async fn get_user_by_id(
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/create",
|
||||
request_body = UsersCreateRequestDto,
|
||||
responses(
|
||||
@@ -70,6 +79,9 @@ pub async fn post_create_user(
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/update/{id}",
|
||||
request_body = UsersCreateRequestDto,
|
||||
responses(
|
||||
@@ -87,6 +99,9 @@ pub async fn put_update_user(
|
||||
|
||||
#[utoipa::path(
|
||||
put,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/activate/{id}",
|
||||
request_body = UsersActiveInactiveRequestDto,
|
||||
responses(
|
||||
@@ -104,6 +119,9 @@ pub async fn patch_user_active_status(
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
path = "/v1/users/delete/{id}",
|
||||
responses(
|
||||
(status = 200, description = "Soft delete user", body = MessageResponseDto)
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
|
||||
use crate::RolesItemDto;
|
||||
|
||||
lazy_static! {
|
||||
static ref PASSWORD_REGEX: Regex = Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
|
||||
}
|
||||
@@ -82,6 +85,7 @@ pub struct UsersUpdateRequestDto {
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersItemDto {
|
||||
pub id: String,
|
||||
pub role: RolesItemDto,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
@@ -97,6 +101,54 @@ pub struct UsersItemDto {
|
||||
pub birthdate: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct UsersItemDtoRaw {
|
||||
pub id: Thing,
|
||||
pub role: Thing,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub referred_by: Option<String>,
|
||||
pub referral_code: Option<String>,
|
||||
pub student_type: String,
|
||||
pub is_active: bool,
|
||||
pub is_profile_completed: bool,
|
||||
pub identity_number: Option<String>,
|
||||
pub religion: Option<String>,
|
||||
pub gender: Option<String>,
|
||||
pub birthdate: Option<String>,
|
||||
}
|
||||
|
||||
impl From<UsersItemDtoRaw> for UsersItemDto {
|
||||
fn from(raw: UsersItemDtoRaw) -> Self {
|
||||
Self {
|
||||
id: raw.id.id.to_string(),
|
||||
role: RolesItemDto {
|
||||
id: raw.role.id.to_string(),
|
||||
name: "".into(),
|
||||
is_deleted: false,
|
||||
permissions: vec![],
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
},
|
||||
fullname: raw.fullname,
|
||||
email: raw.email,
|
||||
avatar: raw.avatar,
|
||||
phone_number: raw.phone_number,
|
||||
referred_by: raw.referred_by,
|
||||
referral_code: raw.referral_code,
|
||||
student_type: raw.student_type,
|
||||
is_active: raw.is_active,
|
||||
is_profile_completed: raw.is_profile_completed,
|
||||
identity_number: raw.identity_number,
|
||||
religion: raw.religion,
|
||||
gender: raw.gender,
|
||||
birthdate: raw.birthdate,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct UsersActiveInactiveRequestDto {
|
||||
pub is_active: bool,
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use super::{UsersActiveInactiveSchema, UsersSchema, UsersSetNewPasswordSchema};
|
||||
use super::{
|
||||
UsersActiveInactiveSchema, UsersItemDto, UsersItemDtoRaw, UsersSchema,
|
||||
UsersSetNewPasswordSchema,
|
||||
};
|
||||
use crate::{
|
||||
get_id, make_thing, query_list_with_meta, AppState, MetaRequestDto, ResourceEnum,
|
||||
ResponseListSuccessDto,
|
||||
@@ -17,20 +20,80 @@ impl<'a> UsersRepository<'a> {
|
||||
pub async fn query_user_list(
|
||||
&self,
|
||||
meta: MetaRequestDto,
|
||||
) -> Result<ResponseListSuccessDto<Vec<UsersSchema>>> {
|
||||
) -> Result<ResponseListSuccessDto<Vec<UsersItemDto>>> {
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let table = ResourceEnum::Users.to_string();
|
||||
|
||||
let mut conditions = vec!["is_deleted = false".to_string()];
|
||||
if let Some(search) = &meta.search {
|
||||
|
||||
if let Some(search) = meta.search.as_deref() {
|
||||
if !search.is_empty() {
|
||||
conditions.push("string::contains(fullname ?? '', $search)".to_string());
|
||||
}
|
||||
}
|
||||
if meta.filter_by.is_some() && meta.filter.is_some() {
|
||||
let filter_by = meta.filter_by.as_ref().unwrap();
|
||||
|
||||
if let (Some(filter_by), Some(_filter)) =
|
||||
(meta.filter_by.as_ref(), meta.filter.as_ref())
|
||||
{
|
||||
conditions.push(format!("{} = $filter", filter_by));
|
||||
}
|
||||
query_list_with_meta::<UsersSchema>(db, &table, &meta, conditions).await
|
||||
|
||||
let where_clause = if !conditions.is_empty() {
|
||||
format!("WHERE {}", conditions.join(" AND "))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let limit = meta.per_page.unwrap_or(10);
|
||||
let start = (meta.page.unwrap_or(1) - 1) * limit;
|
||||
|
||||
let select_query = format!(
|
||||
"
|
||||
SELECT
|
||||
id,
|
||||
role,
|
||||
fullname,
|
||||
email,
|
||||
avatar,
|
||||
phone_number,
|
||||
referred_by,
|
||||
referral_code,
|
||||
student_type,
|
||||
is_active,
|
||||
is_profile_completed,
|
||||
identity_number,
|
||||
religion,
|
||||
gender,
|
||||
birthdate
|
||||
FROM {}
|
||||
{}
|
||||
LIMIT {} START {}
|
||||
FETCH role, role.permissions
|
||||
",
|
||||
ResourceEnum::Users.to_string(),
|
||||
where_clause,
|
||||
limit,
|
||||
start
|
||||
);
|
||||
|
||||
let raw_result = query_list_with_meta::<UsersItemDtoRaw>(
|
||||
db,
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&meta,
|
||||
vec![],
|
||||
Some(select_query),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let converted = raw_result
|
||||
.data
|
||||
.into_iter()
|
||||
.map(UsersItemDto::from)
|
||||
.collect();
|
||||
|
||||
Ok(ResponseListSuccessDto {
|
||||
data: converted,
|
||||
meta: raw_result.meta,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn query_user_by_email(&self, email: String) -> Result<UsersSchema> {
|
||||
|
||||
Reference in New Issue
Block a user