Skip to main content

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