alibi_plugins/oauth/providers/
polar.rs1use 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#[derive(Clone)]
13pub struct PolarOptions {
14 pub client_id: String,
15 pub client_secret: Option<String>,
16 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 pub user_info_endpoint: Option<String>,
25 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 allowed_request_params: Vec::new(),
105 authorization_params: Vec::new(),
106 account_subject: Some(subject),
107 map_user_info: None,
108 get_user_info: Some(std::sync::Arc::new(PolarUserInfo {
109 application_mapper: None,
110 endpoint,
111 mapper: options.map_profile_to_user,
112 })),
113 refresh_access_token: None,
114 verify_id_token: None,
115 id_token: None,
116 disable_id_token_sign_in: false,
117 disable_implicit_sign_up: false,
118 disable_sign_up: false,
119 allow_idp_initiated: false,
120 override_user_info_on_sign_in: false,
121 }
122 }
123}
124#[derive(Clone)]
125struct PolarUserInfo {
126 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
127 endpoint: String,
128 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
129}
130#[async_trait]
131impl OAuthUserInfoHandler for PolarUserInfo {
132 fn errors_are_exceptions(&self) -> bool {
133 false
134 }
135
136 fn mapped_handler(
137 &self,
138 mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
139 ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
140 let mut handler = self.clone();
141 handler.mapper = None;
142 handler.application_mapper = Some(mapper);
143 Some(std::sync::Arc::new(handler))
144 }
145
146 async fn get_user_info(
147 &self,
148 request: OAuthUserInfoRequest,
149 ) -> Result<OAuthUserInfoResponse, String> {
150 let access_token = super::remaining_profile::bearer_access_token(&request)?;
151 let profile: Value = reqwest::Client::new()
152 .get(&self.endpoint)
153 .bearer_auth(access_token)
154 .send()
155 .await
156 .map_err(|error| error.to_string())?
157 .error_for_status()
158 .map_err(|error| error.to_string())?
159 .json()
160 .await
161 .map_err(|error| error.to_string())?;
162 let application_output = if let Some(mapper) = &self.application_mapper {
163 Some(
164 mapper
165 .map_profile(profile.clone())
166 .await
167 .map_err(super::remaining_profile::profile_exception)?,
168 )
169 } else {
170 None
171 };
172 let mapped = self
173 .mapper
174 .map(|mapper| mapper(profile.clone()))
175 .transpose()
176 .map_err(super::remaining_profile::profile_exception)?;
177 if profile.is_null() {
178 return Err(super::remaining_profile::profile_exception(
179 "Null Polar profile",
180 ));
181 }
182 let mut output = serde_json::Map::new();
184 _ = output.insert(
185 "name".into(),
186 profile
187 .get("public_name")
188 .filter(|v| truthy(v))
189 .or_else(|| profile.get("username").filter(|v| truthy(v)))
190 .cloned()
191 .unwrap_or_else(|| Value::String(String::new())),
192 );
193 let email = profile.get("email");
194 if let Some(email) = email {
195 _ = output.insert("email".into(), email.clone());
196 }
197 if let Some(image) = profile.get("avatar_url") {
198 _ = output.insert("image".into(), image.clone());
199 }
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 if let Some(user) = &mapped {
209 output.extend(user.public_profile(true));
210 }
211 let user_output = Some(output);
212 let user = match mapped {
213 Some(user) => user,
214 None => OAuthUserInfo {
215 additional_fields: Map::default(),
216 id: profile
217 .get("id")
218 .map(super::remaining_profile::js_string)
219 .transpose()?
220 .unwrap_or_default(),
221 name: scalar(
222 profile
223 .get("public_name")
224 .filter(|v| truthy(v))
225 .or_else(|| profile.get("username").filter(|v| truthy(v))),
226 )?
227 .or_else(|| Some(String::new())),
228 email: email.and_then(Value::as_str).unwrap_or_default().into(),
229 image: scalar(profile.get("avatar_url"))?,
230 email_verified: profile.get("email_verified").is_some_and(truthy),
231 },
232 };
233 let mut response = OAuthUserInfoResponse {
234 user_output,
235 user,
236 data: profile,
237 };
238 if let Some(mapped) = application_output {
239 super::apply_application_mapping(&mut response, mapped)?;
240 }
241 Ok(response)
242 }
243}
244fn truthy(value: &Value) -> bool {
245 match value {
246 Value::Null | Value::Bool(false) => false,
247 Value::Number(value) => value.as_f64() != Some(0.0),
248 Value::String(value) => !value.is_empty(),
249 Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
250 }
251}
252fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
253 match value {
254 Some(Value::String(value)) => Ok(Some(value.clone())),
255 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
256 .map(Some)
257 .map_err(|error| error.to_string()),
258 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
259 None | Some(Value::Null | Value::Array(_) | Value::Object(_)) => Ok(None),
260 }
261}
262fn subject(profile: &Value) -> Result<String, String> {
263 super::remaining_profile::raw_subject(profile.get("id"))
264}