Skip to main content

alibi_plugins/oauth/providers/
discord.rs

1use super::{OAuthAuthorizationPolicy, OAuthProvider, OAuthScopeOrder, OAuthUserInfo, Value};
2use serde_json::Map;
3impl OAuthProvider {
4    #[must_use]
5    pub fn discord(client_id: &str, client_secret: &str) -> Self {
6        Self {
7            client_id: client_id.to_owned(),
8            additional_client_ids: Vec::new(),
9            hosted_domain: None,
10            require_email_verification: false,
11            client_secret: client_secret.to_owned(),
12            auth_url: "https://discord.com/api/oauth2/authorize".to_owned(),
13            token_url: "https://discord.com/api/oauth2/token".to_owned(),
14            user_info_url: Some("https://discord.com/api/users/@me".to_owned()),
15            scopes: vec!["identify".to_owned(), "email".to_owned()],
16            authorization: Some(OAuthAuthorizationPolicy {
17                scope_order: OAuthScopeOrder::RequestedThenConfigured,
18                pkce: false,
19                default_prompt: Some("none".into()),
20                ..OAuthAuthorizationPolicy::default()
21            }),
22            allowed_request_params: Vec::new(),
23            authorization_params: Vec::new(),
24            account_subject: None,
25            map_user_info: Some(discord_user_info),
26            get_user_info: None,
27            refresh_access_token: None,
28            verify_id_token: None,
29            id_token: None,
30            disable_id_token_sign_in: false,
31            disable_implicit_sign_up: false,
32            disable_sign_up: false,
33            allow_idp_initiated: false,
34            override_user_info_on_sign_in: false,
35        }
36    }
37}
38
39/// Discord's normalized user fields for its declared string profile schema.
40#[expect(
41    clippy::needless_pass_by_value,
42    reason = "Match the public provider callback type, which owns its JSON profile"
43)]
44pub(in crate::oauth::providers) fn discord_user_info(
45    profile: Value,
46) -> Result<OAuthUserInfo, String> {
47    let id = profile
48        .get("id")
49        .and_then(Value::as_str)
50        .ok_or("missing id")?;
51    let email = profile
52        .get("email")
53        .and_then(Value::as_str)
54        .ok_or("missing email")?;
55    let image = if profile.get("avatar").is_some_and(Value::is_null) {
56        let discriminator = profile
57            .get("discriminator")
58            .and_then(Value::as_str)
59            .ok_or("missing discriminator")?;
60        let index = if discriminator == "0" {
61            // Source converts the shifted BigInt to Number before remainder.
62            // This must retain f64 rounding and overflow, rather than exact mod.
63            if id.is_empty() || !id.bytes().all(|byte| byte.is_ascii_digit()) {
64                return Err("invalid Discord decimal snowflake".to_owned());
65            }
66            let snowflake =
67                rsa::BigUint::parse_bytes(id.as_bytes(), 10).ok_or("invalid Discord snowflake")?;
68            let shifted = (snowflake >> 22usize)
69                .to_str_radix(10)
70                .parse::<f64>()
71                .map_err(|_error| "invalid Discord snowflake number")?;
72            shifted % 6.0
73        } else {
74            // Discord's declared discriminator consists of decimal digits.
75            discriminator
76                .parse::<f64>()
77                .map_err(|_error| "invalid Discord discriminator")?
78                % 5.0
79        };
80        format!("https://cdn.discordapp.com/embed/avatars/{index}.png")
81    } else {
82        let avatar = profile
83            .get("avatar")
84            .and_then(Value::as_str)
85            .ok_or("missing avatar")?;
86        let format = if avatar.starts_with("a_") {
87            "gif"
88        } else {
89            "png"
90        };
91        format!("https://cdn.discordapp.com/avatars/{id}/{avatar}.{format}")
92    };
93    Ok(OAuthUserInfo {
94        additional_fields: Map::default(),
95        id: id.to_owned(),
96        email: email.to_owned(),
97        name: Some(
98            profile
99                .get("global_name")
100                .and_then(Value::as_str)
101                .filter(|name| !name.is_empty())
102                .or_else(|| profile.get("username").and_then(Value::as_str))
103                .unwrap_or_default()
104                .to_owned(),
105        ),
106        image: Some(image),
107        email_verified: profile
108            .get("verified")
109            .and_then(Value::as_bool)
110            .unwrap_or(false),
111    })
112}