chore: normalize code
This commit is contained in:
@@ -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))
|
||||
}
|
||||
Reference in New Issue
Block a user