alibi_plugins/oauth/providers/
twitch.rs1use super::remaining_profile::{ProfileKind, PublishedProfile};
3use super::{OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo};
4use serde_json::Value;
5
6#[derive(Clone)]
7pub struct TwitchOptions {
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 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 pub claims: Option<Vec<String>>,
19}
20impl TwitchOptions {
21 #[must_use]
22 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
23 Self {
24 client_id: client_id.into(),
25 client_secret,
26 client_key: None,
27 authorization_endpoint: None,
28 redirect_uri: None,
29 user_info_endpoint: None,
30 map_profile_to_user: None,
31 scope: Vec::new(),
32 disable_default_scope: false,
33 claims: None,
34 }
35 }
36}
37impl std::fmt::Debug for TwitchOptions {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 f.debug_struct("TwitchOptions")
40 .field("client_id", &self.client_id)
41 .field("authorization_endpoint", &self.authorization_endpoint)
42 .finish_non_exhaustive()
43 }
44}
45impl OAuthProvider {
46 #[must_use]
47 pub fn twitch(client_id: &str, client_secret: Option<&str>) -> Self {
48 Self::twitch_with_options(TwitchOptions::new(
49 client_id,
50 client_secret.map(str::to_owned),
51 ))
52 }
53 #[must_use]
54 pub fn twitch_with_options(options: TwitchOptions) -> Self {
55 let mut policy = OAuthAuthorizationPolicy {
56 preserve_raw_profile_scalars: true,
57 source_profile_exceptions: true,
58 require_client_id: true,
59 login_hint: false,
60 pkce: false,
61 configured_scopes: options.scope,
62 disable_default_scopes: options.disable_default_scope,
63 authorization_code_client_key: options.client_key,
64 redirect_uri: options.redirect_uri,
65 token_endpoint_auth: Some(
66 if options
67 .client_secret
68 .as_ref()
69 .is_some_and(|v| !v.is_empty())
70 {
71 OAuthTokenEndpointAuth::ClientSecretPost
72 } else {
73 OAuthTokenEndpointAuth::None
74 },
75 ),
76 allow_missing_access_token: true,
77 preserve_raw_email_errors: true,
78 ..OAuthAuthorizationPolicy::default()
79 };
80 let mut provider = Self {
81 client_id: options.client_id,
82 client_secret: options.client_secret.unwrap_or_default(),
83 additional_client_ids: Vec::new(),
84 hosted_domain: None,
85 require_email_verification: false,
86 auth_url: "https://id.twitch.tv/oauth2/authorize".into(),
87 token_url: "https://id.twitch.tv/oauth2/token".into(),
88 user_info_url: None,
89 scopes: vec!["user:read:email".into(), "openid".into()],
90 authorization: None,
91 authorization_params: Vec::new(),
92 account_subject: Some(subject),
93 map_user_info: None,
94 get_user_info: None,
95 refresh_access_token: None,
96 verify_id_token: None,
97 id_token: None,
98 disable_id_token_sign_in: false,
99 disable_implicit_sign_up: false,
100 disable_sign_up: false,
101 allow_idp_initiated: false,
102 override_user_info_on_sign_in: false,
103 };
104 provider.auth_url = options
105 .authorization_endpoint
106 .filter(|v| !v.is_empty())
107 .unwrap_or(provider.auth_url);
108 provider.user_info_url = options.user_info_endpoint.or(provider.user_info_url);
109 let mut claims = Vec::new();
110 for claim in ["email", "email_verified"]
111 .into_iter()
112 .map(str::to_owned)
113 .chain(options.claims.unwrap_or_else(|| {
114 vec![
115 "email".into(),
116 "email_verified".into(),
117 "preferred_username".into(),
118 "picture".into(),
119 ]
120 }))
121 {
122 if claim != "__proto__" && !claims.iter().any(|(key, _)| key == &claim) {
124 claims.push((claim, alibi_core::utils::json::JsValue::Null));
125 }
126 }
127 #[expect(
129 clippy::expect_used,
130 reason = "Claim keys and null values cannot fail JSON serialization"
131 )]
132 let serialized_claims =
133 alibi_core::utils::json::to_string(&alibi_core::utils::json::JsValue::Object(
134 [(
135 "id_token".into(),
136 alibi_core::utils::json::JsValue::Object(claims.into_iter().collect()),
137 )]
138 .into_iter()
139 .collect(),
140 ))
141 .expect("Twitch claim names and null values are JSON serializable");
142 provider
143 .authorization_params
144 .push(("claims".into(), serialized_claims));
145 policy.propagate_grant_profile_errors = true;
146 provider.authorization = Some(policy);
147 provider.get_user_info = Some(std::sync::Arc::new(PublishedProfile {
148 kind: ProfileKind::Twitch,
149 endpoint: provider.user_info_url.clone(),
150 email_endpoint: None,
151 client_id: provider.client_id.clone(),
152 mapper: options.map_profile_to_user,
153 application_mapper: None,
154 }));
155 provider
156 }
157}
158fn subject(profile: &Value) -> Result<String, String> {
159 super::remaining_profile::subject(ProfileKind::Twitch, profile)
160}