Skip to main content

alibi_api/plugins/oauth/providers/
figma.rs

1//! Figma's ordered scopes, Basic token exchanges and stable raw profile identity.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Value;
8
9/// Application-owned Figma configuration. Generic signup and asynchronous
10/// user-info/refresh callbacks remain configurable on the returned provider.
11#[derive(Clone)]
12pub struct FigmaOptions {
13    pub client_id: String,
14    pub client_secret: Option<String>,
15    /// Sent only during authorization-code exchange.
16    pub client_key: Option<String>,
17    pub scope: Vec<String>,
18    pub disable_default_scope: bool,
19    pub authorization_endpoint: Option<String>,
20    pub redirect_uri: Option<String>,
21    /// Trusted transport override retaining Figma's actual GET and mapping.
22    pub user_info_endpoint: Option<String>,
23    /// Receives the original profile before its raw account identity is resolved.
24    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
25}
26impl FigmaOptions {
27    #[must_use]
28    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
29        Self {
30            client_id: client_id.into(),
31            client_secret,
32            client_key: None,
33            scope: Vec::new(),
34            disable_default_scope: false,
35            authorization_endpoint: None,
36            redirect_uri: None,
37            user_info_endpoint: None,
38            map_profile_to_user: None,
39        }
40    }
41}
42impl std::fmt::Debug for FigmaOptions {
43    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        formatter
45            .debug_struct("FigmaOptions")
46            .field("client_id", &self.client_id)
47            .field("scope", &self.scope)
48            .field("disable_default_scope", &self.disable_default_scope)
49            .field("authorization_endpoint", &self.authorization_endpoint)
50            .field("redirect_uri", &self.redirect_uri)
51            .finish_non_exhaustive()
52    }
53}
54impl OAuthProvider {
55    #[must_use]
56    pub fn figma(client_id: &str, client_secret: Option<&str>) -> Self {
57        Self::figma_with_options(FigmaOptions::new(
58            client_id,
59            client_secret.map(str::to_owned),
60        ))
61    }
62    #[must_use]
63    pub fn figma_with_options(options: FigmaOptions) -> Self {
64        let secret = options.client_secret.unwrap_or_default();
65        let endpoint = options
66            .user_info_endpoint
67            .unwrap_or_else(|| "https://api.figma.com/v1/me".into());
68        Self {
69            client_id: options.client_id,
70            client_secret: secret,
71            additional_client_ids: Vec::new(),
72            hosted_domain: None,
73            require_email_verification: false,
74            auth_url: options
75                .authorization_endpoint
76                .filter(|value| !value.is_empty())
77                .unwrap_or_else(|| "https://www.figma.com/oauth".into()),
78            token_url: "https://api.figma.com/v1/oauth/token".into(),
79            user_info_url: Some(endpoint.clone()),
80            scopes: vec!["current_user:read".into()],
81            authorization: Some(OAuthAuthorizationPolicy {
82                configured_scopes: options.scope,
83                disable_default_scopes: options.disable_default_scope,
84                require_client_id: true,
85                require_client_secret: true,
86                token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
87                authorization_code_client_key: options.client_key,
88                redirect_uri: options.redirect_uri,
89                login_hint: false,
90                ..OAuthAuthorizationPolicy::default()
91            }),
92            authorization_params: Vec::new(),
93            account_subject: Some(subject),
94            map_user_info: None,
95            get_user_info: Some(std::sync::Arc::new(FigmaUserInfo {
96                endpoint,
97                mapper: options.map_profile_to_user,
98            })),
99            refresh_access_token: None,
100            verify_id_token: None,
101            id_token: None,
102            disable_id_token_sign_in: false,
103            disable_implicit_sign_up: false,
104            disable_sign_up: false,
105            override_user_info_on_sign_in: false,
106        }
107    }
108}
109struct FigmaUserInfo {
110    endpoint: String,
111    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
112}
113#[async_trait]
114impl OAuthUserInfoHandler for FigmaUserInfo {
115    async fn get_user_info(
116        &self,
117        request: OAuthUserInfoRequest,
118    ) -> Result<OAuthUserInfoResponse, String> {
119        let access_token = request.access_token.ok_or("Missing Figma access token")?;
120        let profile: Value = reqwest::Client::new()
121            .get(&self.endpoint)
122            .bearer_auth(access_token)
123            .send()
124            .await
125            .map_err(|error| error.to_string())?
126            .error_for_status()
127            .map_err(|error| error.to_string())?
128            .json()
129            .await
130            .map_err(|error| error.to_string())?;
131        let mapped = self
132            .mapper
133            .map(|mapper| mapper(profile.clone()))
134            .transpose()?;
135        let user_output = mapped.as_ref().map(|user| user.public_profile(true));
136        let user = match mapped {
137            Some(user) => user,
138            None => OAuthUserInfo {
139                additional_fields: Default::default(),
140                id: scalar(profile.get("id"))?.unwrap_or_default(),
141                name: scalar(profile.get("handle"))?,
142                email: profile
143                    .get("email")
144                    .and_then(Value::as_str)
145                    .unwrap_or_default()
146                    .into(),
147                image: scalar(profile.get("img_url"))?,
148                email_verified: false,
149            },
150        };
151        Ok(OAuthUserInfoResponse {
152            user_output,
153            user,
154            data: profile,
155        })
156    }
157}
158fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
159    match value {
160        None | Some(Value::Null) => Ok(None),
161        Some(Value::String(value)) => Ok(Some(value.clone())),
162        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
163            .map(Some)
164            .map_err(|error| error.to_string()),
165        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
166        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Figma profile field".into()),
167    }
168}
169fn subject(profile: &Value) -> Result<String, String> {
170    let id = scalar(profile.get("id"))?.ok_or("Missing Figma id")?;
171    if id
172        .trim_matches(|character: char| {
173            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
174        })
175        .is_empty()
176        || id == "null"
177        || id == "undefined"
178    {
179        return Err("Invalid Figma id".into());
180    }
181    Ok(id)
182}