Skip to main content

alibi_plugins/oauth/providers/
wechat.rs

1//! `WeChat` website-app grants use GET and carry openid into userinfo.
2use super::{
3    OAuthAuthorizationCodeCallback, OAuthAuthorizationCodeContext, OAuthAuthorizationCodeHandler,
4    OAuthAuthorizationPolicy, OAuthProvider, OAuthRefreshTokenHandler, OAuthTokenSet,
5    OAuthUserInfo, OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
6};
7use serde_json::Map;
8use serde_json::Value;
9use std::sync::Arc;
10
11#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
12pub enum WeChatLanguage {
13    #[default]
14    Chinese,
15    English,
16}
17#[derive(Clone)]
18pub struct WeChatOptions {
19    pub client_id: String,
20    pub client_secret: String,
21    pub scope: Vec<String>,
22    pub disable_default_scope: bool,
23    pub redirect_uri: Option<String>,
24    pub language: WeChatLanguage,
25    /// Trusted transport overrides retaining `WeChat` GET/query contracts.
26    pub token_endpoint: Option<String>,
27    pub refresh_endpoint: Option<String>,
28    pub user_info_endpoint: Option<String>,
29    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
30}
31impl WeChatOptions {
32    #[must_use]
33    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
34        Self {
35            client_id: client_id.into(),
36            client_secret: client_secret.into(),
37            scope: Vec::new(),
38            disable_default_scope: false,
39            redirect_uri: None,
40            language: WeChatLanguage::Chinese,
41            token_endpoint: None,
42            refresh_endpoint: None,
43            user_info_endpoint: None,
44            map_profile_to_user: None,
45        }
46    }
47}
48impl std::fmt::Debug for WeChatOptions {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.debug_struct("WeChatOptions")
51            .field("client_id", &self.client_id)
52            .field("language", &self.language)
53            .finish_non_exhaustive()
54    }
55}
56impl OAuthProvider {
57    #[must_use]
58    pub fn wechat(client_id: &str, client_secret: &str) -> Self {
59        Self::wechat_with_options(WeChatOptions::new(client_id, client_secret))
60    }
61    #[must_use]
62    pub fn wechat_with_options(options: WeChatOptions) -> Self {
63        let token_endpoint = options
64            .token_endpoint
65            .unwrap_or_else(|| "https://api.weixin.qq.com/sns/oauth2/access_token".into());
66        let refresh_endpoint = options
67            .refresh_endpoint
68            .unwrap_or_else(|| "https://api.weixin.qq.com/sns/oauth2/refresh_token".into());
69        let endpoint = options
70            .user_info_endpoint
71            .unwrap_or_else(|| "https://api.weixin.qq.com/sns/userinfo".into());
72        let grants = Arc::new(WeChatGrants {
73            client_id: options.client_id.clone(),
74            client_secret: options.client_secret.clone(),
75            token_endpoint: token_endpoint.clone(),
76            refresh_endpoint,
77        });
78        Self {
79            client_id: options.client_id,
80            client_secret: options.client_secret,
81            additional_client_ids: Vec::new(),
82            hosted_domain: None,
83            require_email_verification: false,
84            auth_url: "https://open.weixin.qq.com/connect/qrconnect".into(),
85            token_url: token_endpoint,
86            user_info_url: Some(endpoint.clone()),
87            scopes: vec!["snsapi_login".into()],
88            authorization: Some(OAuthAuthorizationPolicy {
89                preserve_raw_profile_scalars: true,
90                source_profile_exceptions: true,
91                authorization_code: Some(OAuthAuthorizationCodeCallback(grants.clone())),
92                client_id_parameter: "appid".into(),
93                token_expiry_always: true,
94                token_response_omits_id_token: true,
95                scope_separator: ",".into(),
96                emit_empty_scope: true,
97                authorization_fragment: Some("wechat_redirect".into()),
98                configured_scopes: options.scope,
99                disable_default_scopes: options.disable_default_scope,
100                redirect_uri: options.redirect_uri,
101                pkce: false,
102                login_hint: false,
103                preserve_raw_email_errors: true,
104                ..OAuthAuthorizationPolicy::default()
105            }),
106            allowed_request_params: Vec::new(),
107            authorization_params: vec![(
108                "lang".into(),
109                match options.language {
110                    WeChatLanguage::Chinese => "cn",
111                    WeChatLanguage::English => "en",
112                }
113                .into(),
114            )],
115            account_subject: Some(subject),
116            map_user_info: None,
117            get_user_info: Some(Arc::new(WeChatProfile {
118                application_mapper: None,
119                endpoint,
120                mapper: options.map_profile_to_user,
121            })),
122            refresh_access_token: Some(grants),
123            verify_id_token: None,
124            id_token: None,
125            disable_id_token_sign_in: false,
126            disable_implicit_sign_up: false,
127            disable_sign_up: false,
128            allow_idp_initiated: false,
129            override_user_info_on_sign_in: false,
130        }
131    }
132}
133#[derive(Clone)]
134struct WeChatGrants {
135    client_id: String,
136    client_secret: String,
137    token_endpoint: String,
138    refresh_endpoint: String,
139}
140async fn token_request(endpoint: &str, query: &[(&str, &str)]) -> Result<OAuthTokenSet, String> {
141    let raw: Value = reqwest::Client::new()
142        .get(endpoint)
143        .query(query)
144        .send()
145        .await
146        .map_err(|e| e.to_string())?
147        .error_for_status()
148        .map_err(|e| e.to_string())?
149        .json()
150        .await
151        .map_err(|e| e.to_string())?;
152    if !super::remaining_profile::truthy(&raw)
153        || raw
154            .get("errcode")
155            .is_some_and(super::remaining_profile::truthy)
156    {
157        return Err("WeChat token request failed".into());
158    }
159    let scope = raw
160        .get("scope")
161        .and_then(Value::as_str)
162        .ok_or("Missing WeChat token scope")?;
163    let expiry = raw
164        .get("expires_in")
165        .and_then(|value| super::remaining_profile::grant_expiry(value, false));
166    Ok(OAuthTokenSet {
167        token_type: Some("Bearer".into()),
168        access_token: raw
169            .get("access_token")
170            .and_then(Value::as_str)
171            .map(str::to_owned),
172        refresh_token: raw
173            .get("refresh_token")
174            .and_then(Value::as_str)
175            .map(str::to_owned),
176        access_token_expires_at: expiry,
177        refresh_token_expires_at: None,
178        scopes: scope.split(',').map(str::to_owned).collect(),
179        id_token: None,
180        raw: Some(raw),
181    })
182}
183#[async_trait::async_trait]
184impl OAuthAuthorizationCodeHandler for WeChatGrants {
185    fn configured_client_ids(
186        &self,
187        ids: &[String],
188    ) -> Option<Arc<dyn OAuthAuthorizationCodeHandler>> {
189        let mut handler = self.clone();
190        handler.client_id = ids.join(",");
191        Some(Arc::new(handler))
192    }
193    async fn validate_authorization_code(
194        &self,
195        context: OAuthAuthorizationCodeContext,
196    ) -> Result<OAuthTokenSet, String> {
197        token_request(
198            &self.token_endpoint,
199            &[
200                ("appid", &self.client_id),
201                ("secret", &self.client_secret),
202                ("code", &context.code),
203                ("grant_type", "authorization_code"),
204            ],
205        )
206        .await
207    }
208}
209#[async_trait::async_trait]
210impl OAuthRefreshTokenHandler for WeChatGrants {
211    fn configured_client_ids(&self, ids: &[String]) -> Option<Arc<dyn OAuthRefreshTokenHandler>> {
212        let mut handler = self.clone();
213        handler.client_id = ids.join(",");
214        Some(Arc::new(handler))
215    }
216    async fn refresh_access_token(&self, refresh_token: &str) -> Result<OAuthTokenSet, String> {
217        token_request(
218            &self.refresh_endpoint,
219            &[
220                ("appid", &self.client_id),
221                ("grant_type", "refresh_token"),
222                ("refresh_token", refresh_token),
223            ],
224        )
225        .await
226    }
227}
228#[derive(Clone)]
229struct WeChatProfile {
230    application_mapper: Option<Arc<dyn super::OAuthProfileMapper>>,
231    endpoint: String,
232    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
233}
234#[async_trait::async_trait]
235impl OAuthUserInfoHandler for WeChatProfile {
236    fn errors_are_exceptions(&self) -> bool {
237        false
238    }
239
240    fn mapped_handler(
241        &self,
242        mapper: Arc<dyn super::OAuthProfileMapper>,
243    ) -> Option<Arc<dyn OAuthUserInfoHandler>> {
244        let mut handler = self.clone();
245        handler.mapper = None;
246        handler.application_mapper = Some(mapper);
247        Some(Arc::new(handler))
248    }
249
250    async fn get_user_info(
251        &self,
252        request: OAuthUserInfoRequest,
253    ) -> Result<OAuthUserInfoResponse, String> {
254        let openid = request
255            .raw
256            .as_ref()
257            .and_then(|raw| raw.get("openid"))
258            .filter(|value| super::remaining_profile::truthy(value))
259            .ok_or("Missing WeChat token openid")?;
260        let openid = super::remaining_profile::js_string(openid)
261            .map_err(super::remaining_profile::profile_exception)?;
262        let access_token = if super::remaining_profile::has_access_token(&request) {
263            super::remaining_profile::bearer_access_token(&request)
264                .map_err(super::remaining_profile::profile_exception)?
265        } else {
266            String::new()
267        };
268        let profile: Value = reqwest::Client::new()
269            .get(&self.endpoint)
270            .query(&[
271                ("access_token", access_token.as_str()),
272                ("openid", openid.as_str()),
273                ("lang", "zh_CN"),
274            ])
275            .send()
276            .await
277            .map_err(|e| e.to_string())?
278            .error_for_status()
279            .map_err(|e| e.to_string())?
280            .json()
281            .await
282            .map_err(|e| e.to_string())?;
283        if !super::remaining_profile::truthy(&profile)
284            || profile
285                .get("errcode")
286                .is_some_and(super::remaining_profile::truthy)
287        {
288            return Err("Missing WeChat profile".into());
289        }
290        let application_output = if let Some(mapper) = &self.application_mapper {
291            Some(
292                mapper
293                    .map_profile(profile.clone())
294                    .await
295                    .map_err(super::remaining_profile::profile_exception)?,
296            )
297        } else {
298            None
299        };
300        let mapped = self
301            .mapper
302            .map(|mapper| mapper(profile.clone()))
303            .transpose()
304            .map_err(super::remaining_profile::profile_exception)?;
305        let raw_id = profile
306            .get("unionid")
307            .filter(|v| super::remaining_profile::truthy(v))
308            .or_else(|| {
309                profile
310                    .get("openid")
311                    .filter(|v| super::remaining_profile::truthy(v))
312            });
313        let id = raw_id
314            .map(super::remaining_profile::js_string)
315            .transpose()
316            .map_err(super::remaining_profile::profile_exception)?
317            .unwrap_or(openid);
318        let email = if let Some(value) = profile
319            .get("email")
320            .filter(|value| super::remaining_profile::truthy(value))
321        {
322            value.clone()
323        } else {
324            let email = format!("{id}@wechat.placeholder.invalid");
325            if !crate::authentication_helpers::is_valid_email(&email) {
326                return Err(super::remaining_profile::profile_exception(
327                    "Invalid WeChat placeholder email",
328                ));
329            }
330            Value::String(email)
331        };
332        let mut output = serde_json::Map::new();
333        for (key, field) in [("name", "nickname"), ("image", "headimgurl")] {
334            if let Some(value) = profile.get(field) {
335                _ = output.insert(key.into(), value.clone());
336            }
337        }
338        _ = output.insert("email".into(), email.clone());
339        _ = output.insert("emailVerified".into(), Value::Bool(false));
340        if let Some(user) = &mapped {
341            output.extend(user.public_profile(true));
342        }
343        let user = match mapped {
344            Some(user) => user,
345            None => OAuthUserInfo {
346                additional_fields: Map::default(),
347                id,
348                name: super::remaining_profile::scalar(
349                    profile
350                        .get("nickname")
351                        .filter(|v| super::remaining_profile::truthy(v)),
352                )?,
353                email: email.as_str().unwrap_or_default().into(),
354                image: super::remaining_profile::scalar(profile.get("headimgurl"))?,
355                email_verified: false,
356            },
357        };
358        let mut response = OAuthUserInfoResponse {
359            user_output: Some(output),
360            user,
361            data: profile,
362        };
363        if let Some(mapped) = application_output {
364            super::apply_application_mapping(&mut response, mapped)?;
365        }
366        Ok(response)
367    }
368}
369fn subject(profile: &Value) -> Result<String, String> {
370    let value = profile
371        .get("unionid")
372        .filter(|value| super::remaining_profile::truthy(value))
373        .or_else(|| profile.get("openid"));
374    super::remaining_profile::raw_subject(value)
375}