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