Skip to main content

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