Skip to main content

alibi_plugins/oauth/providers/
polar.rs

1//! Polar's PKCE grants, ordered scopes and original user-info account identity.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Map;
8use serde_json::Value;
9
10/// Application-owned Polar configuration. Generic signup and asynchronous
11/// user-info/refresh callbacks remain configurable on the returned provider.
12#[derive(Clone)]
13pub struct PolarOptions {
14    pub client_id: String,
15    pub client_secret: Option<String>,
16    /// Sent only during authorization-code exchange.
17    pub client_key: Option<String>,
18    pub scope: Vec<String>,
19    pub prompt: Option<String>,
20    pub disable_default_scope: bool,
21    pub authorization_endpoint: Option<String>,
22    pub redirect_uri: Option<String>,
23    /// Trusted transport override retaining Polar's bearer GET and mapping.
24    pub user_info_endpoint: Option<String>,
25    /// Receives the original profile before its raw account identity is resolved.
26    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
27}
28impl PolarOptions {
29    #[must_use]
30    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
31        Self {
32            client_id: client_id.into(),
33            client_secret,
34            client_key: None,
35            scope: Vec::new(),
36            prompt: None,
37            disable_default_scope: false,
38            authorization_endpoint: None,
39            redirect_uri: None,
40            user_info_endpoint: None,
41            map_profile_to_user: None,
42        }
43    }
44}
45impl std::fmt::Debug for PolarOptions {
46    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        formatter
48            .debug_struct("PolarOptions")
49            .field("client_id", &self.client_id)
50            .field("scope", &self.scope)
51            .field("disable_default_scope", &self.disable_default_scope)
52            .field("authorization_endpoint", &self.authorization_endpoint)
53            .field("redirect_uri", &self.redirect_uri)
54            .finish_non_exhaustive()
55    }
56}
57impl OAuthProvider {
58    #[must_use]
59    pub fn polar(client_id: &str, client_secret: Option<&str>) -> Self {
60        Self::polar_with_options(PolarOptions::new(
61            client_id,
62            client_secret.map(str::to_owned),
63        ))
64    }
65    #[must_use]
66    pub fn polar_with_options(options: PolarOptions) -> Self {
67        let secret = options.client_secret.unwrap_or_default();
68        let refresh_authentication = if secret.is_empty() {
69            OAuthTokenEndpointAuth::None
70        } else {
71            OAuthTokenEndpointAuth::ClientSecretPost
72        };
73        let endpoint = options
74            .user_info_endpoint
75            .unwrap_or_else(|| "https://api.polar.sh/v1/oauth2/userinfo".into());
76        Self {
77            client_id: options.client_id,
78            client_secret: secret,
79            additional_client_ids: Vec::new(),
80            hosted_domain: None,
81            require_email_verification: false,
82            auth_url: options
83                .authorization_endpoint
84                .filter(|value| !value.is_empty())
85                .unwrap_or_else(|| "https://polar.sh/oauth2/authorize".into()),
86            token_url: "https://api.polar.sh/v1/oauth2/token".into(),
87            user_info_url: Some(endpoint.clone()),
88            scopes: vec!["openid".into(), "profile".into(), "email".into()],
89            authorization: Some(OAuthAuthorizationPolicy {
90                preserve_raw_profile_scalars: true,
91                source_profile_exceptions: true,
92                allow_missing_access_token: true,
93                preserve_raw_email_errors: true,
94                configured_scopes: options.scope,
95                disable_default_scopes: options.disable_default_scope,
96                require_client_id: true,
97                token_endpoint_auth: Some(refresh_authentication),
98                authorization_code_client_key: options.client_key,
99                redirect_uri: options.redirect_uri,
100                login_hint: false,
101                prompt: options.prompt,
102                ..OAuthAuthorizationPolicy::default()
103            }),
104            authorization_params: Vec::new(),
105            account_subject: Some(subject),
106            map_user_info: None,
107            get_user_info: Some(std::sync::Arc::new(PolarUserInfo {
108                application_mapper: None,
109                endpoint,
110                mapper: options.map_profile_to_user,
111            })),
112            refresh_access_token: None,
113            verify_id_token: None,
114            id_token: None,
115            disable_id_token_sign_in: false,
116            disable_implicit_sign_up: false,
117            disable_sign_up: false,
118            allow_idp_initiated: false,
119            override_user_info_on_sign_in: false,
120        }
121    }
122}
123#[derive(Clone)]
124struct PolarUserInfo {
125    application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
126    endpoint: String,
127    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
128}
129#[async_trait]
130impl OAuthUserInfoHandler for PolarUserInfo {
131    fn errors_are_exceptions(&self) -> bool {
132        false
133    }
134
135    fn mapped_handler(
136        &self,
137        mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
138    ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
139        let mut handler = self.clone();
140        handler.mapper = None;
141        handler.application_mapper = Some(mapper);
142        Some(std::sync::Arc::new(handler))
143    }
144
145    async fn get_user_info(
146        &self,
147        request: OAuthUserInfoRequest,
148    ) -> Result<OAuthUserInfoResponse, String> {
149        let access_token = super::remaining_profile::bearer_access_token(&request)?;
150        let profile: Value = reqwest::Client::new()
151            .get(&self.endpoint)
152            .bearer_auth(access_token)
153            .send()
154            .await
155            .map_err(|error| error.to_string())?
156            .error_for_status()
157            .map_err(|error| error.to_string())?
158            .json()
159            .await
160            .map_err(|error| error.to_string())?;
161        let application_output = if let Some(mapper) = &self.application_mapper {
162            Some(
163                mapper
164                    .map_profile(profile.clone())
165                    .await
166                    .map_err(super::remaining_profile::profile_exception)?,
167            )
168        } else {
169            None
170        };
171        let mapped = self
172            .mapper
173            .map(|mapper| mapper(profile.clone()))
174            .transpose()
175            .map_err(super::remaining_profile::profile_exception)?;
176        if profile.is_null() {
177            return Err(super::remaining_profile::profile_exception(
178                "Null Polar profile",
179            ));
180        }
181        // Keep the published raw JSON independently from typed persistence.
182        let mut output = serde_json::Map::new();
183        _ = output.insert(
184            "name".into(),
185            profile
186                .get("public_name")
187                .filter(|v| truthy(v))
188                .or_else(|| profile.get("username").filter(|v| truthy(v)))
189                .cloned()
190                .unwrap_or_else(|| Value::String(String::new())),
191        );
192        let email = profile.get("email");
193        if let Some(email) = email {
194            _ = output.insert("email".into(), email.clone());
195        }
196        if let Some(image) = profile.get("avatar_url") {
197            _ = output.insert("image".into(), image.clone());
198        }
199        _ = output.insert(
200            "emailVerified".into(),
201            profile
202                .get("email_verified")
203                .filter(|value| !value.is_null())
204                .cloned()
205                .unwrap_or(Value::Bool(false)),
206        );
207        if let Some(user) = &mapped {
208            output.extend(user.public_profile(true));
209        }
210        let user_output = Some(output);
211        let user = match mapped {
212            Some(user) => user,
213            None => OAuthUserInfo {
214                additional_fields: Map::default(),
215                id: profile
216                    .get("id")
217                    .map(super::remaining_profile::js_string)
218                    .transpose()?
219                    .unwrap_or_default(),
220                name: scalar(
221                    profile
222                        .get("public_name")
223                        .filter(|v| truthy(v))
224                        .or_else(|| profile.get("username").filter(|v| truthy(v))),
225                )?
226                .or_else(|| Some(String::new())),
227                email: email.and_then(Value::as_str).unwrap_or_default().into(),
228                image: scalar(profile.get("avatar_url"))?,
229                email_verified: profile.get("email_verified").is_some_and(truthy),
230            },
231        };
232        let mut response = OAuthUserInfoResponse {
233            user_output,
234            user,
235            data: profile,
236        };
237        if let Some(mapped) = application_output {
238            super::apply_application_mapping(&mut response, mapped)?;
239        }
240        Ok(response)
241    }
242}
243fn truthy(value: &Value) -> bool {
244    match value {
245        Value::Null | Value::Bool(false) => false,
246        Value::Number(value) => value.as_f64() != Some(0.0),
247        Value::String(value) => !value.is_empty(),
248        Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
249    }
250}
251fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
252    match value {
253        Some(Value::String(value)) => Ok(Some(value.clone())),
254        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
255            .map(Some)
256            .map_err(|error| error.to_string()),
257        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
258        None | Some(Value::Null | Value::Array(_) | Value::Object(_)) => Ok(None),
259    }
260}
261fn subject(profile: &Value) -> Result<String, String> {
262    super::remaining_profile::raw_subject(profile.get("id"))
263}