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            authorization_params: Vec::new(),
99            account_subject: Some(subject),
100            map_user_info: None,
101            get_user_info: Some(std::sync::Arc::new(NaverUserInfo {
102                endpoint,
103                mapper: options.map_profile_to_user,
104            })),
105            refresh_access_token: None,
106            verify_id_token: None,
107            id_token: None,
108            disable_id_token_sign_in: false,
109            disable_implicit_sign_up: false,
110            disable_sign_up: false,
111            allow_idp_initiated: false,
112            override_user_info_on_sign_in: false,
113        }
114    }
115}
116struct NaverUserInfo {
117    endpoint: String,
118    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
119}
120#[async_trait]
121impl OAuthUserInfoHandler for NaverUserInfo {
122    async fn get_user_info(
123        &self,
124        request: OAuthUserInfoRequest,
125    ) -> Result<OAuthUserInfoResponse, String> {
126        let access_token = request.access_token.ok_or("Missing Naver access token")?;
127        let response: Value = reqwest::Client::new()
128            .get(&self.endpoint)
129            .bearer_auth(access_token)
130            .send()
131            .await
132            .map_err(|error| error.to_string())?
133            .error_for_status()
134            .map_err(|error| error.to_string())?
135            .json()
136            .await
137            .map_err(|error| error.to_string())?;
138        let profile = response;
139        if profile.get("resultcode").and_then(Value::as_str) != Some("00") {
140            return Err("Invalid Naver resultcode".into());
141        }
142        let account = profile.get("response");
143        let mapped = self
144            .mapper
145            .map(|mapper| mapper(profile.clone()))
146            .transpose()?;
147        // Keep Source's original JSON publication separate from typed persistence.
148        let mut output = alibi_core::field_policy::FieldOutput::new();
149        let name = account
150            .and_then(|value| value.get("name"))
151            .filter(|value| truthy(value))
152            .or_else(|| {
153                account
154                    .and_then(|value| value.get("nickname"))
155                    .filter(|value| truthy(value))
156            })
157            .cloned()
158            .unwrap_or_else(|| Value::String(String::new()));
159        _ = output.insert("name".into(), name);
160        _ = output.insert("emailVerified".into(), Value::Bool(false));
161        for (public, remote) in [("email", "email"), ("image", "profile_image")] {
162            if let Some(value) = account.and_then(|value| value.get(remote)) {
163                _ = output.insert(public.into(), value.clone());
164            }
165        }
166        if let Some(user) = &mapped {
167            output.extend(user.public_profile(true));
168            output.extend(user.additional_fields.clone());
169        }
170        let user = match mapped {
171            Some(user) => user,
172            None => OAuthUserInfo {
173                additional_fields: Map::default(),
174                id: scalar(account.and_then(|value| value.get("id")))?.unwrap_or_default(),
175                name: Some(
176                    scalar(
177                        account
178                            .and_then(|value| value.get("name"))
179                            .filter(|value| truthy(value))
180                            .or_else(|| {
181                                account
182                                    .and_then(|value| value.get("nickname"))
183                                    .filter(|value| truthy(value))
184                            }),
185                    )?
186                    .unwrap_or_default(),
187                ),
188                email: account
189                    .and_then(|value| value.get("email"))
190                    .and_then(Value::as_str)
191                    .unwrap_or_default()
192                    .into(),
193                image: scalar(account.and_then(|value| value.get("profile_image")))?,
194                email_verified: false,
195            },
196        };
197        Ok(OAuthUserInfoResponse {
198            user_output: Some(output),
199            user,
200            data: profile,
201        })
202    }
203}
204fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
205    match value {
206        None | Some(Value::Null) => Ok(None),
207        Some(Value::String(value)) => Ok(Some(value.clone())),
208        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
209            .map(Some)
210            .map_err(|error| error.to_string()),
211        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
212        Some(Value::Array(_) | Value::Object(_)) => Err("Invalid Naver profile field".into()),
213    }
214}
215fn subject(profile: &Value) -> Result<String, String> {
216    let id = scalar(profile.get("response").and_then(|value| value.get("id")))?
217        .ok_or("Missing Naver subject")?;
218    if id
219        .trim_matches(|character: char| {
220            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
221        })
222        .is_empty()
223        || id == "null"
224        || id == "undefined"
225    {
226        return Err("Invalid Naver subject".into());
227    }
228    Ok(id)
229}
230
231fn truthy(value: &Value) -> bool {
232    match value {
233        Value::Null | Value::Bool(false) => false,
234        Value::Number(value) => value.as_f64() != Some(0.0),
235        Value::String(value) => !value.is_empty(),
236        Value::Array(_) | Value::Object(_) | Value::Bool(true) => true,
237    }
238}