alibi_plugins/oauth/providers/
kick.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4 OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Map;
8use serde_json::Value;
9
10#[derive(Clone)]
13pub struct KickOptions {
14 pub client_id: String,
15 pub client_secret: Option<String>,
16 pub client_key: Option<String>,
18 pub scope: Vec<String>,
19 pub disable_default_scope: bool,
20 pub authorization_endpoint: Option<String>,
21 pub redirect_uri: Option<String>,
22 pub user_info_endpoint: Option<String>,
24 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
26}
27impl KickOptions {
28 #[must_use]
29 pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
30 Self {
31 client_id: client_id.into(),
32 client_secret,
33 client_key: None,
34 scope: Vec::new(),
35 disable_default_scope: false,
36 authorization_endpoint: None,
37 redirect_uri: None,
38 user_info_endpoint: None,
39 map_profile_to_user: None,
40 }
41 }
42}
43impl std::fmt::Debug for KickOptions {
44 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 formatter
46 .debug_struct("KickOptions")
47 .field("client_id", &self.client_id)
48 .field("scope", &self.scope)
49 .field("disable_default_scope", &self.disable_default_scope)
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 kick(client_id: &str, client_secret: Option<&str>) -> Self {
58 Self::kick_with_options(KickOptions::new(
59 client_id,
60 client_secret.map(str::to_owned),
61 ))
62 }
63 #[must_use]
64 pub fn kick_with_options(options: KickOptions) -> Self {
65 let secret = options.client_secret.unwrap_or_default();
66 let authentication = if secret.is_empty() {
67 OAuthTokenEndpointAuth::None
68 } else {
69 OAuthTokenEndpointAuth::ClientSecretPost
70 };
71 let endpoint = options
72 .user_info_endpoint
73 .unwrap_or_else(|| "https://api.kick.com/public/v1/users".into());
74 Self {
75 client_id: options.client_id,
76 client_secret: secret,
77 additional_client_ids: Vec::new(),
78 hosted_domain: None,
79 require_email_verification: false,
80 auth_url: options
81 .authorization_endpoint
82 .filter(|value| !value.is_empty())
83 .unwrap_or_else(|| "https://id.kick.com/oauth/authorize".into()),
84 token_url: "https://id.kick.com/oauth/token".into(),
85 user_info_url: Some(endpoint.clone()),
86 scopes: vec!["user:read".into()],
87 authorization: Some(OAuthAuthorizationPolicy {
88 configured_scopes: options.scope,
89 disable_default_scopes: options.disable_default_scope,
90 require_client_id: true,
91 token_endpoint_auth: Some(authentication),
92 authorization_code_client_key: options.client_key,
93 redirect_uri: options.redirect_uri,
94 login_hint: false,
95 ..OAuthAuthorizationPolicy::default()
96 }),
97 authorization_params: Vec::new(),
98 account_subject: Some(subject),
99 map_user_info: None,
100 get_user_info: Some(std::sync::Arc::new(KickUserInfo {
101 endpoint,
102 mapper: options.map_profile_to_user,
103 })),
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 }
114}
115struct KickUserInfo {
116 endpoint: String,
117 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
118}
119#[async_trait]
120impl OAuthUserInfoHandler for KickUserInfo {
121 async fn get_user_info(
122 &self,
123 request: OAuthUserInfoRequest,
124 ) -> Result<OAuthUserInfoResponse, String> {
125 let access_token = request.access_token.ok_or("Missing Kick access token")?;
126 let response: Value = reqwest::Client::new()
127 .get(&self.endpoint)
128 .bearer_auth(access_token)
129 .send()
130 .await
131 .map_err(|error| error.to_string())?
132 .error_for_status()
133 .map_err(|error| error.to_string())?
134 .json()
135 .await
136 .map_err(|error| error.to_string())?;
137 let profile = response
138 .get("data")
139 .and_then(Value::as_array)
140 .and_then(|rows| rows.first())
141 .cloned()
142 .ok_or("Missing Kick profile")?;
143 let mapped = self
144 .mapper
145 .map(|mapper| mapper(profile.clone()))
146 .transpose()?;
147 let user_output = mapped.as_ref().map(|user| user.public_profile(true));
148 let user = match mapped {
149 Some(user) => user,
150 None => OAuthUserInfo {
151 additional_fields: Map::default(),
152 id: scalar(profile.get("user_id"))?.unwrap_or_default(),
153 name: scalar(profile.get("name"))?,
154 email: profile
155 .get("email")
156 .and_then(Value::as_str)
157 .unwrap_or_default()
158 .into(),
159 image: scalar(profile.get("profile_picture"))?,
160 email_verified: false,
161 },
162 };
163 Ok(OAuthUserInfoResponse {
164 user_output,
165 user,
166 data: profile,
167 })
168 }
169}
170fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
171 match value {
172 None | Some(Value::Null) => Ok(None),
173 Some(Value::String(value)) => Ok(Some(value.clone())),
174 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
175 .map(Some)
176 .map_err(|error| error.to_string()),
177 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
178 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Kick profile field".into()),
179 }
180}
181fn subject(profile: &Value) -> Result<String, String> {
182 let id = scalar(profile.get("user_id"))?.ok_or("Missing Kick user_id")?;
183 if id
184 .trim_matches(|character: char| {
185 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
186 })
187 .is_empty()
188 || id == "null"
189 || id == "undefined"
190 {
191 return Err("Invalid Kick user_id".into());
192 }
193 Ok(id)
194}