scufflecloud_core/
google_api.rs1use std::sync::Arc;
2
3use base64::Engine;
4
5use crate::CoreConfig;
6
7pub(crate) const ADMIN_DIRECTORY_API_USER_SCOPE: &str = "https://www.googleapis.com/auth/admin.directory.user.readonly";
8const ALL_SCOPES: [&str; 4] = ["openid", "profile", "email", ADMIN_DIRECTORY_API_USER_SCOPE];
9const REQUIRED_SCOPES: [&str; 3] = ["openid", "profile", "email"];
10
11#[derive(serde_derive::Deserialize, Debug)]
12pub(crate) struct GoogleToken {
13 pub access_token: String,
14 pub expires_in: u64,
15 #[serde(deserialize_with = "deserialize_google_id_token")]
16 pub id_token: GoogleIdToken,
17 pub scope: String,
18 pub token_type: String,
19}
20
21#[derive(serde_derive::Deserialize, Debug, Clone)]
22pub(crate) struct GoogleIdToken {
23 pub sub: String,
24 pub email: String,
25 pub email_verified: bool,
26 pub family_name: Option<String>,
27 pub given_name: Option<String>,
28 pub hd: Option<String>,
29 pub name: Option<String>,
30}
31
32fn deserialize_google_id_token<'de, D>(deserialzer: D) -> Result<GoogleIdToken, D::Error>
33where
34 D: serde::Deserializer<'de>,
35{
36 let token: String = serde::Deserialize::deserialize(deserialzer)?;
37 let parts: Vec<&str> = token.split('.').collect();
38 if parts.len() != 3 {
39 return Err(serde::de::Error::custom("Invalid ID token format"));
40 }
41
42 let payload = base64::prelude::BASE64_URL_SAFE_NO_PAD
43 .decode(parts[1])
44 .map_err(serde::de::Error::custom)?;
45
46 serde_json::from_slice(&payload).map_err(serde::de::Error::custom)
47}
48
49#[derive(thiserror::Error, Debug)]
50pub(crate) enum GoogleTokenError {
51 #[error("invalid token type: {0}")]
52 InvalidTokenType(String),
53 #[error("missing scope: {0}")]
54 MissingScope(String),
55 #[error("HTTP request failed: {0}")]
56 RequestFailed(#[from] reqwest::Error),
57}
58
59pub(crate) fn authorization_url<G: CoreConfig>(global: &Arc<G>, state: &str) -> String {
60 format!(
61 "https://accounts.google.com/o/oauth2/v2/auth?client_id={}&redirect_uri={}&response_type=code&scope={}&state={state}",
62 global.google_client_id(),
63 urlencoding::encode(global.dashboard_origin().as_str()),
64 ALL_SCOPES.join("%20"), )
66}
67
68pub(crate) async fn request_tokens<G: CoreConfig>(global: &Arc<G>, code: &str) -> Result<GoogleToken, GoogleTokenError> {
69 let redirect_uri = format!("{}/oauth2-callback/google", global.dashboard_origin());
70
71 let tokens: GoogleToken = global
72 .http_client()
73 .post("https://oauth2.googleapis.com/token")
74 .form(&[
75 ("client_id", global.google_client_id()),
76 ("client_secret", global.google_client_secret()),
77 ("code", code),
78 ("grant_type", "authorization_code"),
79 ("redirect_uri", &redirect_uri),
80 ])
81 .send()
82 .await?
83 .json()
84 .await?;
85
86 if tokens.token_type != "Bearer" {
87 return Err(GoogleTokenError::InvalidTokenType(tokens.token_type));
88 }
89
90 if let Some(missing) = REQUIRED_SCOPES.iter().find(|scope| !tokens.scope.contains(*scope)) {
91 return Err(GoogleTokenError::MissingScope(missing.to_string()));
92 }
93
94 Ok(tokens)
95}
96
97#[derive(serde_derive::Deserialize, Debug)]
98pub(crate) struct GoogleWorkspaceUser {
99 #[serde(rename = "isAdmin")]
100 pub is_admin: bool,
101 #[serde(rename = "customerId")]
102 pub customer_id: String,
103}
104
105#[derive(thiserror::Error, Debug)]
106pub(crate) enum GoogleWorkspaceGetUserError {
107 #[error("HTTP request failed: {0}")]
108 RequestFailed(#[from] reqwest::Error),
109 #[error("invalid status code: {0}")]
110 InvalidStatusCode(reqwest::StatusCode),
111}
112
113pub(crate) async fn request_google_workspace_user<G: CoreConfig>(
114 global: &Arc<G>,
115 access_token: &str,
116 user_id: &str,
117) -> Result<Option<GoogleWorkspaceUser>, GoogleWorkspaceGetUserError> {
118 let response = global
119 .http_client()
120 .get(format!("https://www.googleapis.com/admin/directory/v1/users/{user_id}"))
121 .bearer_auth(access_token)
122 .send()
123 .await?;
124
125 if response.status() == reqwest::StatusCode::FORBIDDEN {
126 return Ok(None);
127 }
128
129 if !response.status().is_success() {
130 return Err(GoogleWorkspaceGetUserError::InvalidStatusCode(response.status()));
131 }
132
133 Ok(Some(response.json().await?))
134}