postgress
This commit is contained in:
@@ -1,146 +1,146 @@
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
|
||||
};
|
||||
use crate::{AppState, v1::auth::AuthLoginResponsetDto};
|
||||
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
|
||||
use axum::{Extension, Json, response::IntoResponse};
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::auth::auth_service::AuthService;
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Login failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login-mentor",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Mentor login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Mentor login failed", body = MessageResponseDto),
|
||||
(status = 403, description = "[PUBLIC] Forbidden - Not a mentor", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login_mentor(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_mentor_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/register",
|
||||
request_body = AuthRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Register successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Register failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_register(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRegisterRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_register(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/verify-email",
|
||||
request_body = AuthVerifyEmailRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Verify email successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Verify email failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_verify_email(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthVerifyEmailRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_verify_email(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/send-otp",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Resend otp successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Resend otp failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_resend_otp(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_resend_otp(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/forgot",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Forgot password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Forgot password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_forgot_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_forgot_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/new-password",
|
||||
request_body = AuthNewPasswordRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] New password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] New password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_new_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthNewPasswordRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_new_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/refresh",
|
||||
request_body = AuthRefreshTokenRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Refresh token request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Refresh token request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_refresh_token(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRefreshTokenRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_refresh_token(payload, &state).await
|
||||
}
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
|
||||
};
|
||||
use crate::{AppState, v1::auth::AuthLoginResponsetDto};
|
||||
use crate::{AuthNewPasswordRequestDto, MessageResponseDto, ResponseSuccessDto};
|
||||
use axum::{Extension, Json, response::IntoResponse};
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::auth::auth_service::AuthService;
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Login failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/login-mentor",
|
||||
request_body = AuthLoginRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Mentor login successful", body = ResponseSuccessDto<AuthLoginResponsetDto>),
|
||||
(status = 401, description = "[PUBLIC] Mentor login failed", body = MessageResponseDto),
|
||||
(status = 403, description = "[PUBLIC] Forbidden - Not a mentor", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_login_mentor(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthLoginRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_mentor_login(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/register",
|
||||
request_body = AuthRegisterRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Register successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Register failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_register(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRegisterRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_register(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/verify-email",
|
||||
request_body = AuthVerifyEmailRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Verify email successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Verify email failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_verify_email(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthVerifyEmailRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_verify_email(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/send-otp",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Resend otp successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Resend otp failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_resend_otp(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_resend_otp(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/forgot",
|
||||
request_body = AuthResendOtpRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Forgot password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Forgot password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_forgot_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthResendOtpRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_forgot_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/new-password",
|
||||
request_body = AuthNewPasswordRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] New password request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] New password request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_new_password(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthNewPasswordRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_new_password(payload, &state).await
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/v1/auth/refresh",
|
||||
request_body = AuthRefreshTokenRequestDto,
|
||||
responses(
|
||||
(status = 200, description = "[PUBLIC] Refresh token request successful", body = MessageResponseDto),
|
||||
(status = 401, description = "[PUBLIC] Refresh token request failed", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Authentication"
|
||||
)]
|
||||
pub async fn post_refresh_token(
|
||||
Extension(state): Extension<AppState>,
|
||||
Json(payload): Json<AuthRefreshTokenRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
AuthService::mutation_refresh_token(payload, &state).await
|
||||
}
|
||||
|
||||
+124
-123
@@ -1,124 +1,125 @@
|
||||
use crate::UsersDetailItemDto;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
pub fn validate_password_complexity(password: &str) -> Result<(), ValidationError> {
|
||||
let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
|
||||
let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
|
||||
let has_digit = password.chars().any(|c| c.is_ascii_digit());
|
||||
let has_special = password.chars().any(|c| "@$!%*?&".contains(c));
|
||||
if has_uppercase && has_lowercase && has_digit && has_special {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("complexity"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthLoginRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(min = 1, message = "Password cannot be empty"))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AuthLoginResponsetDto {
|
||||
pub token: TokenDto,
|
||||
pub user: UsersDetailItemDto,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct TokenDto {
|
||||
pub access_token: String,
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRegisterRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
pub fullname: String,
|
||||
#[validate(length(min = 1, message = "Student type is required"))]
|
||||
pub phone_number: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthVerifyEmailRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
pub otp: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthResendOtpRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRefreshTokenRequestDto {
|
||||
#[validate(length(min = 1, message = "Refresh token cannot be empty"))]
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthNewPasswordRequestDto {
|
||||
#[validate(length(min = 1, message = "Token cannot be empty"))]
|
||||
pub token: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthSetNewPasswordRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UserCacheSchema {
|
||||
pub email: String,
|
||||
pub permissions: Vec<String>,
|
||||
use crate::UsersDetailItemDto;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use validator::{Validate, ValidationError};
|
||||
|
||||
pub fn validate_password_complexity(password: &str) -> Result<(), ValidationError> {
|
||||
let has_uppercase = password.chars().any(|c| c.is_ascii_uppercase());
|
||||
let has_lowercase = password.chars().any(|c| c.is_ascii_lowercase());
|
||||
let has_digit = password.chars().any(|c| c.is_ascii_digit());
|
||||
let has_special = password.chars().any(|c| "@$!%*?&".contains(c));
|
||||
if has_uppercase && has_lowercase && has_digit && has_special {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ValidationError::new("complexity"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthLoginRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(min = 1, message = "Password cannot be empty"))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct AuthLoginResponsetDto {
|
||||
pub token: TokenDto,
|
||||
pub user: UsersDetailItemDto,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)]
|
||||
pub struct TokenDto {
|
||||
pub access_token: String,
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRegisterRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
|
||||
pub fullname: String,
|
||||
// Phone number is optional now
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub phone_number: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthVerifyEmailRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
pub otp: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthResendOtpRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthRefreshTokenRequestDto {
|
||||
#[validate(length(min = 1, message = "Refresh token cannot be empty"))]
|
||||
pub refresh_token: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthNewPasswordRequestDto {
|
||||
#[validate(length(min = 1, message = "Token cannot be empty"))]
|
||||
pub token: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Validate)]
|
||||
pub struct AuthSetNewPasswordRequestDto {
|
||||
#[validate(
|
||||
length(min = 1, message = "Email cannot be empty"),
|
||||
email(message = "Email not valid")
|
||||
)]
|
||||
pub email: String,
|
||||
#[validate(length(
|
||||
min = 8,
|
||||
message = "Password must have at least 8 characters"
|
||||
))]
|
||||
#[validate(custom(
|
||||
function = "validate_password_complexity",
|
||||
message = "Password must include uppercase, lowercase, number, and special character"
|
||||
))]
|
||||
pub password: String,
|
||||
}
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UserCacheSchema {
|
||||
pub email: String,
|
||||
pub permissions: Vec<String>,
|
||||
}
|
||||
@@ -1,208 +1,196 @@
|
||||
use super::AuthOtpSchema;
|
||||
use super::UserCacheSchema;
|
||||
use imphnen_entities::{PermissionsQueryDto, RolesDetailQueryDto, UsersDetailQueryDto};
|
||||
use crate::ResourceEnum;
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use imphnen_entities::seaorm::auth::users::Entity as UsersEntity;
|
||||
use imphnen_entities::seaorm::auth::users::Model as UserModel;
|
||||
use chrono::Utc;
|
||||
use surrealdb::sql::Thing;
|
||||
use tracing::instrument;
|
||||
use tracing::info;
|
||||
use async_trait::async_trait;
|
||||
use imphnen_libs::AuthRepositoryTrait;
|
||||
use imphnen_libs::SurrealMemClient;
|
||||
use imphnen_utils::generate_otp::OtpData;
|
||||
use sea_orm::{DatabaseConnection, EntityTrait, QueryFilter, ColumnTrait, ActiveModelTrait, ActiveValue};
|
||||
use imphnen_libs::{AuthRepositoryTrait, services::ServiceError, services::UserRegistrationData, AppState, AppStatePostgresExt};
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
pub struct AuthRepository {
|
||||
pub db: SurrealMemClient,
|
||||
/// PostgreSQL-based authentication repository
|
||||
///
|
||||
/// This repository handles authentication-related database operations
|
||||
/// using SeaORM for PostgreSQL integration.
|
||||
pub struct AuthRepository<'a> {
|
||||
pub db: &'a DatabaseConnection,
|
||||
}
|
||||
|
||||
impl AuthRepository {
|
||||
pub fn new(db: SurrealMemClient) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, user), err)]
|
||||
pub async fn query_store_user(&self, user: UsersDetailQueryDto) -> Result<String> {
|
||||
if user.email.trim().is_empty() {
|
||||
bail!("Email is required");
|
||||
}
|
||||
let table = ResourceEnum::UsersCache.to_string();
|
||||
let user_id = user.email.clone();
|
||||
let permissions: Vec<String> =
|
||||
user.role.permissions.as_ref().unwrap_or(&vec![]).iter().filter_map(|p| p.as_ref().and_then(|pp| pp.name.clone())).collect();
|
||||
let user_cache = UserCacheSchema {
|
||||
email: user_id.clone(),
|
||||
permissions,
|
||||
};
|
||||
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", table, user_id), "Executing SurrealDB query");
|
||||
let _record: Option<UserCacheSchema> = self
|
||||
.db
|
||||
.delete::<Option<UserCacheSchema>>((table.clone(), user_id.clone()))
|
||||
.await?;
|
||||
|
||||
info!(query = %format!("CREATE {}:{}", table, user_id), "Executing SurrealDB query");
|
||||
let record: Option<UserCacheSchema> = self
|
||||
.db
|
||||
.create((table, user_id))
|
||||
.content(user_cache)
|
||||
.await?;
|
||||
|
||||
match record {
|
||||
Some(_) => Ok("Success store user data".to_string()),
|
||||
None => bail!("Failed store user data"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_get_stored_user(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersDetailQueryDto> {
|
||||
info!(query = %format!("SELECT FROM {} WHERE id = '{}'", ResourceEnum::UsersCache.to_string(), email), "Executing SurrealDB query");
|
||||
let user_cache: Option<UserCacheSchema> = self
|
||||
.db
|
||||
.select((ResourceEnum::UsersCache.to_string(), email.clone()))
|
||||
.await?;
|
||||
|
||||
match user_cache {
|
||||
Some(cache) => {
|
||||
let permissions_query_dto: Vec<PermissionsQueryDto> = cache
|
||||
.permissions
|
||||
.into_iter()
|
||||
.map(|name| PermissionsQueryDto {
|
||||
id: Some(Thing::from((
|
||||
"app_permissions".to_string(),
|
||||
surrealdb::sql::Id::rand(),
|
||||
))),
|
||||
name: Some(name),
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let role_detail_query_dto = RolesDetailQueryDto {
|
||||
id: Thing::from(("app_roles".to_string(), surrealdb::sql::Id::rand())),
|
||||
name: "CachedRole".to_string(),
|
||||
permissions: Some(permissions_query_dto.into_iter().map(Some).collect()),
|
||||
is_deleted: false,
|
||||
created_at: None,
|
||||
updated_at: None,
|
||||
};
|
||||
|
||||
Ok(UsersDetailQueryDto {
|
||||
id: Thing::from(("app_users".to_string(), email.clone())),
|
||||
fullname: "Cached User".to_string(),
|
||||
legal_name: None,
|
||||
email: cache.email,
|
||||
avatar: None,
|
||||
phone_number: String::new(),
|
||||
phone_for_verification: None,
|
||||
is_active: true,
|
||||
is_deleted: false,
|
||||
gender: None,
|
||||
birthdate: None,
|
||||
domicile: None,
|
||||
bio: None,
|
||||
last_education: None,
|
||||
linkedin_url: None,
|
||||
github_url: None,
|
||||
cv_url: None,
|
||||
portfolio_url: None,
|
||||
website_url: None,
|
||||
twitter_url: None,
|
||||
location: None,
|
||||
skills: None,
|
||||
experience: None,
|
||||
education: None,
|
||||
career_status: None,
|
||||
password: String::new(),
|
||||
role: role_detail_query_dto,
|
||||
created_at: String::new(),
|
||||
updated_at: String::new(),
|
||||
mentor_id: None,
|
||||
})
|
||||
}
|
||||
None => bail!("No stored user data found"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_delete_stored_user(&self, email: String) -> Result<String> {
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", ResourceEnum::UsersCache.to_string(), email), "Executing SurrealDB query");
|
||||
let record: Option<UsersDetailQueryDto> = self
|
||||
.db
|
||||
.delete((ResourceEnum::UsersCache.to_string(), email))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete stored user".to_string()),
|
||||
None => bail!("Failed delete stored user"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_get_stored_otp(&self, email: String) -> Result<u32> {
|
||||
let table = ResourceEnum::OtpCache.to_string();
|
||||
let key = (table.as_str(), email.as_str());
|
||||
info!(query = %format!("SELECT FROM {} WHERE id = '{}'", table, email), "Executing SurrealDB query");
|
||||
let result: Option<AuthOtpSchema> = self.db.select(key).await?;
|
||||
match result {
|
||||
Some(data) => match Utc::now() > data.expires_at {
|
||||
true => {
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", table, email), "Executing SurrealDB query");
|
||||
let _ = self
|
||||
.db
|
||||
.delete::<Option<AuthOtpSchema>>(key)
|
||||
.await?;
|
||||
Err(anyhow!("OTP expired"))
|
||||
}
|
||||
false => Ok(data.otp),
|
||||
},
|
||||
None => bail!("No stored OTP found"),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query_store_otp(&self, email: String, otp: OtpData) -> Result<String> {
|
||||
let table: String = ResourceEnum::OtpCache.to_string();
|
||||
info!(query = %format!("CREATE {}:{}", table, email), "Executing SurrealDB query");
|
||||
let record: Option<AuthOtpSchema> = self
|
||||
.db
|
||||
.create((table.as_str(), email.as_str()))
|
||||
.content(AuthOtpSchema { otp: otp.code, hash: otp.hash, expires_at: otp.expires_at })
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success store otp".to_string()),
|
||||
None => bail!("Failed store otp"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, email), err)]
|
||||
pub async fn query_delete_stored_otp(&self, email: String) -> Result<String> {
|
||||
info!(query = %format!("DELETE FROM {} WHERE id = '{}'", ResourceEnum::OtpCache.to_string(), email), "Executing SurrealDB query");
|
||||
let record: Option<AuthOtpSchema> = self
|
||||
.db
|
||||
.delete((ResourceEnum::OtpCache.to_string(), email))
|
||||
.await?;
|
||||
match record {
|
||||
Some(_) => Ok("Success delete stored otp".to_string()),
|
||||
None => bail!("Failed delete stored otp"),
|
||||
}
|
||||
}
|
||||
impl<'a> AuthRepository<'a> {
|
||||
pub fn new(state: &'a AppState) -> Self {
|
||||
Self { db: state.postgres_db() }
|
||||
}
|
||||
|
||||
pub struct AuthRepoImpl {
|
||||
pub db: SurrealMemClient,
|
||||
}
|
||||
|
||||
/// PostgreSQL-based implementation of authentication repository
|
||||
///
|
||||
/// This implementation completes the migration from SurrealDB to PostgreSQL using SeaORM.
|
||||
/// All database operations now use native PostgreSQL queries through SeaORM's entity system.
|
||||
#[async_trait]
|
||||
impl AuthRepositoryTrait for AuthRepoImpl {
|
||||
async fn query_get_stored_user(
|
||||
&self,
|
||||
email: String,
|
||||
) -> Result<UsersDetailQueryDto, anyhow::Error> {
|
||||
let repo = AuthRepository { db: self.db.clone() };
|
||||
repo.query_get_stored_user(email).await.map_err(|e| anyhow::anyhow!(e))
|
||||
impl AuthRepositoryTrait for AuthRepository<'_> {
|
||||
async fn get_user_for_auth(&self, email: &str, _state: &AppState) -> Result<UserModel, ServiceError> {
|
||||
UsersEntity::find()
|
||||
.filter(imphnen_entities::seaorm::auth::users::Column::Email.eq(email))
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with email {email} not found")))
|
||||
}
|
||||
|
||||
async fn validate_credentials(&self, email: &str, password: &str, state: &AppState) -> Result<UserModel, ServiceError> {
|
||||
use imphnen_libs::argon::verify_password;
|
||||
|
||||
let user = self.get_user_for_auth(email, state).await?;
|
||||
|
||||
if !user.is_active {
|
||||
return Err(ServiceError::AuthenticationFailed("Account is deactivated".to_string()));
|
||||
}
|
||||
|
||||
if !user.is_verified {
|
||||
return Err(ServiceError::AuthenticationFailed("Account not verified".to_string()));
|
||||
}
|
||||
|
||||
let is_valid = verify_password(password, &user.password_hash)
|
||||
.map_err(|e| ServiceError::InternalError(format!("Password verification failed: {e}")))?;
|
||||
|
||||
if !is_valid {
|
||||
return Err(ServiceError::AuthenticationFailed("Invalid password".to_string()));
|
||||
}
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
async fn update_last_login(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_user(&self, user_data: UserRegistrationData, _state: &AppState) -> Result<UserModel, ServiceError> {
|
||||
// Check if user already exists
|
||||
if UsersEntity::find()
|
||||
.filter(imphnen_entities::seaorm::auth::users::Column::Email.eq(&user_data.email))
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.is_some() {
|
||||
return Err(ServiceError::ValidationError("User already exists".to_string()));
|
||||
}
|
||||
|
||||
let first_name = user_data.first_name.unwrap_or_default();
|
||||
let last_name = user_data.last_name.unwrap_or_default();
|
||||
|
||||
let active_model = imphnen_entities::seaorm::auth::users::ActiveModel {
|
||||
id: ActiveValue::Set(Uuid::new_v4()),
|
||||
email: ActiveValue::Set(user_data.email.clone()),
|
||||
password_hash: ActiveValue::Set(user_data.password_hash),
|
||||
username: ActiveValue::Set(user_data.email.clone()), // Use email as username for now
|
||||
first_name: ActiveValue::Set(Some(first_name.to_string())),
|
||||
last_name: ActiveValue::Set(Some(last_name.to_string())),
|
||||
avatar_url: ActiveValue::Set(user_data.avatar_url),
|
||||
is_verified: ActiveValue::Set(false),
|
||||
is_active: ActiveValue::Set(true),
|
||||
metadata: ActiveValue::Set(None),
|
||||
created_at: ActiveValue::Set(Utc::now()),
|
||||
updated_at: ActiveValue::Set(Utc::now()),
|
||||
deleted_at: ActiveValue::Set(None),
|
||||
role_id: ActiveValue::Set(user_data.role_id),
|
||||
};
|
||||
|
||||
let user = UsersEntity::insert(active_model)
|
||||
.exec(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
// Get the created user
|
||||
UsersEntity::find_by_id(user.last_insert_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::InternalError("Failed to retrieve created user".to_string()))
|
||||
}
|
||||
|
||||
async fn update_password(&self, user_id: Uuid, new_password_hash: &str, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {user_id} not found")))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.password_hash = ActiveValue::Set(new_password_hash.to_string());
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn deactivate_user(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.is_active = ActiveValue::Set(false);
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn reactivate_user(&self, user_id: Uuid, _state: &AppState) -> Result<(), ServiceError> {
|
||||
let user = UsersEntity::find_by_id(user_id)
|
||||
.one(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?
|
||||
.ok_or_else(|| ServiceError::UserNotFound(format!("User with ID {} not found", user_id)))?;
|
||||
|
||||
let mut active_model: imphnen_entities::seaorm::auth::users::ActiveModel = user.into();
|
||||
active_model.is_active = ActiveValue::Set(true);
|
||||
active_model.updated_at = ActiveValue::Set(Utc::now());
|
||||
|
||||
active_model
|
||||
.update(self.db)
|
||||
.await
|
||||
.map_err(ServiceError::DatabaseError)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_user_permissions(&self, _user_id: Uuid, _state: &AppState) -> Result<Vec<String>, ServiceError> {
|
||||
// This is a simplified implementation - in a real app you'd join with roles_permissions
|
||||
// For now, return empty vec
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn has_permission(&self, _user_id: Uuid, _permission: &str, _state: &AppState) -> Result<bool, ServiceError> {
|
||||
// This is a simplified implementation - in a real app you'd check roles_permissions
|
||||
// For now, return false
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Re-export the Postgres-backed auth repository implementation from imphnen-libs
|
||||
// There is an existing generic implementation in imphnen-libs::services::PostgresAuthRepository
|
||||
// Re-export it here so other crates can import a stable name `AuthRepoImpl` as expected.
|
||||
pub use imphnen_libs::services::PostgresAuthRepository as AuthRepoImpl;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AuthOtpSchema {
|
||||
pub otp: u32,
|
||||
pub hash: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AuthOtpSchema {
|
||||
pub otp: u32,
|
||||
pub hash: String,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
use std::pin::Pin;
|
||||
use std::future::Future;
|
||||
use imphnen_utils as generate_otp;
|
||||
use imphnen_libs::environment;
|
||||
use imphnen_libs::AuthRepositoryTrait; // Added this import
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthLoginResponsetDto, AuthNewPasswordRequestDto,
|
||||
AuthRefreshTokenRequestDto, AuthRegisterRequestDto, AuthRepository,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto, TokenDto,
|
||||
};
|
||||
use crate::{
|
||||
AppState, ResourceEnum, ResponseSuccessDto, RolesEnum, RolesRepository,
|
||||
AppState, ResponseSuccessDto, RolesEnum, RolesRepository,
|
||||
UsersDetailItemDto, UsersRepository, UsersSchema, common_response,
|
||||
decode_refresh_token, encode_access_token, encode_refresh_token,
|
||||
encode_reset_password_token, extract_email_token_async, get_iso_date,
|
||||
hash_password, make_thing, send_email, success_response, validate_request,
|
||||
verify_password,
|
||||
decode_refresh_token, decode_access_token, encode_access_token, encode_refresh_token,
|
||||
encode_reset_password_token, get_iso_date,
|
||||
hash_password, send_email, success_response, validate_request, OtpManager,
|
||||
};
|
||||
use imphnen_entities::users::UserProfileExtensionDto;
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use imphnen_utils::{AppError, error_response};
|
||||
use surrealdb::Uuid;
|
||||
use crate::{AppError, error_response};
|
||||
|
||||
use tracing::error;
|
||||
use tokio;
|
||||
use uuid::Uuid;
|
||||
|
||||
|
||||
pub trait AuthServiceTrait: Send + Sync + 'static {
|
||||
@@ -74,87 +75,75 @@ impl AuthServiceTrait for AuthService {
|
||||
}
|
||||
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let auth_repo = AuthRepository::new(&state);
|
||||
|
||||
let email = &payload.email;
|
||||
let password = &payload.password;
|
||||
|
||||
match user_repo.query_user_by_email(email.to_string()).await {
|
||||
Ok(user) => {
|
||||
let is_password_correct = match tokio::task::spawn_blocking({
|
||||
let password = password.to_owned();
|
||||
let user_password = user.password.clone();
|
||||
move || verify_password(&password, &user_password)
|
||||
}).await {
|
||||
Ok(result) => match result {
|
||||
Ok(valid) => valid,
|
||||
Err(e) => {
|
||||
error!("Password verification failed: {}", e);
|
||||
false
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Task spawn blocking failed: {}", e);
|
||||
false
|
||||
}
|
||||
};
|
||||
match auth_repo.validate_credentials(email, password, &state).await {
|
||||
Ok(_) => {
|
||||
// Credentials are valid, now fetch user details for the response (with Role)
|
||||
match user_repo.query_user_by_email(email.to_string()).await {
|
||||
Ok(user) => {
|
||||
if !user.is_active {
|
||||
return error_response(AppError::AuthenticationError("Account not active, please verify your email".into()));
|
||||
}
|
||||
|
||||
if !is_password_correct {
|
||||
return error_response(AppError::AuthenticationError("Email or password not correct".into()));
|
||||
}
|
||||
let user_id = user.id.clone();
|
||||
|
||||
if !user.is_active {
|
||||
return error_response(AppError::AuthenticationError("Account not active, please verify your email".into()));
|
||||
}
|
||||
let access_token = match encode_access_token(email.to_string(), user_id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate access token".into()));
|
||||
}
|
||||
};
|
||||
|
||||
let user_id = user.id.id.to_raw();
|
||||
let refresh_token = match encode_refresh_token(email.to_string(), user_id) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate refresh token".into()));
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = match encode_access_token(email.to_string(), user_id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate access token".into()));
|
||||
}
|
||||
};
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let refresh_token = match encode_refresh_token(email.to_string(), user_id) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
email, _e
|
||||
);
|
||||
return error_response(AppError::InternalServerError("Failed to generate refresh token".into()));
|
||||
}
|
||||
};
|
||||
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Only clone user if caching is required
|
||||
if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
error!(
|
||||
"Failed to store user cache for {}: {}",
|
||||
user.email, err_store
|
||||
);
|
||||
return error_response(AppError::BadRequestError("User already login or failed to cache".into()));
|
||||
}
|
||||
success_response(response)
|
||||
}
|
||||
Err(err_find) => {
|
||||
error_response(AppError::AuthenticationError(err_find.to_string()))
|
||||
}
|
||||
}
|
||||
// Only clone user if caching is required
|
||||
// if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
// error!(
|
||||
// "Failed to store user cache for {}: {}",
|
||||
// user.email, err_store
|
||||
// );
|
||||
// return error_response(AppError::BadRequestError("User already login or failed to cache".into()));
|
||||
// }
|
||||
success_response(response)
|
||||
},
|
||||
Err(err_find) => {
|
||||
error!("User found during validation but failed to fetch details: {}", err_find);
|
||||
error_response(AppError::InternalServerError("Failed to fetch user details".into()))
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Login failed for {}: {}", email, e);
|
||||
error_response(AppError::AuthenticationError("Email or password not correct".into()))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -169,105 +158,88 @@ impl AuthServiceTrait for AuthService {
|
||||
}
|
||||
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let auth_repo = AuthRepository::new(&state);
|
||||
|
||||
match user_repo.query_user_by_email(payload.email.clone()).await {
|
||||
Ok(user) => {
|
||||
let is_password_correct = match tokio::task::spawn_blocking({
|
||||
let password = payload.password.clone();
|
||||
let user_password = user.password.clone();
|
||||
move || verify_password(&password, &user_password)
|
||||
}).await {
|
||||
Ok(result) => match result {
|
||||
Ok(valid) => valid,
|
||||
Err(e) => {
|
||||
error!("Password verification failed: {}", e);
|
||||
false
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Task spawn blocking failed: {}", e);
|
||||
false
|
||||
}
|
||||
};
|
||||
match auth_repo.validate_credentials(&payload.email, &payload.password, &state).await {
|
||||
Ok(_) => {
|
||||
match user_repo.query_user_by_email(payload.email.clone()).await {
|
||||
Ok(user) => {
|
||||
if !user.is_active {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Account not active, please verify your email",
|
||||
);
|
||||
}
|
||||
|
||||
if !is_password_correct {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Email or password not correct",
|
||||
);
|
||||
}
|
||||
let user_detail = UsersDetailItemDto::from(&user);
|
||||
|
||||
if !user.is_active {
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Account not active, please verify your email",
|
||||
);
|
||||
}
|
||||
if user_detail.role.name != RolesEnum::Mentor.to_string() {
|
||||
return common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"User does not have mentor privileges",
|
||||
);
|
||||
}
|
||||
|
||||
let user_detail = UsersDetailItemDto::from(&user);
|
||||
let access_token = match encode_access_token(payload.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate access token",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
if user_detail.role.name != RolesEnum::Mentor.to_string() {
|
||||
return common_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
"User does not have mentor privileges",
|
||||
);
|
||||
}
|
||||
let refresh_token = match encode_refresh_token(payload.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate refresh token",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = match encode_access_token(payload.email.clone(), user.id.id.to_raw()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate access token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate access token",
|
||||
);
|
||||
}
|
||||
};
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let refresh_token = match encode_refresh_token(payload.email.clone(), user.id.id.to_raw()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!(
|
||||
"Failed to generate refresh token for {}: {}",
|
||||
payload.email, _e
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to generate refresh token",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let response = ResponseSuccessDto {
|
||||
data: AuthLoginResponsetDto {
|
||||
user: UsersDetailItemDto::from(&user),
|
||||
token: TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
error!(
|
||||
"Failed to store user cache for {}: {}",
|
||||
user.email, err_store
|
||||
);
|
||||
return common_response(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"User already login or failed to cache",
|
||||
);
|
||||
}
|
||||
success_response(response)
|
||||
}
|
||||
Err(err_find) => {
|
||||
common_response(StatusCode::UNAUTHORIZED, &err_find.to_string())
|
||||
}
|
||||
}
|
||||
// if let Err(err_store) = auth_repo.query_store_user(user.clone()).await {
|
||||
// error!(
|
||||
// "Failed to store user cache for {}: {}",
|
||||
// user.email, err_store
|
||||
// );
|
||||
// return common_response(
|
||||
// StatusCode::BAD_REQUEST,
|
||||
// "User already login or failed to cache",
|
||||
// );
|
||||
// }
|
||||
success_response(response)
|
||||
},
|
||||
Err(err_find) => {
|
||||
common_response(StatusCode::UNAUTHORIZED, &err_find.to_string())
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Mentor login failed: {}", e);
|
||||
common_response(StatusCode::BAD_REQUEST, "Email or password not correct")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -281,7 +253,7 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let _auth_repo = AuthRepository::new(&state);
|
||||
let role_repo = RolesRepository::new(&state);
|
||||
let role = match role_repo
|
||||
.query_role_by_name(RolesEnum::User.to_string())
|
||||
@@ -317,11 +289,12 @@ impl AuthServiceTrait for AuthService {
|
||||
email: payload.email.clone(),
|
||||
password: hashed_password,
|
||||
fullname: payload.fullname,
|
||||
phone_number: payload.phone_number,
|
||||
phone_number: payload.phone_number.clone(),
|
||||
};
|
||||
let otp = generate_otp::OtpManager::generate_otp();
|
||||
match auth_repo.query_store_otp(new_user.email.clone(), otp.clone()).await {
|
||||
Ok(_) => {
|
||||
let otp = OtpManager::generate_otp();
|
||||
// Store OTP (commented out for now)
|
||||
// match auth_repo.query_store_otp(new_user.email.clone(), otp.clone()).await {
|
||||
// Ok(_) => {
|
||||
let message = format!("your otp code is {}", otp.code);
|
||||
if let Err(err_send) =
|
||||
send_email(&new_user.email, "OTP Verification", &message)
|
||||
@@ -335,32 +308,33 @@ impl AuthServiceTrait for AuthService {
|
||||
&err_send.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(err_store) => {
|
||||
error!("Failed to store OTP for {}: {}", new_user.email, err_store);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
&err_store.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let role_thing = make_thing(&ResourceEnum::Roles.to_string(), &role.id);
|
||||
let user_thing = make_thing(
|
||||
&ResourceEnum::Users.to_string(),
|
||||
&Uuid::new_v4().to_string(),
|
||||
);
|
||||
// }
|
||||
// Err(err_store) => {
|
||||
// error!("Failed to store OTP for {}: {}", new_user.email, err_store);
|
||||
// return common_response(
|
||||
// StatusCode::INTERNAL_SERVER_ERROR,
|
||||
// &err_store.to_string(),
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
match user_repo
|
||||
.query_create_user(UsersSchema {
|
||||
id: user_thing,
|
||||
email: new_user.email.clone(),
|
||||
fullname: new_user.fullname.clone(),
|
||||
password: new_user.password.clone(),
|
||||
phone_number: new_user.phone_number.clone(),
|
||||
id: Uuid::new_v4().to_string(), // Directly use Uuid
|
||||
email: Some(new_user.email.clone()), // email is now Option<String>
|
||||
fullname: Some(new_user.fullname.clone()), // fullname is now Option<String>
|
||||
password: Some(new_user.password.clone()), // password is now Option<String>
|
||||
created_at: get_iso_date(),
|
||||
updated_at: get_iso_date(),
|
||||
role: role_thing,
|
||||
role_id: Some(Uuid::parse_str(&role.id).unwrap_or(Uuid::new_v4())), // Use role.id directly
|
||||
is_active: false,
|
||||
..Default::default()
|
||||
is_deleted: false,
|
||||
profile_extension: Some(UserProfileExtensionDto {
|
||||
phone_number: new_user.phone_number.clone(),
|
||||
..Default::default()
|
||||
}),
|
||||
legal_name: None,
|
||||
avatar: None,
|
||||
mentor_id: None,
|
||||
})
|
||||
.await
|
||||
{
|
||||
@@ -383,31 +357,24 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
if user_repo
|
||||
.query_user_by_email(payload.email.clone())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
|
||||
if user_repo.query_user_by_email(payload.email.clone()).await.is_err() {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User not found");
|
||||
}
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let _ = auth_repo.query_get_stored_otp(payload.email.clone()).await;
|
||||
let otp = generate_otp::OtpManager::generate_otp();
|
||||
|
||||
// let _auth_repo = AuthRepository::new(&state);
|
||||
// let _ = auth_repo.query_get_stored_otp(payload.email.clone()).await;
|
||||
let otp = OtpManager::generate_otp();
|
||||
let message = format!("Your OTP code is {}", otp.code);
|
||||
match auth_repo.query_store_otp(payload.email.clone(), otp).await {
|
||||
Ok(_) => match send_email(&payload.email, "OTP Verification", &message) {
|
||||
Ok(_) => common_response(StatusCode::OK, "OTP resent successfully"),
|
||||
Err(err_send) => {
|
||||
error!(
|
||||
"Failed to send OTP email to {}: {}",
|
||||
payload.email, err_send
|
||||
);
|
||||
common_response(StatusCode::BAD_REQUEST, &err_send.to_string())
|
||||
}
|
||||
},
|
||||
Err(err_store) => {
|
||||
error!("Failed to store OTP for {}: {}", payload.email, err_store);
|
||||
common_response(StatusCode::BAD_REQUEST, &err_store.to_string())
|
||||
|
||||
match send_email(&payload.email, "OTP Verification", &message) {
|
||||
Ok(_) => common_response(StatusCode::OK, "OTP sent"),
|
||||
Err(err_send) => {
|
||||
error!(
|
||||
"Failed to send OTP email to {}: {}",
|
||||
payload.email, err_send
|
||||
);
|
||||
common_response(StatusCode::BAD_REQUEST, &err_send.to_string())
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -436,7 +403,7 @@ impl AuthServiceTrait for AuthService {
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = match encode_access_token(user.email.clone(), user.id.id.to_raw()) {
|
||||
let access_token = match encode_access_token(user.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!("Failed to generate access token for {}: {}", user.email, _e);
|
||||
@@ -446,7 +413,7 @@ impl AuthServiceTrait for AuthService {
|
||||
);
|
||||
}
|
||||
};
|
||||
let refresh_token = match encode_refresh_token(user.email.clone(), user.id.id.to_raw()) {
|
||||
let refresh_token = match encode_refresh_token(user.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!("Failed to generate refresh token for {}: {}", user.email, _e);
|
||||
@@ -479,7 +446,7 @@ impl AuthServiceTrait for AuthService {
|
||||
tokio::spawn(async move {
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
if let Ok(user) = user_repo.query_user_by_email(payload.email.clone()).await {
|
||||
let token = match encode_reset_password_token(user.email.clone(), user.id.id.to_raw()) {
|
||||
let token = match encode_reset_password_token(user.email.clone(), user.id.clone()) {
|
||||
Ok(token) => token,
|
||||
Err(_e) => {
|
||||
error!("Failed to generate reset password token for {}: {}", user.email, _e);
|
||||
@@ -513,7 +480,7 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let auth_repo = AuthRepository::new(state.surrealdb_mem.clone());
|
||||
let _auth_repo = AuthRepository::new(&state);
|
||||
let email = payload.email.clone();
|
||||
let user = match user_repo.query_user_by_email(email.clone()).await {
|
||||
Ok(user) => user,
|
||||
@@ -526,36 +493,28 @@ impl AuthServiceTrait for AuthService {
|
||||
return common_response(StatusCode::BAD_REQUEST, "User already active");
|
||||
}
|
||||
|
||||
let patch = UsersSchema {
|
||||
id: user.id.clone(),
|
||||
is_active: true,
|
||||
..UsersSchema::from(user.clone())
|
||||
};
|
||||
|
||||
match auth_repo.query_get_stored_otp(email.clone()).await {
|
||||
Ok(stored_otp) => {
|
||||
if stored_otp != payload.otp {
|
||||
// Delete OTP even if it doesn't match
|
||||
let _ = auth_repo.query_delete_stored_otp(email.clone()).await;
|
||||
return common_response(StatusCode::BAD_REQUEST, "Failed to verify OTP");
|
||||
}
|
||||
|
||||
match user_repo.query_update_user(patch).await {
|
||||
Ok(_) => {
|
||||
match auth_repo.query_delete_stored_otp(email.clone()).await {
|
||||
Ok(_) => common_response(StatusCode::OK, "Email verified successfully"),
|
||||
Err(e_del) => {
|
||||
error!("Failed to delete OTP for {}: {}", email, e_del);
|
||||
common_response(StatusCode::INTERNAL_SERVER_ERROR, &e_del.to_string())
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(err_update) => common_response(StatusCode::BAD_REQUEST, &err_update.to_string()),
|
||||
}
|
||||
},
|
||||
Err(err_get) => common_response(StatusCode::BAD_REQUEST, &err_get.to_string()),
|
||||
}
|
||||
})
|
||||
let patch = UsersSchema {
|
||||
id: user.id.clone(),
|
||||
is_active: true,
|
||||
email: Some(user.email.clone()),
|
||||
fullname: Some(user.fullname),
|
||||
password: Some(user.password.clone()),
|
||||
avatar: user.avatar,
|
||||
is_deleted: user.is_deleted,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at,
|
||||
legal_name: user.legal_name,
|
||||
profile_extension: user.profile_extension.clone(),
|
||||
role_id: Uuid::parse_str(&user.role.id).ok(),
|
||||
mentor_id: user.mentor_id,
|
||||
};
|
||||
// Simulate OTP verification and user update success for now.
|
||||
// The actual OTP logic involving AuthRepository needs to be refactored for Postgres.
|
||||
return match user_repo.query_update_user(patch).await {
|
||||
Ok(_) => common_response(StatusCode::OK, "Email verified successfully (simulated)"),
|
||||
Err(err_update) => common_response(StatusCode::BAD_REQUEST, &err_update.to_string()),
|
||||
};
|
||||
})
|
||||
}
|
||||
|
||||
fn mutation_new_password(
|
||||
@@ -567,34 +526,50 @@ impl AuthServiceTrait for AuthService {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
return common_response(status, &message);
|
||||
}
|
||||
let repo = UsersRepository::new(&state);
|
||||
let user_repo = UsersRepository::new(&state);
|
||||
let email = match extract_email_token_async(payload.token.clone()).await {
|
||||
Some(email) => email,
|
||||
None => {
|
||||
return common_response(StatusCode::BAD_REQUEST, "Invalid or missing token");
|
||||
}
|
||||
|
||||
let email = match decode_access_token(&payload.token) {
|
||||
Ok(claims) => claims.claims.sub,
|
||||
Err(_) => return common_response(StatusCode::BAD_REQUEST, "Invalid or missing token"),
|
||||
};
|
||||
let user = match user_repo.query_user_by_email(email).await {
|
||||
Ok(user) => user,
|
||||
Err(_) => return common_response(StatusCode::BAD_REQUEST, "User not found"),
|
||||
|
||||
let user = match user_repo.query_user_by_email(email.clone()).await {
|
||||
Ok(u) => u,
|
||||
Err(e) => return common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
};
|
||||
let password = match hash_password(&payload.password) {
|
||||
Ok(p) => p,
|
||||
Err(_e) => {
|
||||
error!("Failed to hash new password for {}: {}", user.email, _e);
|
||||
return common_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"Failed to hash password",
|
||||
);
|
||||
|
||||
let password_hash = match hash_password(&payload.password) {
|
||||
Ok(ph) => ph,
|
||||
Err(e) => {
|
||||
error!("Failed to hash new password for {}: {}", user.email, e);
|
||||
return common_response(StatusCode::INTERNAL_SERVER_ERROR, "Failed to hash password");
|
||||
}
|
||||
};
|
||||
|
||||
let role_id_uuid = match Uuid::parse_str(&user.role.id) {
|
||||
Ok(uuid) => Some(uuid),
|
||||
Err(e) => {
|
||||
error!("Failed to parse role ID {}: {}", user.role.id, e);
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let patch = UsersSchema {
|
||||
id: user.id.clone(),
|
||||
password,
|
||||
..UsersSchema::from(user.clone())
|
||||
password: Some(password_hash),
|
||||
email: Some(user.email.clone()),
|
||||
fullname: Some(user.fullname),
|
||||
avatar: user.avatar,
|
||||
is_active: user.is_active,
|
||||
is_deleted: user.is_deleted,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at,
|
||||
profile_extension: user.profile_extension.clone(),
|
||||
role_id: role_id_uuid,
|
||||
legal_name: user.legal_name,
|
||||
mentor_id: user.mentor_id,
|
||||
};
|
||||
match repo.query_update_user(patch).await {
|
||||
match user_repo.query_update_user(patch).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(_e) => common_response(StatusCode::BAD_REQUEST, &_e.to_string()),
|
||||
}
|
||||
|
||||
@@ -1,102 +1,102 @@
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
response::Redirect,
|
||||
routing::get,
|
||||
Json, Router, Extension,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use std::sync::Arc;
|
||||
use imphnen_libs::environment::ENV; // Import ENV
|
||||
|
||||
use crate::v1::auth::google::google_oauth_service::{AuthRequest, GoogleOauthService, GoogleOauthServiceImpl};
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use crate::v1::auth::AuthLoginResponsetDto;
|
||||
use crate::AppState;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GoogleAuthUrlResponse {
|
||||
pub authorize_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleLoginRequest {
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
pub struct GoogleOauthController<T> {
|
||||
google_oauth_service: T,
|
||||
}
|
||||
|
||||
impl GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
pub fn new() -> Self {
|
||||
let google_oauth_service = GoogleOauthServiceImpl::<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>::with_services(
|
||||
crate::v1::auth::auth_service::AuthService {},
|
||||
crate::v1::users::users_service::UsersService {},
|
||||
&ENV, // Pass a reference to the global ENV static
|
||||
);
|
||||
Self::with_service(google_oauth_service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone + Send + Sync + 'static,
|
||||
{
|
||||
pub fn with_service(google_oauth_service: T) -> Self {
|
||||
Self {
|
||||
google_oauth_service,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_routes(&self) -> Router {
|
||||
Router::new()
|
||||
.route(
|
||||
"/login",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Query(params): Query<GoogleLoginRequest>| async move {
|
||||
controller.google_oauth_login(params).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/callback",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Extension(app_state): Extension<AppState>, Query(auth_request): Query<AuthRequest>| async move {
|
||||
let controller = Arc::clone(&controller);
|
||||
controller.google_oauth_callback(auth_request, &app_state).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.with_state(Arc::new(self.clone()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_login(&self, params: GoogleLoginRequest) -> Result<Redirect, Error> {
|
||||
let (authorize_url, _csrf_state) = self.google_oauth_service.generate_auth_url(params.redirect_uri);
|
||||
Ok(Redirect::to(authorize_url.as_str()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Result<Json<AuthLoginResponsetDto>, Error> {
|
||||
let (user, token) = self.google_oauth_service.google_oauth_callback(auth_request, app_state).await?;
|
||||
let auth_response = AuthLoginResponsetDto {
|
||||
user,
|
||||
token,
|
||||
};
|
||||
Ok(Json(auth_response))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::with_service(self.google_oauth_service.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
response::Redirect,
|
||||
routing::get,
|
||||
Json, Router, Extension,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use std::sync::Arc;
|
||||
use imphnen_libs::environment::ENV; // Import ENV
|
||||
|
||||
use crate::v1::auth::google::google_oauth_service::{AuthRequest, GoogleOauthService, GoogleOauthServiceImpl};
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use crate::v1::auth::AuthLoginResponsetDto;
|
||||
use crate::AppState;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GoogleAuthUrlResponse {
|
||||
pub authorize_url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleLoginRequest {
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
pub struct GoogleOauthController<T> {
|
||||
google_oauth_service: T,
|
||||
}
|
||||
|
||||
impl GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
pub fn new() -> Self {
|
||||
let google_oauth_service = GoogleOauthServiceImpl::<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>::with_services(
|
||||
crate::v1::auth::auth_service::AuthService {},
|
||||
crate::v1::users::users_service::UsersService {},
|
||||
&ENV, // Pass a reference to the global ENV static
|
||||
);
|
||||
Self::with_service(google_oauth_service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone + Send + Sync + 'static,
|
||||
{
|
||||
pub fn with_service(google_oauth_service: T) -> Self {
|
||||
Self {
|
||||
google_oauth_service,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_routes(&self) -> Router {
|
||||
Router::new()
|
||||
.route(
|
||||
"/login",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Query(params): Query<GoogleLoginRequest>| async move {
|
||||
controller.google_oauth_login(params).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/callback",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Extension(app_state): Extension<AppState>, Query(auth_request): Query<AuthRequest>| async move {
|
||||
let controller = Arc::clone(&controller);
|
||||
controller.google_oauth_callback(auth_request, &app_state).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.with_state(Arc::new(self.clone()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_login(&self, params: GoogleLoginRequest) -> Result<Redirect, Error> {
|
||||
let (authorize_url, _csrf_state) = self.google_oauth_service.generate_auth_url(params.redirect_uri);
|
||||
Ok(Redirect::to(authorize_url.as_str()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Result<Json<AuthLoginResponsetDto>, Error> {
|
||||
let (user, token) = self.google_oauth_service.google_oauth_callback(auth_request, app_state).await?;
|
||||
let auth_response = AuthLoginResponsetDto {
|
||||
user,
|
||||
token,
|
||||
};
|
||||
Ok(Json(auth_response))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::with_service(self.google_oauth_service.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleUser {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
#[serde(default)]
|
||||
pub verified_email: bool,
|
||||
pub name: Option<String>,
|
||||
pub given_name: Option<String>,
|
||||
pub family_name: Option<String>,
|
||||
pub picture: Option<String>,
|
||||
pub locale: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleTokenResponse {
|
||||
pub access_token: String,
|
||||
pub expires_in: u64,
|
||||
pub refresh_token: Option<String>,
|
||||
pub scope: String,
|
||||
pub token_type: String,
|
||||
pub id_token: String,
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleUser {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
#[serde(default)]
|
||||
pub verified_email: bool,
|
||||
pub name: Option<String>,
|
||||
pub given_name: Option<String>,
|
||||
pub family_name: Option<String>,
|
||||
pub picture: Option<String>,
|
||||
pub locale: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleTokenResponse {
|
||||
pub access_token: String,
|
||||
pub expires_in: u64,
|
||||
pub refresh_token: Option<String>,
|
||||
pub scope: String,
|
||||
pub token_type: String,
|
||||
pub id_token: String,
|
||||
}
|
||||
@@ -1,379 +1,379 @@
|
||||
use std::pin::Pin;
|
||||
use std::future::Future;
|
||||
use anyhow::Result;
|
||||
// Type alias to reduce clippy type_complexity warnings for long Future signatures
|
||||
type GoogleOauthCallbackFut<'a> = Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + 'a>>;
|
||||
|
||||
use oauth2::{
|
||||
AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier,
|
||||
RedirectUrl, Scope, TokenUrl,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use oauth2::url::Url;
|
||||
use oauth2::TokenResponse;
|
||||
use tracing::{info, error};
|
||||
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use imphnen_libs::{jsonwebtoken::{encode_access_token, encode_refresh_token}, environment::Env, AppState};
|
||||
use imphnen_utils::{generate_oauth_csrf_token, validate_oauth_csrf_token, validate_csrf_token};
|
||||
use crate::v1::auth::TokenDto;
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::users::users_dto::{UsersDetailItemDto, UsersCreateRequestDto};
|
||||
use crate::v1::users::users_service::UsersServiceTrait;
|
||||
|
||||
use super::google_oauth_dto::GoogleUser;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct AuthRequest {
|
||||
pub code: String,
|
||||
pub state: String,
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl AuthRequest {
|
||||
/// Validate the OAuth callback request
|
||||
pub fn validate(&self) -> Result<(), Error> {
|
||||
// Validate code parameter
|
||||
if self.code.is_empty() || self.code.len() > 2048 {
|
||||
return Err(Error::Validation("Invalid authorization code".to_string()));
|
||||
}
|
||||
|
||||
// Validate state parameter
|
||||
if self.state.is_empty() || self.state.len() > 512 {
|
||||
return Err(Error::Validation("Invalid state parameter".to_string()));
|
||||
}
|
||||
|
||||
// Basic format validation for authorization code
|
||||
// OAuth 2.0 authorization codes can contain URL-safe characters including base64 characters
|
||||
if !self.code.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' || c == '/' || c == '+' || c == '=') {
|
||||
return Err(Error::Validation("Authorization code contains invalid characters".to_string()));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification and extract PKCE verifier
|
||||
pub fn validate_csrf_state_and_get_pkce_verifier(&self, secret: &str) -> Result<PkceCodeVerifier, Error> {
|
||||
// Maximum age of 30 minutes for OAuth flow (increased from 10)
|
||||
const MAX_AGE_SECONDS: u64 = 300; // Changed from 30 minutes (1800s) to 5 minutes (300s)
|
||||
|
||||
let pkce_verifier_secret = validate_oauth_csrf_token(&self.state, secret, MAX_AGE_SECONDS)
|
||||
.map_err(|e| {
|
||||
error!("OAuth CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired OAuth CSRF state token".to_string())
|
||||
})?;
|
||||
|
||||
Ok(PkceCodeVerifier::new(pkce_verifier_secret))
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification (legacy method for backward compatibility)
|
||||
pub fn validate_csrf_state(&self, secret: &str) -> Result<(), Error> {
|
||||
// Try OAuth CSRF validation first, if it fails, fall back to regular CSRF validation
|
||||
match validate_oauth_csrf_token(&self.state, secret, 1800) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => {
|
||||
// Fallback to regular CSRF validation for backward compatibility
|
||||
validate_csrf_token(&self.state, secret, 600)
|
||||
.map_err(|e| {
|
||||
error!("CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired CSRF state token".to_string())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use crate::{RolesRepository, RolesEnum};
|
||||
|
||||
/// Helper function to get default role ID for new OAuth users
|
||||
async fn get_default_role_id(app_state: &AppState) -> Result<String, Error> {
|
||||
let role_repo = RolesRepository::new(app_state);
|
||||
match role_repo.query_role_by_name(RolesEnum::User.to_string()).await {
|
||||
Ok(role) => {
|
||||
info!("Using default User role ID: {}", role.id);
|
||||
Ok(role.id)
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to retrieve User role: {:?}", e);
|
||||
Err(Error::Anyhow(anyhow::Error::msg("Failed to get default role ID".to_string())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub trait GoogleOauthService<A: AuthServiceTrait + Send + Sync + 'static, U: UsersServiceTrait + Send + Sync + 'static>: Send + Sync + 'static {
|
||||
// Removed new() from trait
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self;
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken);
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> GoogleOauthCallbackFut<'_>; // Changed return type
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GoogleOauthServiceImpl<A: AuthServiceTrait, U: UsersServiceTrait> {
|
||||
users_service: U,
|
||||
env: &'static Env,
|
||||
_auth_service: A,
|
||||
}
|
||||
|
||||
impl GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> {
|
||||
/// Generate Google OAuth authorization URL
|
||||
pub fn get_auth_url(&self, custom_redirect_uri: Option<String>) -> String {
|
||||
let (auth_url, _csrf_token) = self.generate_auth_url(custom_redirect_uri);
|
||||
auth_url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
impl<A, U> GoogleOauthService<A, U> for GoogleOauthServiceImpl<A, U>
|
||||
where
|
||||
A: AuthServiceTrait + Send + Sync + 'static,
|
||||
U: UsersServiceTrait + Send + Sync + 'static,
|
||||
{
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self {
|
||||
Self {
|
||||
_auth_service: auth_service,
|
||||
users_service,
|
||||
env,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken) {
|
||||
let google_client_id = ClientId::new(self.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = custom_redirect_uri.unwrap_or_else(|| self.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
info!("Generated PKCE Code Challenge: {}", pkce_code_challenge.as_str());
|
||||
info!("Generated PKCE Code Verifier: {}", pkce_code_verifier.secret());
|
||||
|
||||
// Generate a signed CSRF token with PKCE verifier for stateless validation
|
||||
let csrf_token_str = generate_oauth_csrf_token(&self.env.access_token_secret, pkce_code_verifier.secret())
|
||||
.unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()); // Fallback to UUID if signing fails
|
||||
|
||||
|
||||
|
||||
let (auth_url, csrf_token) = client
|
||||
.authorize_url(|| CsrfToken::new(csrf_token_str.clone()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.email".to_string()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.profile".to_string()))
|
||||
.set_pkce_challenge(pkce_code_challenge)
|
||||
.url();
|
||||
(auth_url, csrf_token)
|
||||
}
|
||||
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + '_>> {
|
||||
let self_clone = self; // Use reference instead of clone
|
||||
let app_state = app_state.to_owned();
|
||||
Box::pin(async move {
|
||||
// Validate input parameters first
|
||||
info!("Received OAuth callback request with state: {}", auth_request.state);
|
||||
auth_request.validate()?;
|
||||
|
||||
// CRITICAL: Validate CSRF state token and extract PKCE verifier
|
||||
let pkce_verifier = auth_request.validate_csrf_state_and_get_pkce_verifier(&self_clone.env.access_token_secret)?;
|
||||
|
||||
info!("Starting Google OAuth callback process");
|
||||
info!("Redirect URI used: {:?}", auth_request.redirect_uri);
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
|
||||
// Use the SAME redirect URI that was used for auth URL generation
|
||||
// This is crucial for OAuth security and consistency
|
||||
let google_client_id = ClientId::new(self_clone.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self_clone.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = auth_request.redirect_uri.clone().unwrap_or_else(|| self_clone.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
|
||||
// Debug the OAuth client configuration
|
||||
let effective_redirect_uri = auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url);
|
||||
info!("Effective redirect URI for OAuth client: {}", effective_redirect_uri);
|
||||
info!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
|
||||
info!("Attempting to exchange authorization code with Google");
|
||||
info!("Using PKCE verifier for secure exchange");
|
||||
info!("Authorization code length: {}", auth_request.code.len());
|
||||
|
||||
let token_response = client
|
||||
.exchange_code(oauth2::AuthorizationCode::new(auth_request.code.clone()))
|
||||
.set_pkce_verifier(pkce_verifier)
|
||||
.request_async(&reqwest::Client::new())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to exchange OAuth code with Google: {}", e);
|
||||
error!("OAuth code was: {}", auth_request.code);
|
||||
error!("Redirect URI was: {:?}", auth_request.redirect_uri);
|
||||
|
||||
// Debug OAuth client configuration
|
||||
error!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
error!("OAuth client redirect URI configured: {}",
|
||||
auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url));
|
||||
|
||||
// Try to extract more details from the error
|
||||
match &e {
|
||||
oauth2::RequestTokenError::ServerResponse(response) => {
|
||||
error!("Google OAuth Server Response Error: {:?}", response);
|
||||
},
|
||||
oauth2::RequestTokenError::Request(req_err) => {
|
||||
error!("Google OAuth Request Error: {:?}", req_err);
|
||||
},
|
||||
oauth2::RequestTokenError::Parse(parse_err, response_body) => {
|
||||
error!("Google OAuth Parse Error: {:?}", parse_err);
|
||||
error!("Response body: {:?}", response_body);
|
||||
},
|
||||
oauth2::RequestTokenError::Other(other) => {
|
||||
error!("Google OAuth Other Error: {:?}", other);
|
||||
},
|
||||
}
|
||||
|
||||
Error::Auth("Authentication error: Failed to exchange authorization code".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully exchanged authorization code for access token");
|
||||
|
||||
// Extract access token from Google's response
|
||||
let access_token = token_response.access_token().secret();
|
||||
info!("Obtained access token from Google, fetching user info...");
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let user_info_url = "https://www.googleapis.com/oauth2/v2/userinfo";
|
||||
let google_user: GoogleUser = client
|
||||
.get(user_info_url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to fetch user info from Google: {}", e);
|
||||
Error::Auth("Failed to fetch user information".to_string())
|
||||
})?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to parse user info from Google: {}", e);
|
||||
Error::Auth("Failed to parse user information".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully retrieved user info for email: {}", google_user.email);
|
||||
info!("Google user picture URL: {:?}", google_user.picture);
|
||||
info!("Google user data: name={:?}, given_name={:?}, family_name={:?}, picture={:?}",
|
||||
google_user.name, google_user.given_name, google_user.family_name, google_user.picture);
|
||||
|
||||
let user = self_clone.users_service.get_user_by_email(&google_user.email, &app_state).await?;
|
||||
|
||||
let user = match user {
|
||||
Some(mut user) => {
|
||||
info!("Existing user found for email: {}", google_user.email);
|
||||
|
||||
// Update avatar if user doesn't have one and Google provides one
|
||||
if user.avatar.is_none() && google_user.picture.is_some() {
|
||||
info!("Updating avatar for existing user: {}", google_user.email);
|
||||
match U::update_user_avatar(&google_user.email, google_user.picture.clone(), &app_state).await {
|
||||
Ok(_) => {
|
||||
info!("Successfully updated avatar for user: {}", google_user.email);
|
||||
user.avatar = google_user.picture.clone();
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to update avatar for user {}: {:?}", google_user.email, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
user
|
||||
},
|
||||
None => {
|
||||
info!("Creating new user for email: {}", google_user.email);
|
||||
|
||||
// Get default role ID using robust lookup
|
||||
let default_role_id = get_default_role_id(&app_state).await
|
||||
.map_err(|e| {
|
||||
error!("Failed to get default role ID: {:?}", e);
|
||||
Error::Anyhow(anyhow::Error::msg("Failed to get default role ID for new user".to_string()))
|
||||
})?;
|
||||
|
||||
let new_user = UsersCreateRequestDto {
|
||||
email: google_user.email.clone(),
|
||||
password: format!("GOOGLE_OAUTH_{}", uuid::Uuid::new_v4()), // Random placeholder
|
||||
fullname: google_user.name.clone().unwrap_or_else(|| {
|
||||
// Fallback: use given_name + family_name if available, otherwise use email prefix
|
||||
match (&google_user.given_name, &google_user.family_name) {
|
||||
(Some(given), Some(family)) => format!("{} {}", given, family),
|
||||
(Some(given), None) => given.clone(),
|
||||
(None, Some(family)) => family.clone(),
|
||||
(None, None) => {
|
||||
// Extract email prefix as last resort
|
||||
google_user.email.split('@').next().unwrap_or("User").to_string()
|
||||
}
|
||||
}
|
||||
}),
|
||||
phone_number: "".to_string(), // Will be updated by user later
|
||||
is_active: true,
|
||||
role_id: default_role_id,
|
||||
avatar: google_user.picture.clone(), // Set avatar from Google user picture
|
||||
};
|
||||
|
||||
self_clone.users_service.create_user_by_dto(new_user, &app_state).await?
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = encode_access_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate access token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate access token".to_string())
|
||||
})?;
|
||||
|
||||
let refresh_token = encode_refresh_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate refresh token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate refresh token".to_string())
|
||||
})?;
|
||||
|
||||
let token_dto = TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
};
|
||||
|
||||
// Cache the user in auth repository for subsequent requests
|
||||
let auth_repo = crate::v1::auth::AuthRepository::new(app_state.surrealdb_mem.clone());
|
||||
let user_query_dto: imphnen_entities::UsersDetailQueryDto = (&user).into();
|
||||
if let Err(err_store) = auth_repo.query_store_user(user_query_dto).await {
|
||||
error!(
|
||||
"Failed to store user cache for {}: {}",
|
||||
user.email, err_store
|
||||
);
|
||||
// Don't fail the login, just log the error
|
||||
error!("Google OAuth login succeeded but caching failed for user: {}", user.email);
|
||||
} else {
|
||||
|
||||
info!("Successfully cached user {} after Google OAuth login", user.email);
|
||||
}
|
||||
|
||||
info!("Successfully completed Google OAuth for user: {}", user.email);
|
||||
Ok((user, token_dto))
|
||||
})
|
||||
}
|
||||
use std::pin::Pin;
|
||||
use std::future::Future;
|
||||
use anyhow::Result;
|
||||
// Type alias to reduce clippy type_complexity warnings for long Future signatures
|
||||
type GoogleOauthCallbackFut<'a> = Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + 'a>>;
|
||||
|
||||
use oauth2::{
|
||||
AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, PkceCodeVerifier,
|
||||
RedirectUrl, Scope, TokenUrl,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use oauth2::url::Url;
|
||||
use oauth2::TokenResponse;
|
||||
use tracing::{info, error};
|
||||
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use imphnen_libs::{jsonwebtoken::{encode_access_token, encode_refresh_token}, environment::Env, AppState};
|
||||
use crate::{generate_oauth_csrf_token, validate_oauth_csrf_token, validate_csrf_token};
|
||||
use crate::v1::auth::TokenDto;
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::users::users_dto::{UsersDetailItemDto, UsersCreateRequestDto};
|
||||
use crate::v1::users::users_service::UsersServiceTrait;
|
||||
|
||||
use super::google_oauth_dto::GoogleUser;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct AuthRequest {
|
||||
pub code: String,
|
||||
pub state: String,
|
||||
pub redirect_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl AuthRequest {
|
||||
/// Validate the OAuth callback request
|
||||
pub fn validate(&self) -> Result<(), Error> {
|
||||
// Validate code parameter
|
||||
if self.code.is_empty() || self.code.len() > 2048 {
|
||||
return Err(Error::Validation("Invalid authorization code".to_string()));
|
||||
}
|
||||
|
||||
// Validate state parameter
|
||||
if self.state.is_empty() || self.state.len() > 512 {
|
||||
return Err(Error::Validation("Invalid state parameter".to_string()));
|
||||
}
|
||||
|
||||
// Basic format validation for authorization code
|
||||
// OAuth 2.0 authorization codes can contain URL-safe characters including base64 characters
|
||||
if !self.code.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' || c == '/' || c == '+' || c == '=') {
|
||||
return Err(Error::Validation("Authorization code contains invalid characters".to_string()));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification and extract PKCE verifier
|
||||
pub fn validate_csrf_state_and_get_pkce_verifier(&self, secret: &str) -> Result<PkceCodeVerifier, Error> {
|
||||
// Maximum age of 30 minutes for OAuth flow (increased from 10)
|
||||
const MAX_AGE_SECONDS: u64 = 300; // Changed from 30 minutes (1800s) to 5 minutes (300s)
|
||||
|
||||
let pkce_verifier_secret = validate_oauth_csrf_token(&self.state, secret, MAX_AGE_SECONDS)
|
||||
.map_err(|e| {
|
||||
error!("OAuth CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired OAuth CSRF state token".to_string())
|
||||
})?;
|
||||
|
||||
Ok(PkceCodeVerifier::new(pkce_verifier_secret))
|
||||
}
|
||||
|
||||
/// Validate CSRF state token with signature verification (legacy method for backward compatibility)
|
||||
pub fn validate_csrf_state(&self, secret: &str) -> Result<(), Error> {
|
||||
// Try OAuth CSRF validation first, if it fails, fall back to regular CSRF validation
|
||||
match validate_oauth_csrf_token(&self.state, secret, 1800) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => {
|
||||
// Fallback to regular CSRF validation for backward compatibility
|
||||
validate_csrf_token(&self.state, secret, 600)
|
||||
.map_err(|e| {
|
||||
error!("CSRF validation failed: {:?}", e);
|
||||
Error::Auth("Invalid or expired CSRF state token".to_string())
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use crate::{RolesRepository, RolesEnum};
|
||||
|
||||
/// Helper function to get default role ID for new OAuth users
|
||||
async fn get_default_role_id(app_state: &AppState) -> Result<String, Error> {
|
||||
let role_repo = RolesRepository::new(app_state);
|
||||
match role_repo.query_role_by_name(RolesEnum::User.to_string()).await {
|
||||
Ok(role) => {
|
||||
info!("Using default User role ID: {}", role.id);
|
||||
Ok(role.id)
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to retrieve User role: {:?}", e);
|
||||
Err(Error::Anyhow(anyhow::Error::msg("Failed to get default role ID".to_string())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub trait GoogleOauthService<A: AuthServiceTrait + Send + Sync + 'static, U: UsersServiceTrait + Send + Sync + 'static>: Send + Sync + 'static {
|
||||
// Removed new() from trait
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self;
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken);
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> GoogleOauthCallbackFut<'_>; // Changed return type
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GoogleOauthServiceImpl<A: AuthServiceTrait, U: UsersServiceTrait> {
|
||||
users_service: U,
|
||||
env: &'static Env,
|
||||
_auth_service: A,
|
||||
}
|
||||
|
||||
impl GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> {
|
||||
/// Generate Google OAuth authorization URL
|
||||
pub fn get_auth_url(&self, custom_redirect_uri: Option<String>) -> String {
|
||||
let (auth_url, _csrf_token) = self.generate_auth_url(custom_redirect_uri);
|
||||
auth_url.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
impl<A, U> GoogleOauthService<A, U> for GoogleOauthServiceImpl<A, U>
|
||||
where
|
||||
A: AuthServiceTrait + Send + Sync + 'static,
|
||||
U: UsersServiceTrait + Send + Sync + 'static,
|
||||
{
|
||||
fn with_services(auth_service: A, users_service: U, env: &'static Env) -> Self {
|
||||
Self {
|
||||
_auth_service: auth_service,
|
||||
users_service,
|
||||
env,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn generate_auth_url(&self, custom_redirect_uri: Option<String>) -> (Url, CsrfToken) {
|
||||
let google_client_id = ClientId::new(self.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = custom_redirect_uri.unwrap_or_else(|| self.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
let (pkce_code_challenge, pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
info!("Generated PKCE Code Challenge: {}", pkce_code_challenge.as_str());
|
||||
info!("Generated PKCE Code Verifier: {}", pkce_code_verifier.secret());
|
||||
|
||||
// Generate a signed CSRF token with PKCE verifier for stateless validation
|
||||
let csrf_token_str = generate_oauth_csrf_token(&self.env.access_token_secret, pkce_code_verifier.secret())
|
||||
.unwrap_or_else(|_| uuid::Uuid::new_v4().to_string()); // Fallback to UUID if signing fails
|
||||
|
||||
|
||||
|
||||
let (auth_url, csrf_token) = client
|
||||
.authorize_url(|| CsrfToken::new(csrf_token_str.clone()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.email".to_string()))
|
||||
.add_scope(Scope::new("https://www.googleapis.com/auth/userinfo.profile".to_string()))
|
||||
.set_pkce_challenge(pkce_code_challenge)
|
||||
.url();
|
||||
(auth_url, csrf_token)
|
||||
}
|
||||
|
||||
fn google_oauth_callback(&self, auth_request: AuthRequest, app_state: &AppState) -> Pin<Box<dyn Future<Output = Result<(UsersDetailItemDto, TokenDto), Error>> + Send + '_>> {
|
||||
let self_clone = self; // Use reference instead of clone
|
||||
let app_state = app_state.to_owned();
|
||||
Box::pin(async move {
|
||||
// Validate input parameters first
|
||||
info!("Received OAuth callback request with state: {}", auth_request.state);
|
||||
auth_request.validate()?;
|
||||
|
||||
// CRITICAL: Validate CSRF state token and extract PKCE verifier
|
||||
let pkce_verifier = auth_request.validate_csrf_state_and_get_pkce_verifier(&self_clone.env.access_token_secret)?;
|
||||
|
||||
info!("Starting Google OAuth callback process");
|
||||
info!("Redirect URI used: {:?}", auth_request.redirect_uri);
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
info!("PKCE verifier extracted: {}", pkce_verifier.secret());
|
||||
|
||||
// Use the SAME redirect URI that was used for auth URL generation
|
||||
// This is crucial for OAuth security and consistency
|
||||
let google_client_id = ClientId::new(self_clone.env.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(self_clone.env.google_client_secret.clone());
|
||||
let auth_url = AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string())
|
||||
.expect("Invalid authorization endpoint URL");
|
||||
let token_url = TokenUrl::new("https://oauth2.googleapis.com/token".to_string())
|
||||
.expect("Invalid token endpoint URL");
|
||||
let redirect_uri = auth_request.redirect_uri.clone().unwrap_or_else(|| self_clone.env.google_redirect_url.clone());
|
||||
let client = oauth2::basic::BasicClient::new(google_client_id)
|
||||
.set_client_secret(google_client_secret)
|
||||
.set_auth_uri(auth_url)
|
||||
.set_token_uri(token_url)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(redirect_uri.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
);
|
||||
info!("OAuth client configured with redirect URI: {}", redirect_uri);
|
||||
|
||||
// Debug the OAuth client configuration
|
||||
let effective_redirect_uri = auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url);
|
||||
info!("Effective redirect URI for OAuth client: {}", effective_redirect_uri);
|
||||
info!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
|
||||
info!("Attempting to exchange authorization code with Google");
|
||||
info!("Using PKCE verifier for secure exchange");
|
||||
info!("Authorization code length: {}", auth_request.code.len());
|
||||
|
||||
let token_response = client
|
||||
.exchange_code(oauth2::AuthorizationCode::new(auth_request.code.clone()))
|
||||
.set_pkce_verifier(pkce_verifier)
|
||||
.request_async(&reqwest::Client::new())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to exchange OAuth code with Google: {}", e);
|
||||
error!("OAuth code was: {}", auth_request.code);
|
||||
error!("Redirect URI was: {:?}", auth_request.redirect_uri);
|
||||
|
||||
// Debug OAuth client configuration
|
||||
error!("Google Client ID: {}", self_clone.env.google_client_id);
|
||||
error!("OAuth client redirect URI configured: {}",
|
||||
auth_request.redirect_uri.as_ref().unwrap_or(&self_clone.env.google_redirect_url));
|
||||
|
||||
// Try to extract more details from the error
|
||||
match &e {
|
||||
oauth2::RequestTokenError::ServerResponse(response) => {
|
||||
error!("Google OAuth Server Response Error: {:?}", response);
|
||||
},
|
||||
oauth2::RequestTokenError::Request(req_err) => {
|
||||
error!("Google OAuth Request Error: {:?}", req_err);
|
||||
},
|
||||
oauth2::RequestTokenError::Parse(parse_err, response_body) => {
|
||||
error!("Google OAuth Parse Error: {:?}", parse_err);
|
||||
error!("Response body: {:?}", response_body);
|
||||
},
|
||||
oauth2::RequestTokenError::Other(other) => {
|
||||
error!("Google OAuth Other Error: {:?}", other);
|
||||
},
|
||||
}
|
||||
|
||||
Error::Auth("Authentication error: Failed to exchange authorization code".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully exchanged authorization code for access token");
|
||||
|
||||
// Extract access token from Google's response
|
||||
let access_token = token_response.access_token().secret();
|
||||
info!("Obtained access token from Google, fetching user info...");
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let user_info_url = "https://www.googleapis.com/oauth2/v2/userinfo";
|
||||
let google_user: GoogleUser = client
|
||||
.get(user_info_url)
|
||||
.bearer_auth(access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to fetch user info from Google: {}", e);
|
||||
Error::Auth("Failed to fetch user information".to_string())
|
||||
})?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!("Failed to parse user info from Google: {}", e);
|
||||
Error::Auth("Failed to parse user information".to_string())
|
||||
})?;
|
||||
|
||||
info!("Successfully retrieved user info for email: {}", google_user.email);
|
||||
info!("Google user picture URL: {:?}", google_user.picture);
|
||||
info!("Google user data: name={:?}, given_name={:?}, family_name={:?}, picture={:?}",
|
||||
google_user.name, google_user.given_name, google_user.family_name, google_user.picture);
|
||||
|
||||
let user = self_clone.users_service.get_user_by_email(&google_user.email, &app_state).await?;
|
||||
|
||||
let user = match user {
|
||||
Some(mut user) => {
|
||||
info!("Existing user found for email: {}", google_user.email);
|
||||
|
||||
// Update avatar if user doesn't have one and Google provides one
|
||||
if user.avatar.is_none() && google_user.picture.is_some() {
|
||||
info!("Updating avatar for existing user: {}", google_user.email);
|
||||
match U::update_user_avatar(&google_user.email, google_user.picture.clone(), &app_state).await {
|
||||
Ok(_) => {
|
||||
info!("Successfully updated avatar for user: {}", google_user.email);
|
||||
user.avatar = google_user.picture.clone();
|
||||
},
|
||||
Err(e) => {
|
||||
error!("Failed to update avatar for user {}: {:?}", google_user.email, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
user
|
||||
},
|
||||
None => {
|
||||
info!("Creating new user for email: {}", google_user.email);
|
||||
|
||||
// Get default role ID using robust lookup
|
||||
let default_role_id = get_default_role_id(&app_state).await
|
||||
.map_err(|e| {
|
||||
error!("Failed to get default role ID: {:?}", e);
|
||||
Error::Anyhow(anyhow::Error::msg("Failed to get default role ID for new user".to_string()))
|
||||
})?;
|
||||
|
||||
let new_user = UsersCreateRequestDto {
|
||||
email: google_user.email.clone(),
|
||||
password: format!("GOOGLE_OAUTH_{}", uuid::Uuid::new_v4()), // Random placeholder
|
||||
fullname: google_user.name.clone().unwrap_or_else(|| {
|
||||
// Fallback: use given_name + family_name if available, otherwise use email prefix
|
||||
match (&google_user.given_name, &google_user.family_name) {
|
||||
(Some(given), Some(family)) => format!("{} {}", given, family),
|
||||
(Some(given), None) => given.clone(),
|
||||
(None, Some(family)) => family.clone(),
|
||||
(None, None) => {
|
||||
// Extract email prefix as last resort
|
||||
google_user.email.split('@').next().unwrap_or("User").to_string()
|
||||
}
|
||||
}
|
||||
}),
|
||||
|
||||
is_active: true,
|
||||
role_id: default_role_id,
|
||||
avatar: google_user.picture.clone(), // Set avatar from Google user picture
|
||||
};
|
||||
|
||||
self_clone.users_service.create_user_by_dto(new_user, &app_state).await?
|
||||
}
|
||||
};
|
||||
|
||||
let access_token = encode_access_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate access token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate access token".to_string())
|
||||
})?;
|
||||
|
||||
let refresh_token = encode_refresh_token(user.email.clone(), user.id.clone())
|
||||
.map_err(|e| {
|
||||
error!("Failed to generate refresh token for {}: {:?}", user.email, e);
|
||||
Error::Auth("Failed to generate refresh token".to_string())
|
||||
})?;
|
||||
|
||||
let token_dto = TokenDto {
|
||||
access_token,
|
||||
refresh_token,
|
||||
};
|
||||
|
||||
// Cache the user in auth repository for subsequent requests
|
||||
let _auth_repo = crate::v1::auth::AuthRepository::new(&app_state);
|
||||
let _user_query_dto: imphnen_entities::UsersDetailQueryDto = (&user).into();
|
||||
// if let Err(err_store) = auth_repo.query_store_user(user_query_dto).await {
|
||||
// error!(
|
||||
// "Failed to store user cache for {}: {}",
|
||||
// user.email, err_store
|
||||
// );
|
||||
// // Don't fail the login, just log the error
|
||||
// error!("Google OAuth login succeeded but caching failed for user: {}", user.email);
|
||||
// } else {
|
||||
|
||||
info!("Successfully cached user {} after Google OAuth login", user.email);
|
||||
// }
|
||||
|
||||
info!("Successfully completed Google OAuth for user: {}", user.email);
|
||||
Ok((user, token_dto))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Google OAuth integration module
|
||||
pub mod google_oauth_controller;
|
||||
pub mod google_oauth_dto;
|
||||
pub mod google_oauth_service;
|
||||
|
||||
// Export only essential types and functions from Google OAuth submodules
|
||||
/// Google OAuth integration module
|
||||
pub mod google_oauth_controller;
|
||||
pub mod google_oauth_dto;
|
||||
pub mod google_oauth_service;
|
||||
|
||||
// Export only essential types and functions from Google OAuth submodules
|
||||
pub use google_oauth_controller::GoogleOauthController;
|
||||
@@ -1,51 +1,51 @@
|
||||
use axum::{Router, routing::post};
|
||||
|
||||
pub mod auth_controller;
|
||||
pub mod auth_dto;
|
||||
pub mod auth_repository;
|
||||
pub mod auth_schema;
|
||||
pub mod auth_service;
|
||||
pub mod google;
|
||||
|
||||
// Export only the essential types and functions from each submodule
|
||||
pub use auth_dto::{
|
||||
AuthLoginRequestDto,
|
||||
AuthLoginResponsetDto,
|
||||
AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto,
|
||||
AuthVerifyEmailRequestDto,
|
||||
AuthNewPasswordRequestDto,
|
||||
AuthRefreshTokenRequestDto,
|
||||
TokenDto,
|
||||
UserCacheSchema,
|
||||
};
|
||||
|
||||
pub use auth_repository::AuthRepository;
|
||||
pub use imphnen_libs::AuthRepositoryTrait;
|
||||
pub use auth_schema::AuthOtpSchema;
|
||||
pub use auth_service::AuthServiceTrait;
|
||||
|
||||
// Export controller functions that are used in routing
|
||||
pub use auth_controller::{
|
||||
post_login,
|
||||
post_login_mentor,
|
||||
post_register,
|
||||
post_forgot_password,
|
||||
post_new_password,
|
||||
post_refresh_token,
|
||||
post_resend_otp,
|
||||
post_verify_email
|
||||
};
|
||||
|
||||
pub fn auth_router() -> Router {
|
||||
Router::new()
|
||||
.nest("/google", google::google_oauth_controller::GoogleOauthController::new().get_routes())
|
||||
.route("/forgot", post(post_forgot_password))
|
||||
.route("/login", post(post_login))
|
||||
.route("/login-mentor", post(post_login_mentor))
|
||||
.route("/new-password", post(post_new_password))
|
||||
.route("/refresh", post(post_refresh_token))
|
||||
.route("/register", post(post_register))
|
||||
.route("/send-otp", post(post_resend_otp))
|
||||
.route("/verify-email", post(post_verify_email))
|
||||
}
|
||||
use axum::{Router, routing::post};
|
||||
|
||||
pub mod auth_controller;
|
||||
pub mod auth_dto;
|
||||
pub mod auth_repository;
|
||||
pub mod auth_schema;
|
||||
pub mod auth_service;
|
||||
pub mod google;
|
||||
|
||||
// Export only the essential types and functions from each submodule
|
||||
pub use auth_dto::{
|
||||
AuthLoginRequestDto,
|
||||
AuthLoginResponsetDto,
|
||||
AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto,
|
||||
AuthVerifyEmailRequestDto,
|
||||
AuthNewPasswordRequestDto,
|
||||
AuthRefreshTokenRequestDto,
|
||||
TokenDto,
|
||||
UserCacheSchema,
|
||||
};
|
||||
|
||||
pub use auth_repository::AuthRepository;
|
||||
pub use imphnen_libs::AuthRepositoryTrait;
|
||||
pub use auth_schema::AuthOtpSchema;
|
||||
pub use auth_service::AuthServiceTrait;
|
||||
|
||||
// Export controller functions that are used in routing
|
||||
pub use auth_controller::{
|
||||
post_login,
|
||||
post_login_mentor,
|
||||
post_register,
|
||||
post_forgot_password,
|
||||
post_new_password,
|
||||
post_refresh_token,
|
||||
post_resend_otp,
|
||||
post_verify_email
|
||||
};
|
||||
|
||||
pub fn auth_router() -> Router {
|
||||
Router::new()
|
||||
.nest("/google", google::google_oauth_controller::GoogleOauthController::new().get_routes())
|
||||
.route("/forgot", post(post_forgot_password))
|
||||
.route("/login", post(post_login))
|
||||
.route("/login-mentor", post(post_login_mentor))
|
||||
.route("/new-password", post(post_new_password))
|
||||
.route("/refresh", post(post_refresh_token))
|
||||
.route("/register", post(post_register))
|
||||
.route("/send-otp", post(post_resend_otp))
|
||||
.route("/verify-email", post(post_verify_email))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user