feat(auth): Implement Google OAuth 2.0 integration with user creation and JWT generation
- Added Google OAuth controller and service to handle authentication via Google. - Introduced DTOs for Google user and token responses. - Updated AuthService and UsersService traits to support new Google OAuth functionality. - Implemented logic to create a new user if they do not exist in the system after Google authentication. - Enhanced existing user retrieval and JWT generation upon successful login. - Added tests for Google OAuth flow, including login redirection and callback handling for both new and existing users. - Updated environment configuration to include Google OAuth credentials.
This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
use super::{
|
||||
AuthLoginRequestDto, AuthRefreshTokenRequestDto, AuthRegisterRequestDto,
|
||||
AuthResendOtpRequestDto, AuthService, AuthVerifyEmailRequestDto,
|
||||
AuthResendOtpRequestDto, AuthVerifyEmailRequestDto,
|
||||
};
|
||||
use crate::{AppState, v1::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,
|
||||
|
||||
@@ -15,10 +15,49 @@ use axum::{http::StatusCode, response::Response};
|
||||
use surrealdb::Uuid;
|
||||
use tracing::error;
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
#[async_trait]
|
||||
pub trait AuthServiceTrait: Send + Sync + 'static {
|
||||
async fn mutation_login(
|
||||
payload: AuthLoginRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response;
|
||||
async fn mutation_mentor_login(
|
||||
payload: AuthLoginRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response;
|
||||
async fn mutation_register(
|
||||
payload: AuthRegisterRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response;
|
||||
async fn mutation_resend_otp(
|
||||
payload: AuthResendOtpRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response;
|
||||
async fn mutation_refresh_token(
|
||||
payload: AuthRefreshTokenRequestDto,
|
||||
) -> Response;
|
||||
async fn mutation_forgot_password(
|
||||
payload: AuthResendOtpRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response;
|
||||
async fn mutation_verify_email(
|
||||
payload: AuthVerifyEmailRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response;
|
||||
async fn mutation_new_password(
|
||||
payload: AuthNewPasswordRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response;
|
||||
}
|
||||
|
||||
#[derive(Clone)] // Added Clone derive
|
||||
pub struct AuthService;
|
||||
|
||||
impl AuthService {
|
||||
pub async fn mutation_login(
|
||||
#[async_trait]
|
||||
impl AuthServiceTrait for AuthService {
|
||||
async fn mutation_login(
|
||||
payload: AuthLoginRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
@@ -104,7 +143,7 @@ impl AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_mentor_login(
|
||||
async fn mutation_mentor_login(
|
||||
payload: AuthLoginRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
@@ -199,7 +238,7 @@ impl AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_register(
|
||||
async fn mutation_register(
|
||||
payload: AuthRegisterRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
@@ -298,7 +337,7 @@ impl AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_resend_otp(
|
||||
async fn mutation_resend_otp(
|
||||
payload: AuthResendOtpRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
@@ -335,7 +374,7 @@ impl AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_refresh_token(
|
||||
async fn mutation_refresh_token(
|
||||
payload: AuthRefreshTokenRequestDto,
|
||||
) -> Response {
|
||||
if let Err((status, message)) = validate_request(&payload) {
|
||||
@@ -376,7 +415,7 @@ impl AuthService {
|
||||
success_response(response)
|
||||
}
|
||||
|
||||
pub async fn mutation_forgot_password(
|
||||
async fn mutation_forgot_password(
|
||||
payload: AuthResendOtpRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
@@ -431,7 +470,7 @@ impl AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_verify_email(
|
||||
async fn mutation_verify_email(
|
||||
payload: AuthVerifyEmailRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
@@ -478,7 +517,7 @@ impl AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn mutation_new_password(
|
||||
async fn mutation_new_password(
|
||||
payload: AuthNewPasswordRequestDto,
|
||||
state: &AppState,
|
||||
) -> Response {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
response::{IntoResponse, Redirect},
|
||||
routing::get,
|
||||
Json, Router,
|
||||
};
|
||||
use axum::http::StatusCode;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use std::sync::Arc; // Import Arc
|
||||
|
||||
use crate::v1::auth::google::google_oauth_service::{AuthRequest, GoogleOauthService, GoogleOauthServiceImpl};
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::users::users_service::UsersServiceTrait;
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, ToSchema)]
|
||||
pub struct GoogleAuthUrlResponse {
|
||||
pub authorize_url: String,
|
||||
}
|
||||
|
||||
pub struct GoogleOauthController<T> { // Generic over T
|
||||
google_oauth_service: T,
|
||||
}
|
||||
|
||||
// Concrete implementation for new()
|
||||
impl GoogleOauthController<GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
google_oauth_service: GoogleOauthServiceImpl::<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService>::new(), // Explicitly specify type parameters
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Generic implementation for with_service and get_routes
|
||||
impl<T> GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone + Send + Sync + 'static, // Explicitly constrain T
|
||||
{
|
||||
pub fn with_service(google_oauth_service: T) -> Self {
|
||||
Self {
|
||||
google_oauth_service,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_routes(&self) -> Router { // Take self by reference
|
||||
Router::new()
|
||||
.route(
|
||||
"/google/login",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>| async move {
|
||||
controller.google_oauth_login().await
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
"/google/callback",
|
||||
get(
|
||||
move |State(controller): State<Arc<Self>>, Query(auth_request): Query<AuthRequest>| async move {
|
||||
let controller = Arc::clone(&controller);
|
||||
controller.google_oauth_callback(auth_request).await
|
||||
},
|
||||
),
|
||||
)
|
||||
.with_state(Arc::new(self.clone())) // Pass an Arc clone of self to with_state
|
||||
}
|
||||
|
||||
pub async fn google_oauth_login(&self) -> Result<Redirect, Error> {
|
||||
let (authorize_url, _csrf_state) = self.google_oauth_service.generate_auth_url();
|
||||
Ok(Redirect::to(authorize_url.as_str()))
|
||||
}
|
||||
|
||||
pub async fn google_oauth_callback(&self, auth_request: AuthRequest) -> Result<impl IntoResponse + use<T>, Error> {
|
||||
let token = self.google_oauth_service.google_oauth_callback(auth_request).await?;
|
||||
Ok((StatusCode::OK, Json(serde_json::json!({"token": token}))))
|
||||
}
|
||||
}
|
||||
|
||||
// Clone implementation
|
||||
impl<T> Clone for GoogleOauthController<T>
|
||||
where
|
||||
T: GoogleOauthService<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> + Clone, // Explicitly constrain T
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::with_service(self.google_oauth_service.clone())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GoogleUser {
|
||||
pub id: String,
|
||||
pub email: String,
|
||||
pub verified_email: bool,
|
||||
pub name: String,
|
||||
pub given_name: String,
|
||||
pub family_name: String,
|
||||
pub picture: String,
|
||||
pub locale: 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,
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use oauth2::{
|
||||
basic::BasicClient, AuthUrl, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge,
|
||||
RedirectUrl, Scope, TokenResponse, TokenUrl,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use oauth2::url::Url;
|
||||
|
||||
use imphnen_entities::error_dto::error::Error;
|
||||
use imphnen_libs::{jsonwebtoken::generate_jwt, enviroment::ENV};
|
||||
use crate::v1::auth::auth_service::AuthServiceTrait;
|
||||
use crate::v1::users::users_dto::{UsersCreateRequestDto, UsersDetailItemDto};
|
||||
use crate::v1::users::users_service::UsersServiceTrait;
|
||||
|
||||
use super::google_oauth_dto::{GoogleTokenResponse, GoogleUser};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct AuthRequest {
|
||||
pub code: String,
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
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) -> Self;
|
||||
fn google_oauth_client(&self) -> BasicClient;
|
||||
fn generate_auth_url(&self) -> (Url, CsrfToken);
|
||||
async fn google_oauth_callback(&self, auth_request: AuthRequest) -> Result<String, Error>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GoogleOauthServiceImpl<A: AuthServiceTrait, U: UsersServiceTrait> {
|
||||
auth_service: A,
|
||||
users_service: U,
|
||||
}
|
||||
|
||||
impl GoogleOauthServiceImpl<crate::v1::auth::auth_service::AuthService, crate::v1::users::users_service::UsersService> {
|
||||
pub fn new() -> Self {
|
||||
GoogleOauthServiceImpl {
|
||||
auth_service: crate::v1::auth::auth_service::AuthService {},
|
||||
users_service: crate::v1::users::users_service::UsersService {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
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) -> Self {
|
||||
Self {
|
||||
auth_service,
|
||||
users_service,
|
||||
}
|
||||
}
|
||||
|
||||
fn google_oauth_client(&self) -> BasicClient {
|
||||
let google_client_id = ClientId::new(ENV.google_client_id.clone());
|
||||
let google_client_secret = ClientSecret::new(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");
|
||||
|
||||
BasicClient::new(
|
||||
google_client_id,
|
||||
Some(google_client_secret),
|
||||
auth_url,
|
||||
Some(token_url),
|
||||
)
|
||||
.set_redirect_uri(
|
||||
RedirectUrl::new(ENV.google_redirect_url.clone())
|
||||
.expect("Invalid redirect URL"),
|
||||
)
|
||||
}
|
||||
|
||||
fn generate_auth_url(&self) -> (Url, CsrfToken) {
|
||||
let client = self.google_oauth_client();
|
||||
let (pkce_code_challenge, _pkce_code_verifier) = PkceCodeChallenge::new_random_sha256();
|
||||
|
||||
client
|
||||
.authorize_url(CsrfToken::new_random)
|
||||
.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()
|
||||
}
|
||||
|
||||
async fn google_oauth_callback(&self, auth_request: AuthRequest) -> Result<String, Error> {
|
||||
let client = self.google_oauth_client();
|
||||
|
||||
let token_response = client
|
||||
.exchange_code(oauth2::AuthorizationCode::new(auth_request.code))
|
||||
.request_async(oauth2::reqwest::async_http_client)
|
||||
.await
|
||||
.map_err(|e| Error::Db(format!("Failed to exchange code: {}", e)))?;
|
||||
|
||||
let google_token_response: GoogleTokenResponse = serde_json::from_str(&token_response.access_token().secret())
|
||||
.map_err(|e| Error::Db(format!("Failed to parse Google token response: {}", e)))?;
|
||||
|
||||
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(google_token_response.access_token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::Db(format!("Failed to fetch user info: {}", e)))?
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| Error::Db(format!("Failed to parse user info: {}", e)))?;
|
||||
|
||||
let user = self.users_service.get_user_by_email(&google_user.email).await?;
|
||||
|
||||
let user = match user {
|
||||
Some(user) => user,
|
||||
None => {
|
||||
let new_user = UsersCreateRequestDto {
|
||||
email: google_user.email,
|
||||
password: "GOOGLE_OAUTH_PASSWORD".to_string(), // Placeholder password as it's not used
|
||||
fullname: google_user.name.clone(), // Use fullname for UsersCreateRequestDto
|
||||
phone_number: "N/A".to_string(), // Placeholder for phone number
|
||||
is_active: true, // Assuming active by default for new Google users
|
||||
role_id: "default_role_id".to_string(), // Placeholder for role_id
|
||||
};
|
||||
self.users_service.create_user_by_dto(new_user).await?
|
||||
}
|
||||
};
|
||||
|
||||
let token = generate_jwt(&user.id.to_string())?;
|
||||
Ok(token)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod google_oauth_controller;
|
||||
pub mod google_oauth_dto;
|
||||
pub mod google_oauth_service;
|
||||
@@ -5,6 +5,7 @@ pub mod auth_dto;
|
||||
pub mod auth_repository;
|
||||
pub mod auth_schema;
|
||||
pub mod auth_service;
|
||||
pub mod google;
|
||||
|
||||
pub use auth_dto::*;
|
||||
pub use auth_repository::*;
|
||||
@@ -13,6 +14,7 @@ pub use auth_service::*;
|
||||
|
||||
pub fn auth_router() -> Router {
|
||||
Router::new()
|
||||
.nest("/google", google::google_oauth_controller::GoogleOauthController::new().get_routes())
|
||||
.route("/forgot", post(auth_controller::post_forgot_password))
|
||||
.route("/login", post(auth_controller::post_login))
|
||||
.route("/login-mentor", post(auth_controller::post_login_mentor))
|
||||
|
||||
@@ -28,7 +28,7 @@ pub struct RolesListItemDto {
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema, Default)] // Added Default derive
|
||||
pub struct RolesDetailItemDto {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::{AppState, MetaRequestDto, v1::users_service::UsersService};
|
||||
use crate::{AppState, MetaRequestDto};
|
||||
use crate::{
|
||||
MessageResponseDto, PermissionsEnum, ResponseListSuccessDto, ResponseSuccessDto,
|
||||
UsersCreateRequestDto, UsersDetailItemDto, permissions_guard,
|
||||
};
|
||||
use axum::extract::{Path, Query};
|
||||
use axum::extract::{Path}; // Removed Query
|
||||
use axum::http::HeaderMap;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::{Extension, Json};
|
||||
@@ -11,6 +11,7 @@ use axum::{Extension, Json};
|
||||
use super::{
|
||||
UsersActiveInactiveRequestDto, UsersListItemDto, UsersUpdateRequestDto,
|
||||
};
|
||||
use crate::v1::users::users_service::{UsersServiceTrait, UsersService};
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
@@ -35,7 +36,7 @@ use super::{
|
||||
pub async fn get_user_list(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Query(meta): Query<MetaRequestDto>,
|
||||
Json(meta): Json<MetaRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
@@ -178,7 +179,7 @@ pub async fn put_update_user_me(
|
||||
Json(payload): Json<UsersUpdateRequestDto>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(&headers, state.clone(), vec![]).await {
|
||||
Ok(_) => UsersService::update_user_me(&state, headers, payload).await,
|
||||
Ok(_) => UsersService::update_user_me(headers, &state, payload).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize};
|
||||
use surrealdb::sql::Thing;
|
||||
use utoipa::ToSchema;
|
||||
use validator::Validate;
|
||||
use crate::UsersSchema; // Import UsersSchema
|
||||
|
||||
lazy_static! {
|
||||
static ref PASSWORD_REGEX: regex::Regex =
|
||||
@@ -96,14 +97,14 @@ pub struct UsersDetailItemDto {
|
||||
}
|
||||
|
||||
impl UsersDetailItemDto {
|
||||
pub fn from(dto: &UsersDetailQueryDto) -> Self {
|
||||
pub fn from(dto: &UsersDetailQueryDto) -> Self { // Reverted to taking a reference
|
||||
Self {
|
||||
id: dto.id.id.to_raw().clone(),
|
||||
role: RolesDetailItemDto::from(&dto.role),
|
||||
fullname: dto.fullname.clone(),
|
||||
email: dto.email.clone(),
|
||||
avatar: dto.avatar.clone(),
|
||||
phone_number: dto.phone_number.clone(),
|
||||
phone_number: dto.phone_number.clone(), // Corrected from dto.phone.clone()
|
||||
is_active: dto.is_active,
|
||||
gender: dto.gender.clone(),
|
||||
birthdate: dto.birthdate.clone(),
|
||||
@@ -111,6 +112,22 @@ impl UsersDetailItemDto {
|
||||
updated_at: dto.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_schema(schema: &UsersSchema) -> Self {
|
||||
Self {
|
||||
id: schema.id.id.to_raw(),
|
||||
role: RolesDetailItemDto::default(), // Placeholder, role needs to be fetched
|
||||
fullname: schema.fullname.clone(),
|
||||
email: schema.email.clone(),
|
||||
avatar: schema.avatar.clone(),
|
||||
phone_number: schema.phone_number.clone(),
|
||||
is_active: schema.is_active,
|
||||
gender: schema.gender.clone(),
|
||||
birthdate: schema.birthdate.clone(),
|
||||
created_at: schema.created_at.clone(),
|
||||
updated_at: schema.updated_at.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
|
||||
@@ -131,7 +148,7 @@ pub struct UsersListQueryDto {
|
||||
pub id: Thing,
|
||||
pub role: RolesDetailQueryDto,
|
||||
pub fullname: String,
|
||||
pub email: String,
|
||||
pub email: String, // Corrected from pub pub email: String,
|
||||
pub avatar: Option<String>,
|
||||
pub phone_number: String,
|
||||
pub is_active: bool,
|
||||
|
||||
@@ -14,12 +14,33 @@ use axum::{http::StatusCode, response::Response};
|
||||
use imphnen_libs::{ResourceEnum, hash_password, verify_password};
|
||||
use imphnen_utils::make_thing;
|
||||
use uuid::Uuid;
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use crate::v1::users::users_dto::{UsersDetailItemDto as UserDto, UsersCreateRequestDto as CreateUserDto, UsersDetailQueryDto};
|
||||
|
||||
#[async_trait]
|
||||
pub trait UsersServiceTrait: Send + Sync + 'static {
|
||||
async fn get_user_list(state: &AppState, meta: MetaRequestDto) -> Response;
|
||||
async fn get_user_by_id(state: &AppState, id: String) -> Response;
|
||||
async fn get_user_me(headers: HeaderMap, state: &AppState) -> Response;
|
||||
async fn create_user(state: &AppState, new_user: UsersCreateRequestDto) -> Response;
|
||||
async fn update_user(state: &AppState, id: String, user: UsersUpdateRequestDto) -> Response;
|
||||
async fn update_user_me(headers: HeaderMap, state: &AppState, user: UsersUpdateRequestDto) -> Response;
|
||||
async fn set_user_active_status(state: &AppState, id: String, payload: UsersActiveInactiveRequestDto) -> Response;
|
||||
async fn update_user_password(state: &AppState, email: String, payload: UsersSetNewPasswordRequestDto) -> Response;
|
||||
async fn get_user_by_mentor_id(state: &AppState, mentor_id: String) -> Response;
|
||||
async fn delete_user(state: &AppState, id: String) -> Response;
|
||||
|
||||
async fn get_user_by_email(&self, email: &str) -> Result<Option<UserDto>>;
|
||||
async fn create_user_by_dto(&self, new_user: CreateUserDto) -> Result<UserDto>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct UsersService;
|
||||
|
||||
impl UsersService {
|
||||
pub async fn get_user_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
#[async_trait]
|
||||
impl UsersServiceTrait for UsersService {
|
||||
async fn get_user_list(state: &AppState, meta: MetaRequestDto) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
match repo.query_user_list(meta).await {
|
||||
Ok(data) => {
|
||||
@@ -33,7 +54,7 @@ impl UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_user_by_id(state: &AppState, id: String) -> Response {
|
||||
async fn get_user_by_id(state: &AppState, id: String) -> Response {
|
||||
if Uuid::parse_str(&id).is_err() {
|
||||
return common_response(StatusCode::BAD_REQUEST, "Invalid User ID format");
|
||||
}
|
||||
@@ -41,14 +62,14 @@ impl UsersService {
|
||||
let thing_id = make_thing(&ResourceEnum::Users.to_string(), &id);
|
||||
match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: UsersDetailItemDto::from(&user),
|
||||
data: UserDto::from(&user), // Corrected to use UserDto::from by reference
|
||||
}),
|
||||
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_user_me(headers: HeaderMap, state: &AppState) -> Response {
|
||||
async fn get_user_me(headers: HeaderMap, state: &AppState) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
let email = match extract_email(&headers) {
|
||||
Some(email) => email,
|
||||
@@ -56,14 +77,14 @@ impl UsersService {
|
||||
};
|
||||
match repo.query_user_by_email(email).await {
|
||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: UsersDetailItemDto::from(&user),
|
||||
data: UserDto::from(&user), // Corrected to use UserDto::from by reference
|
||||
}),
|
||||
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_user(
|
||||
async fn create_user(
|
||||
state: &AppState,
|
||||
new_user: UsersCreateRequestDto,
|
||||
) -> Response {
|
||||
@@ -86,7 +107,7 @@ impl UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_user(
|
||||
async fn update_user(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
user: UsersUpdateRequestDto,
|
||||
@@ -105,9 +126,9 @@ impl UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_user_me(
|
||||
state: &AppState,
|
||||
async fn update_user_me(
|
||||
headers: HeaderMap,
|
||||
state: &AppState,
|
||||
user: UsersUpdateRequestDto,
|
||||
) -> Response {
|
||||
let repo = UsersRepository::new(state);
|
||||
@@ -129,7 +150,7 @@ impl UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn set_user_active_status(
|
||||
async fn set_user_active_status(
|
||||
state: &AppState,
|
||||
id: String,
|
||||
payload: UsersActiveInactiveRequestDto,
|
||||
@@ -156,7 +177,7 @@ impl UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_user_password(
|
||||
async fn update_user_password(
|
||||
state: &AppState,
|
||||
email: String,
|
||||
payload: UsersSetNewPasswordRequestDto,
|
||||
@@ -199,7 +220,7 @@ impl UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_user_by_mentor_id(
|
||||
async fn get_user_by_mentor_id(
|
||||
state: &AppState,
|
||||
mentor_id: String,
|
||||
) -> Response {
|
||||
@@ -207,14 +228,14 @@ impl UsersService {
|
||||
let thing_id = make_thing(&ResourceEnum::Mentors.to_string(), &mentor_id);
|
||||
match repo.query_user_by_id(&thing_id).await {
|
||||
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
|
||||
data: UsersDetailItemDto::from(&user),
|
||||
data: UserDto::from(&user), // Corrected to use UserDto::from by reference
|
||||
}),
|
||||
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_user(state: &AppState, id: String) -> Response {
|
||||
async fn delete_user(state: &AppState, id: String) -> Response {
|
||||
if Uuid::parse_str(&id).is_err() {
|
||||
return common_response(StatusCode::BAD_REQUEST, "Invalid User ID format");
|
||||
}
|
||||
@@ -228,4 +249,43 @@ impl UsersService {
|
||||
Err(e) => common_response(StatusCode::BAD_REQUEST, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_user_by_email(&self, email: &str) -> Result<Option<UserDto>> {
|
||||
let state = AppState {
|
||||
surrealdb_ws: todo!(),
|
||||
surrealdb_mem: todo!(),
|
||||
};
|
||||
let repo = UsersRepository::new(&state);
|
||||
let user = repo.query_user_by_email(email.to_string()).await;
|
||||
match user {
|
||||
Ok(u) => Ok(Some(UserDto::from(&u))), // Corrected to use UserDto::from by reference
|
||||
Err(e) if e.to_string().contains("User not found") => Ok(None),
|
||||
Err(e) => Err(anyhow::anyhow!(e.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_user_by_dto(&self, new_user: CreateUserDto) -> Result<UserDto> {
|
||||
let state = AppState {
|
||||
surrealdb_ws: todo!(),
|
||||
surrealdb_mem: todo!(),
|
||||
};
|
||||
let repo = UsersRepository::new(&state);
|
||||
let user_schema = UsersSchema {
|
||||
email: new_user.email,
|
||||
password: new_user.password, // No unwrap_or_default needed
|
||||
fullname: new_user.fullname,
|
||||
phone_number: new_user.phone_number, // No unwrap_or_default needed
|
||||
is_active: new_user.is_active, // No unwrap_or needed
|
||||
role: make_thing(&ResourceEnum::Roles.to_string(), &new_user.role_id),
|
||||
..Default::default()
|
||||
};
|
||||
match repo.query_create_user(user_schema).await {
|
||||
Ok(msg) => { // msg is String, not UsersDetailQueryDto
|
||||
// Re-fetch the created user to get the full UsersDetailQueryDto
|
||||
let created_user = repo.query_user_by_email(new_user.email.clone()).await?; // Cloned email
|
||||
Ok(UserDto::from(&created_user)) // Corrected to use UserDto::from by reference
|
||||
},
|
||||
Err(e) => Err(anyhow::anyhow!(e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user