Skip to main content

alibi_plugins/oauth/providers/
reddit.rs

1//! Reddit's non-PKCE Basic grants and stable placeholder-email profile.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Value;
8
9/// Application-owned Reddit configuration. Signup policies and asynchronous
10/// user-info/refresh overrides remain available on the returned native provider.
11#[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    /// Forwarded when nonempty; caller additional parameters take precedence.
18    pub duration: Option<String>,
19    pub authorization_endpoint: Option<String>,
20    pub redirect_uri: Option<String>,
21    /// Trusted application transport override preserving Reddit's mapping.
22    pub user_info_endpoint: Option<String>,
23    /// Receives the original profile before account identity resolution.
24    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            allow_idp_initiated: false,
118            override_user_info_on_sign_in: false,
119        }
120    }
121}
122#[derive(Clone)]
123struct RedditUserInfo {
124    application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
125    endpoint: String,
126    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
127}
128#[async_trait]
129impl OAuthUserInfoHandler for RedditUserInfo {
130    fn errors_are_exceptions(&self) -> bool {
131        false
132    }
133
134    fn mapped_handler(
135        &self,
136        mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
137    ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
138        let mut handler = self.clone();
139        handler.mapper = None;
140        handler.application_mapper = Some(mapper);
141        Some(std::sync::Arc::new(handler))
142    }
143
144    async fn get_user_info(
145        &self,
146        request: OAuthUserInfoRequest,
147    ) -> Result<OAuthUserInfoResponse, String> {
148        let access_token = super::remaining_profile::bearer_access_token(&request)?;
149        let profile: Value = reqwest::Client::new()
150            .get(&self.endpoint)
151            .bearer_auth(access_token)
152            .header("User-Agent", "better-auth")
153            .send()
154            .await
155            .map_err(|e| e.to_string())?
156            .error_for_status()
157            .map_err(|e| e.to_string())?
158            .json()
159            .await
160            .map_err(|e| e.to_string())?;
161        let mapped = if let Some(mapper) = &self.application_mapper {
162            mapper
163                .map_profile(profile.clone())
164                .await
165                .map_err(super::remaining_profile::profile_exception)?
166        } else {
167            self.mapper
168                .map(|mapper| mapper(profile.clone()))
169                .transpose()
170                .map_err(super::remaining_profile::profile_exception)?
171                .map(|user| user.public_profile(true))
172                .unwrap_or_default()
173        };
174        if profile.is_null() {
175            return Err(super::remaining_profile::profile_exception(
176                "Null Reddit profile",
177            ));
178        }
179        let email = if let Some(value) = mapped
180            .get("email")
181            .filter(|value| super::remaining_profile::truthy(value))
182        {
183            value.clone()
184        } else {
185            let identifier = profile
186                .get("id")
187                .map(super::remaining_profile::js_string)
188                .transpose()
189                .map_err(super::remaining_profile::profile_exception)?
190                .unwrap_or_else(|| "undefined".into());
191            let email = format!("{identifier}@reddit.placeholder.invalid");
192            if !crate::authentication_helpers::is_valid_email(&email) {
193                return Err(super::remaining_profile::profile_exception(
194                    "Invalid placeholder email",
195                ));
196            }
197            Value::String(email)
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            _ = output.insert("name".into(), name.clone());
213        }
214        if let Some(image) = image {
215            _ = output.insert("image".into(), image);
216        }
217        output.extend(mapped.clone());
218        _ = output.insert("email".into(), email);
219        _ = output.insert(
220            "emailVerified".into(),
221            mapped
222                .get("emailVerified")
223                .filter(|value| !value.is_null())
224                .cloned()
225                .unwrap_or(Value::Bool(false)),
226        );
227        let user = OAuthUserInfo {
228            additional_fields: output
229                .iter()
230                .filter(|(key, _)| {
231                    !matches!(
232                        key.as_str(),
233                        "id" | "name" | "email" | "image" | "emailVerified"
234                    )
235                })
236                .map(|(key, value)| (key.clone(), value.clone()))
237                .collect(),
238            id: profile
239                .get("id")
240                .map(super::remaining_profile::js_string)
241                .transpose()
242                .map_err(super::remaining_profile::profile_exception)?
243                .unwrap_or_default(),
244            name: super::remaining_profile::scalar(
245                output
246                    .get("name")
247                    .filter(|value| super::remaining_profile::truthy(value)),
248            )?,
249            email: output
250                .get("email")
251                .and_then(Value::as_str)
252                .unwrap_or_default()
253                .into(),
254            image: super::remaining_profile::scalar(output.get("image"))?,
255            email_verified: output
256                .get("emailVerified")
257                .is_some_and(super::remaining_profile::truthy),
258        };
259        Ok(OAuthUserInfoResponse {
260            user_output: Some(output),
261            user,
262            data: profile,
263        })
264    }
265}
266fn subject(profile: &Value) -> Result<String, String> {
267    super::remaining_profile::raw_subject(profile.get("id"))
268}