Skip to main content

alibi_api/plugins/oauth/providers/
naver.rs

1//! Naver's resultcode gate and original envelope account authority.
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 Naver configuration. Generic signup and asynchronous
10/// user-info/refresh callbacks remain configurable on the returned provider.
11#[derive(Clone)]
12pub struct NaverOptions {
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 Naver'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 NaverOptions {
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 NaverOptions {
43    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        formatter
45            .debug_struct("NaverOptions")
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 naver(client_id: &str, client_secret: Option<&str>) -> Self {
57        Self::naver_with_options(NaverOptions::new(
58            client_id,
59            client_secret.map(str::to_owned),
60        ))
61    }
62    #[must_use]
63    pub fn naver_with_options(options: NaverOptions) -> 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://openapi.naver.com/v1/nid/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://nid.naver.com/oauth2.0/authorize".into()),
83            token_url: "https://nid.naver.com/oauth2.0/token".into(),
84            user_info_url: Some(endpoint.clone()),
85            scopes: ["profile", "email"].map(String::from).to_vec(),
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                pkce: 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(NaverUserInfo {
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            override_user_info_on_sign_in: false,
111        }
112    }
113}
114struct NaverUserInfo {
115    endpoint: String,
116    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
117}
118#[async_trait]
119impl OAuthUserInfoHandler for NaverUserInfo {
120    async fn get_user_info(
121        &self,
122        request: OAuthUserInfoRequest,
123    ) -> Result<OAuthUserInfoResponse, String> {
124        let access_token = request.access_token.ok_or("Missing Naver access token")?;
125        let response: Value = reqwest::Client::new()
126            .get(&self.endpoint)
127            .bearer_auth(access_token)
128            .send()
129            .await
130            .map_err(|error| error.to_string())?
131            .error_for_status()
132            .map_err(|error| error.to_string())?
133            .json()
134            .await
135            .map_err(|error| error.to_string())?;
136        let profile = response;
137        if profile.get("resultcode").and_then(Value::as_str) != Some("00") {
138            return Err("Invalid Naver resultcode".into());
139        }
140        let account = profile.get("response");
141        let mapped = self
142            .mapper
143            .map(|mapper| mapper(profile.clone()))
144            .transpose()?;
145        // Keep Source's original JSON publication separate from typed persistence.
146        let mut output = alibi_core::field_policy::FieldOutput::new();
147        let name = account
148            .and_then(|value| value.get("name"))
149            .filter(|value| truthy(value))
150            .or_else(|| {
151                account
152                    .and_then(|value| value.get("nickname"))
153                    .filter(|value| truthy(value))
154            })
155            .cloned()
156            .unwrap_or_else(|| Value::String(String::new()));
157        drop(output.insert("name".into(), name));
158        drop(output.insert("emailVerified".into(), Value::Bool(false)));
159        for (public, remote) in [("email", "email"), ("image", "profile_image")] {
160            if let Some(value) = account.and_then(|value| value.get(remote)) {
161                drop(output.insert(public.into(), value.clone()));
162            }
163        }
164        if let Some(user) = &mapped {
165            output.extend(user.public_profile(true));
166            output.extend(user.additional_fields.clone());
167        }
168        let user = match mapped {
169            Some(user) => user,
170            None => OAuthUserInfo {
171                additional_fields: Default::default(),
172                id: scalar(account.and_then(|value| value.get("id")))?.unwrap_or_default(),
173                name: Some(
174                    scalar(
175                        account
176                            .and_then(|value| value.get("name"))
177                            .filter(|value| truthy(value))
178                            .or_else(|| {
179                                account
180                                    .and_then(|value| value.get("nickname"))
181                                    .filter(|value| truthy(value))
182                            }),
183                    )?
184                    .unwrap_or_default(),
185                ),
186                email: account
187                    .and_then(|value| value.get("email"))
188                    .and_then(Value::as_str)
189                    .unwrap_or_default()
190                    .into(),
191                image: scalar(account.and_then(|value| value.get("profile_image")))?,
192                email_verified: false,
193            },
194        };
195        Ok(OAuthUserInfoResponse {
196            user_output: Some(output),
197            user,
198            data: profile,
199        })
200    }
201}
202fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
203    match value {
204        None | Some(Value::Null) => Ok(None),
205        Some(Value::String(value)) => Ok(Some(value.clone())),
206        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
207            .map(Some)
208            .map_err(|error| error.to_string()),
209        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
210        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Naver profile field".into()),
211    }
212}
213fn subject(profile: &Value) -> Result<String, String> {
214    let id = scalar(profile.get("response").and_then(|value| value.get("id")))?
215        .ok_or("Missing Naver subject")?;
216    if id
217        .trim_matches(|character: char| {
218            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
219        })
220        .is_empty()
221        || id == "null"
222        || id == "undefined"
223    {
224        return Err("Invalid Naver subject".into());
225    }
226    Ok(id)
227}
228
229fn truthy(value: &Value) -> bool {
230    match value {
231        Value::Null | Value::Bool(false) => false,
232        Value::Number(value) => value.as_f64() != Some(0.0),
233        Value::String(value) => !value.is_empty(),
234        Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
235    }
236}