alibi_plugins/oauth/providers/
kakao.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 KakaoOptions {
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 KakaoOptions {
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 KakaoOptions {
44 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 formatter
46 .debug_struct("KakaoOptions")
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 kakao(client_id: &str, client_secret: Option<&str>) -> Self {
58 Self::kakao_with_options(KakaoOptions::new(
59 client_id,
60 client_secret.map(str::to_owned),
61 ))
62 }
63 #[must_use]
64 pub fn kakao_with_options(options: KakaoOptions) -> 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://kapi.kakao.com/v2/user/me".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://kauth.kakao.com/oauth/authorize".into()),
84 token_url: "https://kauth.kakao.com/oauth/token".into(),
85 user_info_url: Some(endpoint.clone()),
86 scopes: vec![
87 "account_email".into(),
88 "profile_image".into(),
89 "profile_nickname".into(),
90 ],
91 authorization: Some(OAuthAuthorizationPolicy {
92 configured_scopes: options.scope,
93 disable_default_scopes: options.disable_default_scope,
94 require_client_id: true,
95 token_endpoint_auth: Some(authentication),
96 authorization_code_client_key: options.client_key,
97 redirect_uri: options.redirect_uri,
98 login_hint: false,
99 pkce: false,
100 ..OAuthAuthorizationPolicy::default()
101 }),
102 allowed_request_params: Vec::new(),
103 authorization_params: Vec::new(),
104 account_subject: Some(subject),
105 map_user_info: None,
106 get_user_info: Some(std::sync::Arc::new(KakaoUserInfo {
107 endpoint,
108 mapper: options.map_profile_to_user,
109 })),
110 refresh_access_token: None,
111 verify_id_token: None,
112 id_token: None,
113 disable_id_token_sign_in: false,
114 disable_implicit_sign_up: false,
115 disable_sign_up: false,
116 allow_idp_initiated: false,
117 override_user_info_on_sign_in: false,
118 }
119 }
120}
121struct KakaoUserInfo {
122 endpoint: String,
123 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
124}
125#[async_trait]
126impl OAuthUserInfoHandler for KakaoUserInfo {
127 async fn get_user_info(
128 &self,
129 request: OAuthUserInfoRequest,
130 ) -> Result<OAuthUserInfoResponse, String> {
131 let access_token = request.access_token.ok_or("Missing Kakao access token")?;
132 let profile: Value = reqwest::Client::new()
133 .get(&self.endpoint)
134 .bearer_auth(access_token)
135 .send()
136 .await
137 .map_err(|error| error.to_string())?
138 .error_for_status()
139 .map_err(|error| error.to_string())?
140 .json()
141 .await
142 .map_err(|error| error.to_string())?;
143 let account = profile.get("kakao_account").filter(|value| truthy(value));
144 let kakao_profile = account
145 .and_then(|value| value.get("profile"))
146 .filter(|value| truthy(value));
147 let mapped = self
148 .mapper
149 .map(|mapper| mapper(profile.clone()))
150 .transpose()?;
151 let user_output = mapped.as_ref().map(|user| user.public_profile(true));
152 let user = match mapped {
153 Some(user) => user,
154 None => OAuthUserInfo {
155 additional_fields: Map::default(),
156 id: scalar(profile.get("id"))?.unwrap_or_default(),
157 name: Some(
158 scalar(
159 kakao_profile
160 .and_then(|value| value.get("nickname"))
161 .filter(|value| truthy(value))
162 .or_else(|| {
163 account
164 .and_then(|value| value.get("name"))
165 .filter(|value| truthy(value))
166 }),
167 )?
168 .unwrap_or_default(),
169 ),
170 email: account
171 .and_then(|value| value.get("email"))
172 .and_then(Value::as_str)
173 .unwrap_or_default()
174 .into(),
175 image: scalar(
176 kakao_profile
177 .and_then(|value| value.get("profile_image_url"))
178 .filter(|value| truthy(value))
179 .or_else(|| {
180 kakao_profile.and_then(|value| value.get("thumbnail_image_url"))
181 }),
182 )?,
183 email_verified: account
184 .and_then(|value| value.get("is_email_valid"))
185 .is_some_and(truthy)
186 && account
187 .and_then(|value| value.get("is_email_verified"))
188 .is_some_and(truthy),
189 },
190 };
191 Ok(OAuthUserInfoResponse {
192 user_output,
193 user,
194 data: profile,
195 })
196 }
197}
198fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
199 match value {
200 None | Some(Value::Null) => Ok(None),
201 Some(Value::String(value)) => Ok(Some(value.clone())),
202 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
203 .map(Some)
204 .map_err(|error| error.to_string()),
205 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
206 Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Kakao profile field".into()),
207 }
208}
209fn subject(profile: &Value) -> Result<String, String> {
210 let id = scalar(profile.get("id"))?.ok_or("Missing Kakao id")?;
211 if id
212 .trim_matches(|character: char| {
213 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
214 })
215 .is_empty()
216 || id == "null"
217 || id == "undefined"
218 {
219 return Err("Invalid Kakao id".into());
220 }
221 Ok(id)
222}
223
224fn truthy(value: &Value) -> bool {
225 match value {
226 Value::Null => false,
227 Value::Bool(value) => *value,
228 Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
229 Value::String(value) => !value.is_empty(),
230 Value::Array(_) | Value::Object(_) => true,
231 }
232}