Skip to main content

pakem/core/auth/socialite/
google.rs

1use crate::core::auth::socialite::provider::{SocialProvider, SocialUser};
2use async_trait::async_trait;
3use oauth2::{
4    basic::BasicClient, AuthUrl, AuthorizationCode, ClientId, ClientSecret, RedirectUrl, Scope,
5    TokenResponse, TokenUrl,
6};
7use reqwest::Client;
8use serde::Deserialize;
9
10pub struct GoogleProvider {
11    client: BasicClient,
12    http_client: Client,
13}
14
15impl GoogleProvider {
16    pub fn new(client_id: String, client_secret: String, redirect_url: String) -> Self {
17        let client = BasicClient::new(
18            ClientId::new(client_id),
19            Some(ClientSecret::new(client_secret)),
20            AuthUrl::new("https://accounts.google.com/o/oauth2/v2/auth".to_string()).unwrap(),
21            Some(TokenUrl::new("https://oauth2.googleapis.com/token".to_string()).unwrap()),
22        )
23        .set_redirect_uri(RedirectUrl::new(redirect_url).unwrap());
24
25        Self {
26            client,
27            http_client: Client::new(),
28        }
29    }
30}
31
32#[derive(Debug, Deserialize)]
33struct GoogleUserResponse {
34    id: String,
35    name: String,
36    email: String,
37    picture: Option<String>,
38}
39
40#[async_trait]
41impl SocialProvider for GoogleProvider {
42    fn name(&self) -> &str {
43        "google"
44    }
45
46    fn get_redirect_url(&self) -> String {
47        let (auth_url, _csrf_token) = self
48            .client
49            .authorize_url(oauth2::CsrfToken::new_random)
50            .add_scope(Scope::new(
51                "https://www.googleapis.com/auth/userinfo.email".to_string(),
52            ))
53            .add_scope(Scope::new(
54                "https://www.googleapis.com/auth/userinfo.profile".to_string(),
55            ))
56            .url();
57
58        auth_url.to_string()
59    }
60
61    async fn get_user_by_code(&self, code: String) -> Result<SocialUser, String> {
62        // Exchange code for token
63        let token_result = self
64            .client
65            .exchange_code(AuthorizationCode::new(code))
66            .request_async(oauth2::reqwest::async_http_client)
67            .await
68            .map_err(|e| format!("Gagal exchange token: {}", e))?;
69
70        let access_token = token_result.access_token().secret();
71
72        // Fetch user info from Google API
73        let user_info = self
74            .http_client
75            .get("https://www.googleapis.com/oauth2/v1/userinfo")
76            .bearer_auth(access_token)
77            .send()
78            .await
79            .map_err(|e| format!("Gagal memanggil Google API: {}", e))?
80            .json::<GoogleUserResponse>()
81            .await
82            .map_err(|e| format!("Gagal parse data user Google: {}", e))?;
83
84        Ok(SocialUser {
85            id: user_info.id,
86            name: user_info.name,
87            email: user_info.email,
88            avatar: user_info.picture,
89            provider: "google".to_string(),
90        })
91    }
92}