Skip to main content

auth_framework/profile_utils/
mod.rs

1//! Utilities for token-to-profile conversion and user profile management.
2
3use crate::errors::{AuthError, OAuthProviderError, Result};
4use crate::providers::{OAuthProvider, OAuthTokenResponse, ProviderProfile};
5use crate::tokens::AuthToken;
6use reqwest::Client;
7use serde_json::Value;
8// HashMap is used for token metadata
9
10/// Trait for converting tokens to user profiles
11#[allow(
12    async_fn_in_trait,
13    reason = "the trait does not promise that the returned future is `Send`; changing that is a public API change"
14)]
15pub trait TokenToProfile {
16    /// Convert a token to a user profile
17    async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile>;
18}
19
20/// Trait for automatic extraction of user profiles from responses
21pub trait ExtractProfile {
22    /// Extract a user profile from a JSON response
23    fn extract_profile(
24        &self,
25        provider: &OAuthProvider,
26        json_response: Value,
27    ) -> Result<ProviderProfile>;
28}
29
30impl TokenToProfile for OAuthTokenResponse {
31    async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile> {
32        let config = provider.config();
33        let userinfo_url = config.userinfo_url.clone().ok_or_else(|| {
34            AuthError::OAuthProvider(OAuthProviderError::UnsupportedFeature {
35                provider: format!("{:?}", provider),
36                feature: "userinfo endpoint".to_string(),
37            })
38        })?;
39
40        let client = Client::new();
41        let response = client
42            .get(&userinfo_url)
43            .bearer_auth(&self.access_token)
44            .send()
45            .await
46            .map_err(|e| AuthError::internal(format!("Failed to fetch user profile: {}", e)))?;
47
48        let status = response.status();
49        if !status.is_success() {
50            return Err(AuthError::internal(format!(
51                "Failed to fetch user profile. Status code: {}",
52                status
53            )));
54        }
55
56        let json_response = response.json::<Value>().await.map_err(|e| {
57            AuthError::internal(format!("Failed to parse user profile response: {}", e))
58        })?;
59
60        provider.extract_profile(provider, json_response)
61    }
62}
63
64impl ExtractProfile for OAuthProvider {
65    fn extract_profile(
66        &self,
67        _provider: &OAuthProvider,
68        json_response: Value,
69    ) -> Result<ProviderProfile> {
70        // Default extractor attempts to map standard fields based on provider
71        let mut profile = ProviderProfile::new();
72
73        // Get ID field based on provider
74        match self {
75            OAuthProvider::GitHub => {
76                profile = profile.with_id(extract_string(&json_response, "id")?);
77                profile = profile.with_username(extract_string_optional(&json_response, "login"));
78                profile = profile.with_name(extract_string_optional(&json_response, "name"));
79                profile = profile.with_email(extract_string_optional(&json_response, "email"));
80                profile =
81                    profile.with_picture(extract_string_optional(&json_response, "avatar_url"));
82            }
83            OAuthProvider::Google => {
84                profile = profile.with_id(extract_string(&json_response, "sub")?);
85                profile = profile.with_email(extract_string_optional(&json_response, "email"));
86                profile = profile.with_name(extract_string_optional(&json_response, "name"));
87                profile = profile.with_picture(extract_string_optional(&json_response, "picture"));
88                profile = profile.with_locale(extract_string_optional(&json_response, "locale"));
89
90                if let Some(email_verified) = json_response
91                    .get("email_verified")
92                    .and_then(|v| v.as_bool())
93                {
94                    profile = profile.with_email_verified(email_verified);
95                }
96            }
97            OAuthProvider::Microsoft => {
98                profile = profile.with_id(extract_string(&json_response, "id")?);
99                profile = profile.with_email(
100                    extract_string_optional(&json_response, "userPrincipalName")
101                        .or_else(|| extract_string_optional(&json_response, "mail")),
102                );
103                profile = profile.with_name(extract_string_optional(&json_response, "displayName"));
104
105                // Microsoft Graph API might have these in different formats
106                if let Some(photo) = json_response.get("photo") {
107                    profile = profile.with_picture(photo.as_str().map(String::from));
108                }
109            }
110            OAuthProvider::Discord => {
111                profile = profile.with_id(extract_string(&json_response, "id")?);
112                profile =
113                    profile.with_username(extract_string_optional(&json_response, "username"));
114                profile = profile.with_email(extract_string_optional(&json_response, "email"));
115
116                if let Some(avatar) = extract_string_optional(&json_response, "avatar") {
117                    let id = extract_string_optional(&json_response, "id").unwrap_or_default();
118                    let avatar_url =
119                        format!("https://cdn.discordapp.com/avatars/{}/{}.png", id, avatar);
120                    profile = profile.with_picture(Some(avatar_url));
121                }
122            }
123            OAuthProvider::GitLab => {
124                profile = profile.with_id(extract_string(&json_response, "id")?);
125                profile =
126                    profile.with_username(extract_string_optional(&json_response, "username"));
127                profile = profile.with_name(extract_string_optional(&json_response, "name"));
128                profile = profile.with_email(extract_string_optional(&json_response, "email"));
129                profile =
130                    profile.with_picture(extract_string_optional(&json_response, "avatar_url"));
131            }
132            OAuthProvider::Twitter => {
133                // Twitter API v2 has a different structure
134                if let Some(data) = json_response.get("data") {
135                    profile = profile.with_id(extract_string_from_value(data, "id")?);
136                    profile =
137                        profile.with_username(extract_string_optional_from_value(data, "username"));
138                    profile = profile.with_name(extract_string_optional_from_value(data, "name"));
139                } else {
140                    profile = profile.with_id(extract_string(&json_response, "id")?);
141                    profile = profile
142                        .with_username(extract_string_optional(&json_response, "screen_name"));
143                    profile = profile.with_name(extract_string_optional(&json_response, "name"));
144                    profile = profile.with_picture(extract_string_optional(
145                        &json_response,
146                        "profile_image_url_https",
147                    ));
148                }
149            }
150            OAuthProvider::Facebook => {
151                profile = profile.with_id(extract_string(&json_response, "id")?);
152                profile = profile.with_name(extract_string_optional(&json_response, "name"));
153                profile = profile.with_email(extract_string_optional(&json_response, "email"));
154                // Facebook requires requesting the picture separately or with fields parameter
155                if let Some(id) = extract_string_optional(&json_response, "id") {
156                    let picture_url =
157                        format!("https://graph.facebook.com/{}/picture?type=large", id);
158                    profile = profile.with_picture(Some(picture_url));
159                }
160            }
161            OAuthProvider::LinkedIn => {
162                profile = profile.with_id(extract_string(&json_response, "id")?);
163                // LinkedIn API structure is complex, try to navigate it
164                if let Some(name) = json_response
165                    .get("localizedFirstName")
166                    .and_then(|f| f.as_str())
167                    .zip(
168                        json_response
169                            .get("localizedLastName")
170                            .and_then(|l| l.as_str()),
171                    )
172                {
173                    profile = profile.with_name(Some(format!("{} {}", name.0, name.1)));
174                }
175                // For LinkedIn, email requires a separate API call with r_emailaddress permission
176            }
177            OAuthProvider::Custom { name, .. } => {
178                // For custom providers, try some common ID field names
179                let id = extract_string_optional(&json_response, "id")
180                    .or_else(|| extract_string_optional(&json_response, "sub"))
181                    .or_else(|| extract_string_optional(&json_response, "user_id"));
182
183                if let Some(id) = id {
184                    profile = profile.with_id(id);
185                } else {
186                    return Err(AuthError::validation(format!(
187                        "Could not find ID field in response from custom provider {}",
188                        name
189                    )));
190                }
191
192                // Try common fields
193                profile = profile.with_email(extract_string_optional(&json_response, "email"));
194                profile = profile.with_name(
195                    extract_string_optional(&json_response, "name")
196                        .or_else(|| extract_string_optional(&json_response, "display_name")),
197                );
198                profile = profile.with_username(
199                    extract_string_optional(&json_response, "username")
200                        .or_else(|| extract_string_optional(&json_response, "login")),
201                );
202                profile = profile.with_picture(
203                    extract_string_optional(&json_response, "picture")
204                        .or_else(|| extract_string_optional(&json_response, "avatar"))
205                        .or_else(|| extract_string_optional(&json_response, "avatar_url")),
206                );
207            }
208        }
209
210        // Store the full response in additional_data for access to all fields
211        profile = profile.with_additional_data("raw_profile", json_response);
212        Ok(profile)
213    }
214}
215
216impl TokenToProfile for AuthToken {
217    async fn to_profile(&self, _provider: &OAuthProvider) -> Result<ProviderProfile> {
218        // Create a basic profile from the token data
219        let mut profile = ProviderProfile::new();
220
221        // Use the user ID as the profile ID
222        profile = profile.with_id(self.user_id.clone());
223
224        // Use the auth method as the provider if available
225        profile = profile.with_provider(self.auth_method.clone());
226
227        // Add custom metadata if available
228        if let Some(name) = self.metadata.custom.get("name").and_then(|v| v.as_str()) {
229            profile = profile.with_name(Some(name.to_string()));
230        }
231
232        if let Some(email) = self.metadata.custom.get("email").and_then(|v| v.as_str()) {
233            profile = profile.with_email(Some(email.to_string()));
234        }
235
236        // We can add more information later if needed
237
238        Ok(profile)
239    }
240}
241
242/// Helper function to extract a required string from a JSON response
243fn extract_string(json: &Value, field: &str) -> Result<String> {
244    json.get(field)
245        .and_then(|v| v.as_str())
246        .map(String::from)
247        .ok_or_else(|| {
248            AuthError::validation(format!("Field '{}' not found or not a string", field))
249        })
250}
251
252/// Helper function to extract an optional string from a JSON response
253fn extract_string_optional(json: &Value, field: &str) -> Option<String> {
254    json.get(field).and_then(|v| v.as_str()).map(String::from)
255}
256
257/// Helper function to extract a required string from a JSON value
258fn extract_string_from_value(json: &Value, field: &str) -> Result<String> {
259    json.get(field)
260        .and_then(|v| v.as_str())
261        .map(String::from)
262        .ok_or_else(|| {
263            AuthError::validation(format!("Field '{}' not found or not a string", field))
264        })
265}
266
267/// Helper function to extract an optional string from a JSON value
268fn extract_string_optional_from_value(json: &Value, field: &str) -> Option<String> {
269    json.get(field).and_then(|v| v.as_str()).map(String::from)
270}