alibi_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::Map;
9use serde_json::Value;
10
11#[derive(Clone)]
14pub struct PaybinOptions {
15 pub client_id: String,
16 pub client_secret: Option<String>,
17 pub client_key: Option<String>,
19 pub scope: Vec<String>,
20 pub disable_default_scope: bool,
21 pub authorization_endpoint: Option<String>,
22 pub redirect_uri: Option<String>,
23 pub issuer: Option<String>,
25 pub prompt: Option<String>,
26 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
28}
29impl PaybinOptions {
30 #[must_use]
31 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
32 Self {
33 client_id: client_id.into(),
34 client_secret,
35 client_key: None,
36 scope: Vec::new(),
37 disable_default_scope: false,
38 authorization_endpoint: None,
39 redirect_uri: None,
40 issuer: None,
41 prompt: None,
42 map_profile_to_user: None,
43 }
44 }
45}
46impl std::fmt::Debug for PaybinOptions {
47 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 formatter
49 .debug_struct("PaybinOptions")
50 .field("client_id", &self.client_id)
51 .field("scope", &self.scope)
52 .field("disable_default_scope", &self.disable_default_scope)
53 .field("authorization_endpoint", &self.authorization_endpoint)
54 .field("redirect_uri", &self.redirect_uri)
55 .finish_non_exhaustive()
56 }
57}
58impl OAuthProvider {
59 #[must_use]
60 pub fn paybin(client_id: &str, client_secret: Option<&str>) -> Self {
61 Self::paybin_with_options(PaybinOptions::new(
62 client_id,
63 client_secret.map(str::to_owned),
64 ))
65 }
66 #[must_use]
67 pub fn paybin_with_options(options: PaybinOptions) -> Self {
68 let secret = options.client_secret.unwrap_or_default();
69 let authentication = if secret.is_empty() {
70 OAuthTokenEndpointAuth::None
71 } else {
72 OAuthTokenEndpointAuth::ClientSecretPost
73 };
74 let issuer = options
75 .issuer
76 .filter(|value| !value.is_empty())
77 .unwrap_or_else(|| "https://idp.paybin.io".into());
78 Self {
79 client_id: options.client_id,
80 client_secret: secret,
81 additional_client_ids: Vec::new(),
82 hosted_domain: None,
83 require_email_verification: false,
84 auth_url: options
85 .authorization_endpoint
86 .filter(|value| !value.is_empty())
87 .unwrap_or_else(|| format!("{issuer}/oauth2/authorize")),
88 token_url: format!("{issuer}/oauth2/token"),
89 user_info_url: None,
90 scopes: vec!["openid".into(), "email".into(), "profile".into()],
91 authorization: Some(OAuthAuthorizationPolicy {
92 preserve_raw_profile_scalars: true,
93 source_profile_exceptions: true,
94 allow_missing_access_token: true,
95 configured_scopes: options.scope,
96 disable_default_scopes: options.disable_default_scope,
97 require_client_id: true,
98 require_client_secret: true,
99 default_prompt: options.prompt,
100 token_endpoint_auth: Some(authentication),
101 authorization_code_client_key: options.client_key,
102 redirect_uri: options.redirect_uri,
103 login_hint: true,
104 propagate_grant_profile_errors: true,
105 preserve_raw_email_errors: true,
106 ..OAuthAuthorizationPolicy::default()
107 }),
108 allowed_request_params: Vec::new(),
109 authorization_params: Vec::new(),
110 account_subject: Some(subject),
111 map_user_info: None,
112 get_user_info: Some(std::sync::Arc::new(PaybinUserInfo {
113 application_mapper: None,
114 mapper: options.map_profile_to_user,
115 })),
116 refresh_access_token: None,
117 verify_id_token: None,
118 id_token: None,
119 disable_id_token_sign_in: false,
120 disable_implicit_sign_up: false,
121 disable_sign_up: false,
122 allow_idp_initiated: false,
123 override_user_info_on_sign_in: false,
124 }
125 }
126}
127#[derive(Clone)]
128struct PaybinUserInfo {
129 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
130 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
131}
132#[async_trait]
133impl OAuthUserInfoHandler for PaybinUserInfo {
134 fn errors_are_exceptions(&self) -> bool {
135 false
136 }
137
138 fn mapped_handler(
139 &self,
140 mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
141 ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
142 let mut handler = self.clone();
143 handler.mapper = None;
144 handler.application_mapper = Some(mapper);
145 Some(std::sync::Arc::new(handler))
146 }
147
148 async fn get_user_info(
149 &self,
150 request: OAuthUserInfoRequest,
151 ) -> Result<OAuthUserInfoResponse, String> {
152 let profile = super::remaining_profile::grant_id_token(&request)?
155 .as_deref()
156 .and_then(decode_profile)
157 .ok_or("Missing or invalid Paybin ID token")?;
158 let application_output = if let Some(mapper) = &self.application_mapper {
159 Some(
160 mapper
161 .map_profile(profile.clone())
162 .await
163 .map_err(super::remaining_profile::profile_exception)?,
164 )
165 } else {
166 None
167 };
168 let mapped = self
169 .mapper
170 .map(|mapper| mapper(profile.clone()))
171 .transpose()
172 .map_err(super::remaining_profile::profile_exception)?;
173 let mut output = serde_json::Map::new();
175 for (source, target) in [("email", "email"), ("picture", "image")] {
176 if let Some(value) = profile.get(source) {
177 _ = output.insert(target.into(), value.clone());
178 }
179 }
180 let name = profile
181 .get("name")
182 .filter(|v| truthy(v))
183 .or_else(|| profile.get("preferred_username").filter(|v| truthy(v)))
184 .cloned()
185 .unwrap_or_else(|| Value::String(String::new()));
186 _ = output.insert("name".into(), name.clone());
187 _ = output.insert(
188 "emailVerified".into(),
189 profile
190 .get("email_verified")
191 .filter(|v| truthy(v))
192 .cloned()
193 .unwrap_or(Value::Bool(false)),
194 );
195 if let Some(user) = &mapped {
196 output.extend(user.public_profile(true));
197 }
198 let user_output = Some(output);
199 let user = match mapped {
200 Some(user) => user,
201 None => OAuthUserInfo {
202 additional_fields: Map::default(),
203 id: profile
204 .get("sub")
205 .map(super::remaining_profile::js_string)
206 .transpose()?
207 .unwrap_or_default(),
208 name: scalar(Some(&name))?,
209 email: profile
210 .get("email")
211 .and_then(Value::as_str)
212 .unwrap_or_default()
213 .into(),
214 image: scalar(profile.get("picture"))?,
215 email_verified: profile.get("email_verified").is_some_and(truthy),
216 },
217 };
218 let mut response = OAuthUserInfoResponse {
219 user_output,
220 user,
221 data: profile,
222 };
223 if let Some(mapped) = application_output {
224 super::apply_application_mapping(&mut response, mapped)?;
225 }
226 Ok(response)
227 }
228}
229fn truthy(value: &Value) -> bool {
230 match value {
231 Value::Null | Value::Bool(false) => false,
232 Value::Number(value) => value.as_f64() != Some(0.0),
233 Value::String(value) => !value.is_empty(),
234 Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
235 }
236}
237fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
238 match value {
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 None | Some(Value::Null | 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 _ = parts.next()?;
254 let payload = parts.next()?;
255 _ = 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}