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