alibi_api/plugins/oauth/providers/
linkedin.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4 OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Value;
8
9#[derive(Clone)]
12pub struct LinkedInOptions {
13 pub client_id: String,
14 pub client_secret: Option<String>,
15 pub client_key: Option<String>,
17 pub scope: Vec<String>,
18 pub disable_default_scope: bool,
19 pub authorization_endpoint: Option<String>,
20 pub redirect_uri: Option<String>,
21 pub user_info_endpoint: Option<String>,
23 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
25}
26impl LinkedInOptions {
27 #[must_use]
28 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
29 Self {
30 client_id: client_id.into(),
31 client_secret,
32 client_key: None,
33 scope: Vec::new(),
34 disable_default_scope: false,
35 authorization_endpoint: None,
36 redirect_uri: None,
37 user_info_endpoint: None,
38 map_profile_to_user: None,
39 }
40 }
41}
42impl std::fmt::Debug for LinkedInOptions {
43 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 formatter
45 .debug_struct("LinkedInOptions")
46 .field("client_id", &self.client_id)
47 .field("scope", &self.scope)
48 .field("disable_default_scope", &self.disable_default_scope)
49 .field("authorization_endpoint", &self.authorization_endpoint)
50 .field("redirect_uri", &self.redirect_uri)
51 .finish_non_exhaustive()
52 }
53}
54impl OAuthProvider {
55 #[must_use]
56 pub fn linkedin(client_id: &str, client_secret: Option<&str>) -> Self {
57 Self::linkedin_with_options(LinkedInOptions::new(
58 client_id,
59 client_secret.map(str::to_owned),
60 ))
61 }
62 #[must_use]
63 pub fn linkedin_with_options(options: LinkedInOptions) -> Self {
64 let secret = options.client_secret.unwrap_or_default();
65 let authentication = if secret.is_empty() {
66 OAuthTokenEndpointAuth::None
67 } else {
68 OAuthTokenEndpointAuth::ClientSecretPost
69 };
70 let endpoint = options
71 .user_info_endpoint
72 .unwrap_or_else(|| "https://api.linkedin.com/v2/userinfo".into());
73 Self {
74 client_id: options.client_id,
75 client_secret: secret,
76 additional_client_ids: Vec::new(),
77 hosted_domain: None,
78 require_email_verification: false,
79 auth_url: options
80 .authorization_endpoint
81 .filter(|value| !value.is_empty())
82 .unwrap_or_else(|| "https://www.linkedin.com/oauth/v2/authorization".into()),
83 token_url: "https://www.linkedin.com/oauth/v2/accessToken".into(),
84 user_info_url: Some(endpoint.clone()),
85 scopes: ["profile", "email", "openid"].map(String::from).to_vec(),
86 authorization: Some(OAuthAuthorizationPolicy {
87 configured_scopes: options.scope,
88 disable_default_scopes: options.disable_default_scope,
89 require_client_id: true,
90 token_endpoint_auth: Some(authentication),
91 authorization_code_client_key: options.client_key,
92 redirect_uri: options.redirect_uri,
93 login_hint: true,
94 pkce: false,
95 ..OAuthAuthorizationPolicy::default()
96 }),
97 authorization_params: Vec::new(),
98 account_subject: Some(subject),
99 map_user_info: None,
100 get_user_info: Some(std::sync::Arc::new(LinkedInUserInfo {
101 endpoint,
102 mapper: options.map_profile_to_user,
103 })),
104 refresh_access_token: None,
105 verify_id_token: None,
106 id_token: None,
107 disable_id_token_sign_in: false,
108 disable_implicit_sign_up: false,
109 disable_sign_up: false,
110 override_user_info_on_sign_in: false,
111 }
112 }
113}
114struct LinkedInUserInfo {
115 endpoint: String,
116 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
117}
118#[async_trait]
119impl OAuthUserInfoHandler for LinkedInUserInfo {
120 async fn get_user_info(
121 &self,
122 request: OAuthUserInfoRequest,
123 ) -> Result<OAuthUserInfoResponse, String> {
124 let access_token = request
125 .access_token
126 .ok_or("Missing LinkedIn access token")?;
127 let response: Value = reqwest::Client::new()
128 .get(&self.endpoint)
129 .bearer_auth(access_token)
130 .send()
131 .await
132 .map_err(|error| error.to_string())?
133 .error_for_status()
134 .map_err(|error| error.to_string())?
135 .json()
136 .await
137 .map_err(|error| error.to_string())?;
138 let profile = response;
139 let mapped = self
140 .mapper
141 .map(|mapper| mapper(profile.clone()))
142 .transpose()?;
143 let mut output = serde_json::Map::new();
146 for (source, target) in [("name", "name"), ("email", "email"), ("picture", "image")] {
147 if let Some(value) = profile.get(source) {
148 drop(output.insert(target.into(), value.clone()));
149 }
150 }
151 drop(
152 output.insert(
153 "emailVerified".into(),
154 profile
155 .get("email_verified")
156 .filter(|value| !value.is_null())
157 .cloned()
158 .unwrap_or(Value::Bool(false)),
159 ),
160 );
161 if let Some(user) = &mapped {
162 output.extend(user.public_profile(true));
163 }
164 let user_output = Some(output);
165 let user = match mapped {
166 Some(user) => user,
167 None => OAuthUserInfo {
168 additional_fields: Default::default(),
169 id: scalar(profile.get("sub"))?.unwrap_or_default(),
170 name: scalar(profile.get("name"))?,
171 email: profile
172 .get("email")
173 .and_then(Value::as_str)
174 .unwrap_or_default()
175 .into(),
176 image: scalar(profile.get("picture"))?,
177 email_verified: profile
178 .get("email_verified")
179 .and_then(Value::as_bool)
180 .unwrap_or(false),
181 },
182 };
183 Ok(OAuthUserInfoResponse {
184 user_output,
185 user,
186 data: profile,
187 })
188 }
189}
190fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
191 match value {
192 None | Some(Value::Null) => Ok(None),
193 Some(Value::String(value)) => Ok(Some(value.clone())),
194 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
195 .map(Some)
196 .map_err(|error| error.to_string()),
197 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
198 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid LinkedIn profile field".into()),
199 }
200}
201fn subject(profile: &Value) -> Result<String, String> {
202 let id = scalar(profile.get("sub"))?.ok_or("Missing LinkedIn subject")?;
203 if id
204 .trim_matches(|character: char| {
205 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
206 })
207 .is_empty()
208 || id == "null"
209 || id == "undefined"
210 {
211 return Err("Invalid LinkedIn subject".into());
212 }
213 Ok(id)
214}