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:
MythEclipse
2025-08-11 22:31:51 +07:00
parent c6a95c1231
commit cda950ed7e
22 changed files with 1144 additions and 104 deletions
@@ -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)
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod google_oauth_controller;
pub mod google_oauth_dto;
pub mod google_oauth_service;