alibi_plugins/oauth/providers/
notion.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 NotionOptions {
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 user_info_endpoint: Option<String>,
24 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
26}
27impl NotionOptions {
28 #[must_use]
29 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
30 Self {
31 client_id: client_id.into(),
32 client_secret,
33 client_key: None,
34 scope: Vec::new(),
35 disable_default_scope: false,
36 authorization_endpoint: None,
37 redirect_uri: None,
38 user_info_endpoint: None,
39 map_profile_to_user: None,
40 }
41 }
42}
43impl std::fmt::Debug for NotionOptions {
44 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 formatter
46 .debug_struct("NotionOptions")
47 .field("client_id", &self.client_id)
48 .field("scope", &self.scope)
49 .field("disable_default_scope", &self.disable_default_scope)
50 .field("authorization_endpoint", &self.authorization_endpoint)
51 .field("redirect_uri", &self.redirect_uri)
52 .finish_non_exhaustive()
53 }
54}
55impl OAuthProvider {
56 #[must_use]
57 pub fn notion(client_id: &str, client_secret: Option<&str>) -> Self {
58 Self::notion_with_options(NotionOptions::new(
59 client_id,
60 client_secret.map(str::to_owned),
61 ))
62 }
63 #[must_use]
64 pub fn notion_with_options(options: NotionOptions) -> Self {
65 let secret = options.client_secret.unwrap_or_default();
66 let refresh_authentication = if secret.is_empty() {
67 OAuthTokenEndpointAuth::None
68 } else {
69 OAuthTokenEndpointAuth::ClientSecretPost
70 };
71 let endpoint = options
72 .user_info_endpoint
73 .unwrap_or_else(|| "https://api.notion.com/v1/users/me".into());
74 Self {
75 client_id: options.client_id,
76 client_secret: secret,
77 additional_client_ids: Vec::new(),
78 hosted_domain: None,
79 require_email_verification: false,
80 auth_url: options
81 .authorization_endpoint
82 .filter(|value| !value.is_empty())
83 .unwrap_or_else(|| "https://api.notion.com/v1/oauth/authorize".into()),
84 token_url: "https://api.notion.com/v1/oauth/token".into(),
85 user_info_url: Some(endpoint.clone()),
86 scopes: Vec::new(),
87 authorization: Some(OAuthAuthorizationPolicy {
88 preserve_raw_profile_scalars: true,
89 source_profile_exceptions: true,
90 allow_missing_access_token: true,
91 preserve_raw_email_errors: true,
92 configured_scopes: options.scope,
93 disable_default_scopes: options.disable_default_scope,
94 require_client_id: true,
95 token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
96 refresh_token_endpoint_auth: Some(refresh_authentication),
97 fixed_authorization_params: vec![("owner".into(), "user".into())],
98 authorization_code_client_key: options.client_key,
99 redirect_uri: options.redirect_uri,
100 login_hint: true,
101 pkce: false,
102 ..OAuthAuthorizationPolicy::default()
103 }),
104 authorization_params: Vec::new(),
105 account_subject: Some(subject),
106 map_user_info: None,
107 get_user_info: Some(std::sync::Arc::new(NotionUserInfo {
108 application_mapper: None,
109 endpoint,
110 mapper: options.map_profile_to_user,
111 })),
112 refresh_access_token: None,
113 verify_id_token: None,
114 id_token: None,
115 disable_id_token_sign_in: false,
116 disable_implicit_sign_up: false,
117 disable_sign_up: false,
118 allow_idp_initiated: false,
119 override_user_info_on_sign_in: false,
120 }
121 }
122}
123#[derive(Clone)]
124struct NotionUserInfo {
125 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
126 endpoint: String,
127 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
128}
129#[async_trait]
130impl OAuthUserInfoHandler for NotionUserInfo {
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 access_token = super::remaining_profile::bearer_access_token(&request)?;
150 let response: Value = reqwest::Client::new()
151 .get(&self.endpoint)
152 .header("Notion-Version", "2022-06-28")
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 profile = response
163 .get("bot")
164 .and_then(|bot| bot.get("owner"))
165 .and_then(|owner| owner.get("user"))
166 .filter(|user| truthy(user))
167 .cloned()
168 .ok_or("Missing Notion profile")?;
169 let application_output = if let Some(mapper) = &self.application_mapper {
170 Some(
171 mapper
172 .map_profile(profile.clone())
173 .await
174 .map_err(super::remaining_profile::profile_exception)?,
175 )
176 } else {
177 None
178 };
179 let mapped = self
180 .mapper
181 .map(|mapper| mapper(profile.clone()))
182 .transpose()
183 .map_err(super::remaining_profile::profile_exception)?;
184 let mut output = serde_json::Map::new();
186 _ = output.insert(
187 "name".into(),
188 profile
189 .get("name")
190 .filter(|v| truthy(v))
191 .cloned()
192 .unwrap_or_else(|| Value::String(String::new())),
193 );
194 let email = profile
195 .get("person")
196 .and_then(|person| person.get("email"))
197 .filter(|v| truthy(v));
198 _ = output.insert("email".into(), email.cloned().unwrap_or(Value::Null));
199 if let Some(image) = profile.get("avatar_url") {
200 _ = output.insert("image".into(), image.clone());
201 }
202 _ = output.insert("emailVerified".into(), Value::Bool(false));
203 if let Some(user) = &mapped {
204 output.extend(user.public_profile(true));
205 }
206 let user_output = Some(output);
207 let user = match mapped {
208 Some(user) => user,
209 None => OAuthUserInfo {
210 additional_fields: Map::default(),
211 id: profile
212 .get("id")
213 .map(super::remaining_profile::js_string)
214 .transpose()?
215 .unwrap_or_default(),
216 name: scalar(profile.get("name").filter(|v| truthy(v)))?
217 .or_else(|| Some(String::new())),
218 email: email.and_then(Value::as_str).unwrap_or_default().into(),
219 image: scalar(profile.get("avatar_url"))?,
220 email_verified: false,
221 },
222 };
223 let mut response = OAuthUserInfoResponse {
224 user_output,
225 user,
226 data: profile,
227 };
228 if let Some(mapped) = application_output {
229 super::apply_application_mapping(&mut response, mapped)?;
230 }
231 Ok(response)
232 }
233}
234fn truthy(value: &Value) -> bool {
235 match value {
236 Value::Null | Value::Bool(false) => false,
237 Value::Number(value) => value.as_f64() != Some(0.0),
238 Value::String(value) => !value.is_empty(),
239 Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
240 }
241}
242fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
243 match value {
244 Some(Value::String(value)) => Ok(Some(value.clone())),
245 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
246 .map(Some)
247 .map_err(|error| error.to_string()),
248 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
249 None | Some(Value::Null | Value::Array(_) | Value::Object(_)) => Ok(None),
250 }
251}
252fn subject(profile: &Value) -> Result<String, String> {
253 super::remaining_profile::raw_subject(profile.get("id"))
254}