alibi_api/plugins/oauth/providers/
reddit.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 RedditOptions {
13 pub client_id: String,
14 pub client_secret: Option<String>,
15 pub scope: Vec<String>,
16 pub disable_default_scope: bool,
17 pub duration: Option<String>,
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 RedditOptions {
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 scope: Vec::new(),
33 disable_default_scope: false,
34 duration: None,
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 RedditOptions {
43 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 formatter
45 .debug_struct("RedditOptions")
46 .field("client_id", &self.client_id)
47 .field("scope", &self.scope)
48 .field("disable_default_scope", &self.disable_default_scope)
49 .field("duration", &self.duration)
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 reddit(client_id: &str, client_secret: Option<&str>) -> Self {
58 Self::reddit_with_options(RedditOptions::new(
59 client_id,
60 client_secret.map(str::to_owned),
61 ))
62 }
63 #[must_use]
64 pub fn reddit_with_options(options: RedditOptions) -> Self {
65 let endpoint = options
66 .user_info_endpoint
67 .unwrap_or_else(|| "https://oauth.reddit.com/api/v1/me".into());
68 Self {
69 client_id: options.client_id,
70 client_secret: options.client_secret.unwrap_or_default(),
71 additional_client_ids: Vec::new(),
72 hosted_domain: None,
73 require_email_verification: false,
74 auth_url: options
75 .authorization_endpoint
76 .filter(|v| !v.is_empty())
77 .unwrap_or_else(|| "https://www.reddit.com/api/v1/authorize".into()),
78 token_url: "https://www.reddit.com/api/v1/access_token".into(),
79 user_info_url: Some(endpoint.clone()),
80 scopes: vec!["identity".into()],
81 authorization: Some(OAuthAuthorizationPolicy {
82 preserve_raw_profile_scalars: true,
83 source_profile_exceptions: true,
84 allow_missing_access_token: true,
85 preserve_raw_email_errors: true,
86 configured_scopes: options.scope,
87 disable_default_scopes: options.disable_default_scope,
88 require_client_id: true,
89 token_endpoint_auth: Some(OAuthTokenEndpointAuth::ClientSecretBasic),
90 authorization_code_headers: vec![
91 ("accept".into(), "text/plain".into()),
92 ("user-agent".into(), "better-auth".into()),
93 ],
94 redirect_uri: options.redirect_uri,
95 login_hint: false,
96 pkce: false,
97 ..OAuthAuthorizationPolicy::default()
98 }),
99 authorization_params: options
100 .duration
101 .filter(|v| !v.is_empty())
102 .map(|v| vec![("duration".into(), v)])
103 .unwrap_or_default(),
104 account_subject: Some(subject),
105 map_user_info: None,
106 get_user_info: Some(std::sync::Arc::new(RedditUserInfo {
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 RedditUserInfo {
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 RedditUserInfo {
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 profile: Value = reqwest::Client::new()
149 .get(&self.endpoint)
150 .bearer_auth(access_token)
151 .header("User-Agent", "better-auth")
152 .send()
153 .await
154 .map_err(|e| e.to_string())?
155 .error_for_status()
156 .map_err(|e| e.to_string())?
157 .json()
158 .await
159 .map_err(|e| e.to_string())?;
160 let mapped = if let Some(mapper) = &self.application_mapper {
161 mapper
162 .map_profile(profile.clone())
163 .await
164 .map_err(super::remaining_profile::profile_exception)?
165 } else {
166 self.mapper
167 .map(|mapper| mapper(profile.clone()))
168 .transpose()
169 .map_err(super::remaining_profile::profile_exception)?
170 .map(|user| user.public_profile(true))
171 .unwrap_or_default()
172 };
173 if profile.is_null() {
174 return Err(super::remaining_profile::profile_exception(
175 "Null Reddit profile",
176 ));
177 }
178 let email = match mapped
179 .get("email")
180 .filter(|value| super::remaining_profile::truthy(value))
181 {
182 Some(value) => value.clone(),
183 None => {
184 let identifier = profile
185 .get("id")
186 .map(super::remaining_profile::js_string)
187 .transpose()
188 .map_err(super::remaining_profile::profile_exception)?
189 .unwrap_or_else(|| "undefined".into());
190 let email = format!("{identifier}@reddit.placeholder.invalid");
191 if !crate::plugins::authentication_helpers::is_valid_email(&email) {
192 return Err(super::remaining_profile::profile_exception(
193 "Invalid placeholder email",
194 ));
195 }
196 Value::String(email)
197 }
198 };
199 let image = match profile.get("icon_img") {
200 None | Some(Value::Null) => None,
201 Some(Value::String(image)) => Some(Value::String(
202 image.split('?').next().unwrap_or_default().into(),
203 )),
204 _ => {
205 return Err(super::remaining_profile::profile_exception(
206 "Invalid Reddit icon_img",
207 ));
208 }
209 };
210 let mut output = serde_json::Map::new();
211 if let Some(name) = profile.get("name") {
212 drop(output.insert("name".into(), name.clone()));
213 }
214 if let Some(image) = image {
215 drop(output.insert("image".into(), image));
216 }
217 output.extend(mapped.clone());
218 drop(output.insert("email".into(), email));
219 drop(
220 output.insert(
221 "emailVerified".into(),
222 mapped
223 .get("emailVerified")
224 .filter(|value| !value.is_null())
225 .cloned()
226 .unwrap_or(Value::Bool(false)),
227 ),
228 );
229 let user = OAuthUserInfo {
230 additional_fields: output
231 .iter()
232 .filter(|(key, _)| {
233 !matches!(
234 key.as_str(),
235 "id" | "name" | "email" | "image" | "emailVerified"
236 )
237 })
238 .map(|(key, value)| (key.clone(), value.clone()))
239 .collect(),
240 id: profile
241 .get("id")
242 .map(super::remaining_profile::js_string)
243 .transpose()
244 .map_err(super::remaining_profile::profile_exception)?
245 .unwrap_or_default(),
246 name: super::remaining_profile::scalar(
247 output
248 .get("name")
249 .filter(|value| super::remaining_profile::truthy(value)),
250 )?,
251 email: output
252 .get("email")
253 .and_then(Value::as_str)
254 .unwrap_or_default()
255 .into(),
256 image: super::remaining_profile::scalar(output.get("image"))?,
257 email_verified: output
258 .get("emailVerified")
259 .is_some_and(super::remaining_profile::truthy),
260 };
261 Ok(OAuthUserInfoResponse {
262 user_output: Some(output),
263 user,
264 data: profile,
265 })
266 }
267}
268fn subject(profile: &Value) -> Result<String, String> {
269 super::remaining_profile::raw_subject(profile.get("id"))
270}