Skip to main content

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