alibi_api/plugins/oauth/providers/
paybin.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4 OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use base64::Engine;
8use serde_json::Value;
9
10#[derive(Clone)]
13pub struct PaybinOptions {
14 pub client_id: String,
15 pub client_secret: Option<String>,
16 pub client_key: Option<String>,
18 pub scope: Vec<String>,
19 pub disable_default_scope: bool,
20 pub authorization_endpoint: Option<String>,
21 pub redirect_uri: Option<String>,
22 pub issuer: Option<String>,
24 pub prompt: Option<String>,
25 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
27}
28impl PaybinOptions {
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 disable_default_scope: false,
37 authorization_endpoint: None,
38 redirect_uri: None,
39 issuer: None,
40 prompt: None,
41 map_profile_to_user: None,
42 }
43 }
44}
45impl std::fmt::Debug for PaybinOptions {
46 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 formatter
48 .debug_struct("PaybinOptions")
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 paybin(client_id: &str, client_secret: Option<&str>) -> Self {
60 Self::paybin_with_options(PaybinOptions::new(
61 client_id,
62 client_secret.map(str::to_owned),
63 ))
64 }
65 #[must_use]
66 pub fn paybin_with_options(options: PaybinOptions) -> Self {
67 let secret = options.client_secret.unwrap_or_default();
68 let authentication = if secret.is_empty() {
69 OAuthTokenEndpointAuth::None
70 } else {
71 OAuthTokenEndpointAuth::ClientSecretPost
72 };
73 let issuer = options
74 .issuer
75 .filter(|value| !value.is_empty())
76 .unwrap_or_else(|| "https://idp.paybin.io".into());
77 Self {
78 client_id: options.client_id,
79 client_secret: secret,
80 additional_client_ids: Vec::new(),
81 hosted_domain: None,
82 require_email_verification: false,
83 auth_url: options
84 .authorization_endpoint
85 .filter(|value| !value.is_empty())
86 .unwrap_or_else(|| format!("{issuer}/oauth2/authorize")),
87 token_url: format!("{issuer}/oauth2/token"),
88 user_info_url: None,
89 scopes: vec!["openid".into(), "email".into(), "profile".into()],
90 authorization: Some(OAuthAuthorizationPolicy {
91 preserve_raw_profile_scalars: true,
92 source_profile_exceptions: true,
93 allow_missing_access_token: true,
94 configured_scopes: options.scope,
95 disable_default_scopes: options.disable_default_scope,
96 require_client_id: true,
97 require_client_secret: true,
98 default_prompt: options.prompt,
99 token_endpoint_auth: Some(authentication),
100 authorization_code_client_key: options.client_key,
101 redirect_uri: options.redirect_uri,
102 login_hint: true,
103 propagate_grant_profile_errors: true,
104 preserve_raw_email_errors: true,
105 ..OAuthAuthorizationPolicy::default()
106 }),
107 authorization_params: Vec::new(),
108 account_subject: Some(subject),
109 map_user_info: None,
110 get_user_info: Some(std::sync::Arc::new(PaybinUserInfo {
111 application_mapper: None,
112 mapper: options.map_profile_to_user,
113 })),
114 refresh_access_token: None,
115 verify_id_token: None,
116 id_token: None,
117 disable_id_token_sign_in: false,
118 disable_implicit_sign_up: false,
119 disable_sign_up: false,
120 override_user_info_on_sign_in: false,
121 }
122 }
123}
124#[derive(Clone)]
125struct PaybinUserInfo {
126 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
127 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
128}
129#[async_trait]
130impl OAuthUserInfoHandler for PaybinUserInfo {
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 profile = super::remaining_profile::grant_id_token(&request)?
152 .as_deref()
153 .and_then(decode_profile)
154 .ok_or("Missing or invalid Paybin ID token")?;
155 let application_output = if let Some(mapper) = &self.application_mapper {
156 Some(
157 mapper
158 .map_profile(profile.clone())
159 .await
160 .map_err(super::remaining_profile::profile_exception)?,
161 )
162 } else {
163 None
164 };
165 let mapped = self
166 .mapper
167 .map(|mapper| mapper(profile.clone()))
168 .transpose()
169 .map_err(super::remaining_profile::profile_exception)?;
170 let mut output = serde_json::Map::new();
172 for (source, target) in [("email", "email"), ("picture", "image")] {
173 if let Some(value) = profile.get(source) {
174 drop(output.insert(target.into(), value.clone()));
175 }
176 }
177 let name = profile
178 .get("name")
179 .filter(|v| truthy(v))
180 .or_else(|| profile.get("preferred_username").filter(|v| truthy(v)))
181 .cloned()
182 .unwrap_or_else(|| Value::String(String::new()));
183 drop(output.insert("name".into(), name.clone()));
184 drop(
185 output.insert(
186 "emailVerified".into(),
187 profile
188 .get("email_verified")
189 .filter(|v| truthy(v))
190 .cloned()
191 .unwrap_or(Value::Bool(false)),
192 ),
193 );
194 if let Some(user) = &mapped {
195 output.extend(user.public_profile(true));
196 }
197 let user_output = Some(output);
198 let user = match mapped {
199 Some(user) => user,
200 None => OAuthUserInfo {
201 additional_fields: Default::default(),
202 id: profile
203 .get("sub")
204 .map(super::remaining_profile::js_string)
205 .transpose()?
206 .unwrap_or_default(),
207 name: scalar(Some(&name))?,
208 email: profile
209 .get("email")
210 .and_then(Value::as_str)
211 .unwrap_or_default()
212 .into(),
213 image: scalar(profile.get("picture"))?,
214 email_verified: profile.get("email_verified").is_some_and(truthy),
215 },
216 };
217 let mut response = OAuthUserInfoResponse {
218 user_output,
219 user,
220 data: profile,
221 };
222 if let Some(mapped) = application_output {
223 super::apply_application_mapping(&mut response, mapped)?;
224 }
225 Ok(response)
226 }
227}
228fn truthy(value: &Value) -> bool {
229 match value {
230 Value::Null | Value::Bool(false) => false,
231 Value::Number(value) => value.as_f64() != Some(0.0),
232 Value::String(value) => !value.is_empty(),
233 Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
234 }
235}
236fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
237 match value {
238 None | Some(Value::Null) => Ok(None),
239 Some(Value::String(value)) => Ok(Some(value.clone())),
240 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
241 .map(Some)
242 .map_err(|error| error.to_string()),
243 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
244 Some(Value::Array(_) | Value::Object(_)) => Ok(None),
245 }
246}
247fn subject(profile: &Value) -> Result<String, String> {
248 super::remaining_profile::raw_subject(profile.get("sub"))
249}
250
251fn decode_profile(token: &str) -> Option<Value> {
252 let mut parts = token.split('.');
253 let _header = parts.next()?;
254 let payload = parts.next()?;
255 let _signature = parts.next()?;
256 if payload.is_empty() || parts.next().is_some() {
257 return None;
258 }
259 let encoded = payload.replace('-', "+").replace('_', "/");
260 let decoder = base64::engine::GeneralPurpose::new(
261 &base64::alphabet::STANDARD,
262 base64::engine::GeneralPurposeConfig::new()
263 .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
264 );
265 let bytes = decoder.decode(encoded).ok()?;
266 let profile: Value = alibi_core::utils::json::from_slice(&bytes).ok()?;
267 profile.is_object().then_some(profile)
268}