Skip to main content

alibi_plugins/oauth/providers/
kakao.rs

1//! Kakao's ordered scopes, nested profile mapping and raw account identity.
2use 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/// Application-owned Kakao configuration. Generic signup and asynchronous
11/// user-info/refresh callbacks remain configurable on the returned provider.
12#[derive(Clone)]
13pub struct KakaoOptions {
14    pub client_id: String,
15    pub client_secret: Option<String>,
16    /// Sent only during authorization-code exchange.
17    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    /// Trusted transport override retaining Kakao's actual GET and mapping.
23    pub user_info_endpoint: Option<String>,
24    /// Receives the original profile before its raw account identity is resolved.
25    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            authorization_params: Vec::new(),
103            account_subject: Some(subject),
104            map_user_info: None,
105            get_user_info: Some(std::sync::Arc::new(KakaoUserInfo {
106                endpoint,
107                mapper: options.map_profile_to_user,
108            })),
109            refresh_access_token: None,
110            verify_id_token: None,
111            id_token: None,
112            disable_id_token_sign_in: false,
113            disable_implicit_sign_up: false,
114            disable_sign_up: false,
115            allow_idp_initiated: false,
116            override_user_info_on_sign_in: false,
117        }
118    }
119}
120struct KakaoUserInfo {
121    endpoint: String,
122    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
123}
124#[async_trait]
125impl OAuthUserInfoHandler for KakaoUserInfo {
126    async fn get_user_info(
127        &self,
128        request: OAuthUserInfoRequest,
129    ) -> Result<OAuthUserInfoResponse, String> {
130        let access_token = request.access_token.ok_or("Missing Kakao access token")?;
131        let profile: Value = reqwest::Client::new()
132            .get(&self.endpoint)
133            .bearer_auth(access_token)
134            .send()
135            .await
136            .map_err(|error| error.to_string())?
137            .error_for_status()
138            .map_err(|error| error.to_string())?
139            .json()
140            .await
141            .map_err(|error| error.to_string())?;
142        let account = profile.get("kakao_account").filter(|value| truthy(value));
143        let kakao_profile = account
144            .and_then(|value| value.get("profile"))
145            .filter(|value| truthy(value));
146        let mapped = self
147            .mapper
148            .map(|mapper| mapper(profile.clone()))
149            .transpose()?;
150        let user_output = mapped.as_ref().map(|user| user.public_profile(true));
151        let user = match mapped {
152            Some(user) => user,
153            None => OAuthUserInfo {
154                additional_fields: Map::default(),
155                id: scalar(profile.get("id"))?.unwrap_or_default(),
156                name: Some(
157                    scalar(
158                        kakao_profile
159                            .and_then(|value| value.get("nickname"))
160                            .filter(|value| truthy(value))
161                            .or_else(|| {
162                                account
163                                    .and_then(|value| value.get("name"))
164                                    .filter(|value| truthy(value))
165                            }),
166                    )?
167                    .unwrap_or_default(),
168                ),
169                email: account
170                    .and_then(|value| value.get("email"))
171                    .and_then(Value::as_str)
172                    .unwrap_or_default()
173                    .into(),
174                image: scalar(
175                    kakao_profile
176                        .and_then(|value| value.get("profile_image_url"))
177                        .filter(|value| truthy(value))
178                        .or_else(|| {
179                            kakao_profile.and_then(|value| value.get("thumbnail_image_url"))
180                        }),
181                )?,
182                email_verified: account
183                    .and_then(|value| value.get("is_email_valid"))
184                    .is_some_and(truthy)
185                    && account
186                        .and_then(|value| value.get("is_email_verified"))
187                        .is_some_and(truthy),
188            },
189        };
190        Ok(OAuthUserInfoResponse {
191            user_output,
192            user,
193            data: profile,
194        })
195    }
196}
197fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
198    match value {
199        None | Some(Value::Null) => Ok(None),
200        Some(Value::String(value)) => Ok(Some(value.clone())),
201        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
202            .map(Some)
203            .map_err(|error| error.to_string()),
204        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
205        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Kakao profile field".into()),
206    }
207}
208fn subject(profile: &Value) -> Result<String, String> {
209    let id = scalar(profile.get("id"))?.ok_or("Missing Kakao id")?;
210    if id
211        .trim_matches(|character: char| {
212            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
213        })
214        .is_empty()
215        || id == "null"
216        || id == "undefined"
217    {
218        return Err("Invalid Kakao id".into());
219    }
220    Ok(id)
221}
222
223fn truthy(value: &Value) -> bool {
224    match value {
225        Value::Null => false,
226        Value::Bool(value) => *value,
227        Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
228        Value::String(value) => !value.is_empty(),
229        Value::Array(_) | Value::Object(_) => true,
230    }
231}