alibi_api/plugins/oauth/providers/
notion.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 NotionOptions {
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 NotionOptions {
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 NotionOptions {
43 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 formatter
45 .debug_struct("NotionOptions")
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 notion(client_id: &str, client_secret: Option<&str>) -> Self {
57 Self::notion_with_options(NotionOptions::new(
58 client_id,
59 client_secret.map(str::to_owned),
60 ))
61 }
62 #[must_use]
63 pub fn notion_with_options(options: NotionOptions) -> Self {
64 let secret = options.client_secret.unwrap_or_default();
65 let refresh_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.notion.com/v1/users/me".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://api.notion.com/v1/oauth/authorize".into()),
83 token_url: "https://api.notion.com/v1/oauth/token".into(),
84 user_info_url: Some(endpoint.clone()),
85 scopes: Vec::new(),
86 authorization: Some(OAuthAuthorizationPolicy {
87 preserve_raw_profile_scalars: true,
88 source_profile_exceptions: true,
89 allow_missing_access_token: true,
90 preserve_raw_email_errors: true,
91 configured_scopes: options.scope,
92 disable_default_scopes: options.disable_default_scope,
93 require_client_id: true,
94 token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
95 refresh_token_endpoint_auth: Some(refresh_authentication),
96 fixed_authorization_params: vec![("owner".into(), "user".into())],
97 authorization_code_client_key: options.client_key,
98 redirect_uri: options.redirect_uri,
99 login_hint: true,
100 pkce: false,
101 ..OAuthAuthorizationPolicy::default()
102 }),
103 authorization_params: Vec::new(),
104 account_subject: Some(subject),
105 map_user_info: None,
106 get_user_info: Some(std::sync::Arc::new(NotionUserInfo {
107 application_mapper: None,
108 endpoint,
109 mapper: options.map_profile_to_user,
110 })),
111 refresh_access_token: None,
112 verify_id_token: None,
113 id_token: None,
114 disable_id_token_sign_in: false,
115 disable_implicit_sign_up: false,
116 disable_sign_up: false,
117 override_user_info_on_sign_in: false,
118 }
119 }
120}
121#[derive(Clone)]
122struct NotionUserInfo {
123 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
124 endpoint: String,
125 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
126}
127#[async_trait]
128impl OAuthUserInfoHandler for NotionUserInfo {
129 fn errors_are_exceptions(&self) -> bool {
130 false
131 }
132
133 fn mapped_handler(
134 &self,
135 mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
136 ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
137 let mut handler = self.clone();
138 handler.mapper = None;
139 handler.application_mapper = Some(mapper);
140 Some(std::sync::Arc::new(handler))
141 }
142
143 async fn get_user_info(
144 &self,
145 request: OAuthUserInfoRequest,
146 ) -> Result<OAuthUserInfoResponse, String> {
147 let access_token = super::remaining_profile::bearer_access_token(&request)?;
148 let response: Value = reqwest::Client::new()
149 .get(&self.endpoint)
150 .header("Notion-Version", "2022-06-28")
151 .bearer_auth(access_token)
152 .send()
153 .await
154 .map_err(|error| error.to_string())?
155 .error_for_status()
156 .map_err(|error| error.to_string())?
157 .json()
158 .await
159 .map_err(|error| error.to_string())?;
160 let profile = response
161 .get("bot")
162 .and_then(|bot| bot.get("owner"))
163 .and_then(|owner| owner.get("user"))
164 .filter(|user| truthy(user))
165 .cloned()
166 .ok_or("Missing Notion profile")?;
167 let application_output = if let Some(mapper) = &self.application_mapper {
168 Some(
169 mapper
170 .map_profile(profile.clone())
171 .await
172 .map_err(super::remaining_profile::profile_exception)?,
173 )
174 } else {
175 None
176 };
177 let mapped = self
178 .mapper
179 .map(|mapper| mapper(profile.clone()))
180 .transpose()
181 .map_err(super::remaining_profile::profile_exception)?;
182 let mut output = serde_json::Map::new();
184 drop(
185 output.insert(
186 "name".into(),
187 profile
188 .get("name")
189 .filter(|v| truthy(v))
190 .cloned()
191 .unwrap_or_else(|| Value::String(String::new())),
192 ),
193 );
194 let email = profile
195 .get("person")
196 .and_then(|person| person.get("email"))
197 .filter(|v| truthy(v));
198 drop(output.insert("email".into(), email.cloned().unwrap_or(Value::Null)));
199 if let Some(image) = profile.get("avatar_url") {
200 drop(output.insert("image".into(), image.clone()));
201 }
202 drop(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: Default::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 None | Some(Value::Null) => Ok(None),
245 Some(Value::String(value)) => Ok(Some(value.clone())),
246 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
247 .map(Some)
248 .map_err(|error| error.to_string()),
249 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
250 Some(Value::Array(_) | Value::Object(_)) => Ok(None),
251 }
252}
253fn subject(profile: &Value) -> Result<String, String> {
254 super::remaining_profile::raw_subject(profile.get("id"))
255}