alibi_plugins/oauth/providers/
paypal.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4 OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use serde_json::Map;
7use serde_json::Value;
8
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10pub enum PayPalEnvironment {
11 #[default]
12 Sandbox,
13 Live,
14}
15
16#[derive(Clone)]
20pub struct PayPalOptions {
21 pub client_id: String,
22 pub client_secret: String,
23 pub environment: PayPalEnvironment,
24 pub prompt: Option<String>,
25 pub authorization_endpoint: Option<String>,
26 pub redirect_uri: Option<String>,
27 pub user_info_endpoint: Option<String>,
29 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
31}
32impl PayPalOptions {
33 #[must_use]
34 pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
35 Self {
36 client_id: client_id.into(),
37 client_secret: client_secret.into(),
38 environment: PayPalEnvironment::Sandbox,
39 prompt: None,
40 authorization_endpoint: None,
41 redirect_uri: None,
42 user_info_endpoint: None,
43 map_profile_to_user: None,
44 }
45 }
46}
47impl std::fmt::Debug for PayPalOptions {
48 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 formatter
50 .debug_struct("PayPalOptions")
51 .field("client_id", &self.client_id)
52 .field("environment", &self.environment)
53 .field("prompt", &self.prompt)
54 .field("authorization_endpoint", &self.authorization_endpoint)
55 .field("redirect_uri", &self.redirect_uri)
56 .finish_non_exhaustive()
57 }
58}
59impl OAuthProvider {
60 #[must_use]
61 pub fn paypal(client_id: &str, client_secret: &str) -> Self {
62 Self::paypal_with_options(PayPalOptions::new(client_id, client_secret))
63 }
64 #[must_use]
65 pub fn paypal_with_options(options: PayPalOptions) -> Self {
66 let sandbox = options.environment == PayPalEnvironment::Sandbox;
67 let web = if sandbox {
68 "www.sandbox.paypal.com"
69 } else {
70 "www.paypal.com"
71 };
72 let api = if sandbox {
73 "api-m.sandbox.paypal.com"
74 } else {
75 "api-m.paypal.com"
76 };
77 let endpoint = options
78 .user_info_endpoint
79 .unwrap_or_else(|| format!("https://{api}/v1/identity/oauth2/userinfo"));
80 Self {
81 client_id: options.client_id,
82 client_secret: options.client_secret,
83 additional_client_ids: Vec::new(),
84 hosted_domain: None,
85 require_email_verification: false,
86 auth_url: options
87 .authorization_endpoint
88 .filter(|value| !value.is_empty())
89 .unwrap_or_else(|| format!("https://{web}/signin/authorize")),
90 token_url: format!("https://{api}/v1/oauth2/token"),
91 user_info_url: Some(endpoint.clone()),
92 scopes: Vec::new(),
93 authorization: Some(OAuthAuthorizationPolicy {
94 preserve_raw_profile_scalars: true,
95 source_profile_exceptions: true,
96 allow_missing_access_token: true,
97 preserve_raw_email_errors: true,
98 omit_scopes: true,
99 require_client_id: true,
100 require_client_secret: true,
101 token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
102 redirect_uri: options.redirect_uri,
103 login_hint: false,
104 prompt: options.prompt,
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(PayPalUserInfo {
111 application_mapper: None,
112 endpoint,
113 mapper: options.map_profile_to_user,
114 })),
115 refresh_access_token: None,
116 verify_id_token: None,
117 id_token: None,
118 disable_id_token_sign_in: false,
119 disable_implicit_sign_up: false,
120 disable_sign_up: false,
121 allow_idp_initiated: false,
122 override_user_info_on_sign_in: false,
123 }
124 }
125}
126#[derive(Clone)]
127struct PayPalUserInfo {
128 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
129 endpoint: String,
130 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
131}
132#[async_trait::async_trait]
133impl OAuthUserInfoHandler for PayPalUserInfo {
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 if !super::remaining_profile::has_access_token(&request) {
153 return Err("Missing PayPal access token".into());
154 }
155 let access_token = super::remaining_profile::bearer_access_token(&request)?;
156 let profile: Value = reqwest::Client::new()
157 .get(&self.endpoint)
158 .query(&[("schema", "paypalv1.1")])
159 .bearer_auth(access_token)
160 .header("Accept", "application/json")
161 .send()
162 .await
163 .map_err(|error| error.to_string())?
164 .error_for_status()
165 .map_err(|error| error.to_string())?
166 .json()
167 .await
168 .map_err(|error| error.to_string())?;
169 if !profile.is_object() {
170 return Err("Missing PayPal profile".into());
171 }
172 if request.id_token.is_none()
173 && request
174 .raw
175 .as_ref()
176 .and_then(|raw| raw.get("id_token"))
177 .is_some_and(truthy)
178 {
179 return Err("Invalid PayPal ID token type".into());
180 }
181 if let Some(token) = super::remaining_profile::grant_id_token(&request)? {
182 let claims = super::remaining_profile::decode_grant_jwt(&token)?;
186 let token_subject = claims
187 .get("sub")
188 .filter(|value| truthy(value))
189 .ok_or("Missing PayPal ID-token subject")?;
190 let profile_subject = profile
191 .get("sub")
192 .filter(|value| !value.is_null())
193 .or_else(|| profile.get("user_id"));
194 if !profile_subject.is_some_and(|subject| {
195 super::remaining_profile::strict_primitive_equal(subject, token_subject)
196 }) {
197 return Err("PayPal ID-token subject mismatch".into());
198 }
199 }
200 let application_output = if let Some(mapper) = &self.application_mapper {
201 Some(mapper.map_profile(profile.clone()).await?)
202 } else {
203 None
204 };
205 let mapped = self
206 .mapper
207 .map(|mapper| mapper(profile.clone()))
208 .transpose()?;
209 let mut output = serde_json::Map::new();
210 for (source, target) in [
211 ("name", "name"),
212 ("email", "email"),
213 ("picture", "image"),
214 ("email_verified", "emailVerified"),
215 ] {
216 if let Some(value) = profile.get(source) {
217 _ = output.insert(target.into(), value.clone());
218 }
219 }
220 if let Some(user) = &mapped {
221 output.extend(user.public_profile(true));
222 }
223 let user = match mapped {
224 Some(user) => user,
225 None => OAuthUserInfo {
226 additional_fields: Map::default(),
227 id: profile
228 .get("user_id")
229 .map(super::remaining_profile::js_string)
230 .transpose()?
231 .unwrap_or_default(),
232 name: scalar(profile.get("name").filter(|value| truthy(value)))?,
233 email: profile
234 .get("email")
235 .and_then(Value::as_str)
236 .unwrap_or_default()
237 .into(),
238 image: scalar(profile.get("picture"))?,
239 email_verified: profile.get("email_verified").is_some_and(truthy),
240 },
241 };
242 let mut response = OAuthUserInfoResponse {
243 user_output: Some(output),
244 user,
245 data: profile,
246 };
247 if let Some(mapped) = application_output {
248 super::apply_application_mapping(&mut response, mapped)?;
249 }
250 Ok(response)
251 }
252}
253fn truthy(value: &Value) -> bool {
254 match value {
255 Value::Null | Value::Bool(false) => false,
256 Value::Number(value) => value.as_f64() != Some(0.0),
257 Value::String(value) => !value.is_empty(),
258 _ => true,
259 }
260}
261fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
262 match value {
263 None | Some(Value::Null) => Ok(None),
264 Some(Value::String(value)) => Ok(Some(value.clone())),
265 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
266 .map(Some)
267 .map_err(|error| error.to_string()),
268 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
269 _ => Err("Invalid PayPal profile field".into()),
270 }
271}
272fn subject(profile: &Value) -> Result<String, String> {
273 super::remaining_profile::raw_subject(profile.get("user_id"))
274}