Skip to main content

alibi_plugins/oauth/providers/
twitter.rs

1//! Dedicated published Better Auth 1.7.6 Twitter factory.
2use super::remaining_profile::{ProfileKind, PublishedProfile};
3use super::{OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo};
4use serde_json::Value;
5
6#[derive(Clone)]
7pub struct TwitterOptions {
8    pub client_id: String,
9    pub client_secret: Option<String>,
10    pub client_key: Option<String>,
11    pub authorization_endpoint: Option<String>,
12    pub redirect_uri: Option<String>,
13    /// Trusted application transport override; it does not change profile semantics.
14    pub user_info_endpoint: Option<String>,
15    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
16    pub scope: Vec<String>,
17    pub disable_default_scope: bool,
18    /// Trusted transport for the second, independent confirmed-email request.
19    pub email_info_endpoint: Option<String>,
20}
21impl TwitterOptions {
22    #[must_use]
23    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
24        Self {
25            client_id: client_id.into(),
26            client_secret,
27            client_key: None,
28            authorization_endpoint: None,
29            redirect_uri: None,
30            user_info_endpoint: None,
31            map_profile_to_user: None,
32            scope: Vec::new(),
33            disable_default_scope: false,
34            email_info_endpoint: None,
35        }
36    }
37}
38impl std::fmt::Debug for TwitterOptions {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("TwitterOptions")
41            .field("client_id", &self.client_id)
42            .field("authorization_endpoint", &self.authorization_endpoint)
43            .finish_non_exhaustive()
44    }
45}
46impl OAuthProvider {
47    #[must_use]
48    pub fn twitter(client_id: &str, client_secret: Option<&str>) -> Self {
49        Self::twitter_with_options(TwitterOptions::new(
50            client_id,
51            client_secret.map(str::to_owned),
52        ))
53    }
54    #[must_use]
55    pub fn twitter_with_options(options: TwitterOptions) -> Self {
56        let mut policy = OAuthAuthorizationPolicy {
57            preserve_raw_profile_scalars: true,
58            source_profile_exceptions: true,
59            require_client_id: true,
60            login_hint: false,
61            pkce: true,
62            configured_scopes: options.scope,
63            disable_default_scopes: options.disable_default_scope,
64            authorization_code_client_key: options.client_key,
65            redirect_uri: options.redirect_uri,
66            token_endpoint_auth: Some(
67                if options
68                    .client_secret
69                    .as_ref()
70                    .is_some_and(|v| !v.is_empty())
71                {
72                    OAuthTokenEndpointAuth::ClientSecretPost
73                } else {
74                    OAuthTokenEndpointAuth::None
75                },
76            ),
77            allow_missing_access_token: true,
78            preserve_raw_email_errors: true,
79            ..OAuthAuthorizationPolicy::default()
80        };
81        let mut provider = Self {
82            client_id: options.client_id,
83            client_secret: options.client_secret.unwrap_or_default(),
84            additional_client_ids: Vec::new(),
85            hosted_domain: None,
86            require_email_verification: false,
87            auth_url: "https://x.com/i/oauth2/authorize".into(),
88            token_url: "https://api.x.com/2/oauth2/token".into(),
89            user_info_url: Some(
90                "https://api.x.com/2/users/me?user.fields=profile_image_url".into(),
91            ),
92            scopes: vec![
93                "users.read".into(),
94                "tweet.read".into(),
95                "offline.access".into(),
96                "users.email".into(),
97            ],
98            authorization: None,
99            allowed_request_params: Vec::new(),
100            authorization_params: Vec::new(),
101            account_subject: Some(subject),
102            map_user_info: None,
103            get_user_info: None,
104            refresh_access_token: None,
105            verify_id_token: None,
106            id_token: None,
107            disable_id_token_sign_in: false,
108            disable_implicit_sign_up: false,
109            disable_sign_up: false,
110            allow_idp_initiated: false,
111            override_user_info_on_sign_in: false,
112        };
113        provider.auth_url = options
114            .authorization_endpoint
115            .filter(|v| !v.is_empty())
116            .unwrap_or(provider.auth_url);
117        provider.user_info_url = options.user_info_endpoint.or(provider.user_info_url);
118        policy.token_endpoint_auth = Some(OAuthTokenEndpointAuth::ClientSecretBasic);
119        provider.authorization = Some(policy);
120        provider.get_user_info = Some(std::sync::Arc::new(PublishedProfile {
121            kind: ProfileKind::Twitter,
122            endpoint: provider.user_info_url.clone(),
123            email_endpoint: options.email_info_endpoint,
124            client_id: provider.client_id.clone(),
125            mapper: options.map_profile_to_user,
126            application_mapper: None,
127        }));
128        provider
129    }
130}
131fn subject(profile: &Value) -> Result<String, String> {
132    super::remaining_profile::subject(ProfileKind::Twitter, profile)
133}