Skip to main content

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