1use 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 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 authorization_params: vec![(
107 "lang".into(),
108 match options.language {
109 WeChatLanguage::Chinese => "cn",
110 WeChatLanguage::English => "en",
111 }
112 .into(),
113 )],
114 account_subject: Some(subject),
115 map_user_info: None,
116 get_user_info: Some(Arc::new(WeChatProfile {
117 application_mapper: None,
118 endpoint,
119 mapper: options.map_profile_to_user,
120 })),
121 refresh_access_token: Some(grants),
122 verify_id_token: None,
123 id_token: None,
124 disable_id_token_sign_in: false,
125 disable_implicit_sign_up: false,
126 disable_sign_up: false,
127 allow_idp_initiated: false,
128 override_user_info_on_sign_in: false,
129 }
130 }
131}
132#[derive(Clone)]
133struct WeChatGrants {
134 client_id: String,
135 client_secret: String,
136 token_endpoint: String,
137 refresh_endpoint: String,
138}
139async fn token_request(endpoint: &str, query: &[(&str, &str)]) -> Result<OAuthTokenSet, String> {
140 let raw: Value = reqwest::Client::new()
141 .get(endpoint)
142 .query(query)
143 .send()
144 .await
145 .map_err(|e| e.to_string())?
146 .error_for_status()
147 .map_err(|e| e.to_string())?
148 .json()
149 .await
150 .map_err(|e| e.to_string())?;
151 if !super::remaining_profile::truthy(&raw)
152 || raw
153 .get("errcode")
154 .is_some_and(super::remaining_profile::truthy)
155 {
156 return Err("WeChat token request failed".into());
157 }
158 let scope = raw
159 .get("scope")
160 .and_then(Value::as_str)
161 .ok_or("Missing WeChat token scope")?;
162 let expiry = raw
163 .get("expires_in")
164 .and_then(|value| super::remaining_profile::grant_expiry(value, false));
165 Ok(OAuthTokenSet {
166 token_type: Some("Bearer".into()),
167 access_token: raw
168 .get("access_token")
169 .and_then(Value::as_str)
170 .map(str::to_owned),
171 refresh_token: raw
172 .get("refresh_token")
173 .and_then(Value::as_str)
174 .map(str::to_owned),
175 access_token_expires_at: expiry,
176 refresh_token_expires_at: None,
177 scopes: scope.split(',').map(str::to_owned).collect(),
178 id_token: None,
179 raw: Some(raw),
180 })
181}
182#[async_trait::async_trait]
183impl OAuthAuthorizationCodeHandler for WeChatGrants {
184 fn configured_client_ids(
185 &self,
186 ids: &[String],
187 ) -> Option<Arc<dyn OAuthAuthorizationCodeHandler>> {
188 let mut handler = self.clone();
189 handler.client_id = ids.join(",");
190 Some(Arc::new(handler))
191 }
192 async fn validate_authorization_code(
193 &self,
194 context: OAuthAuthorizationCodeContext,
195 ) -> Result<OAuthTokenSet, String> {
196 token_request(
197 &self.token_endpoint,
198 &[
199 ("appid", &self.client_id),
200 ("secret", &self.client_secret),
201 ("code", &context.code),
202 ("grant_type", "authorization_code"),
203 ],
204 )
205 .await
206 }
207}
208#[async_trait::async_trait]
209impl OAuthRefreshTokenHandler for WeChatGrants {
210 fn configured_client_ids(&self, ids: &[String]) -> Option<Arc<dyn OAuthRefreshTokenHandler>> {
211 let mut handler = self.clone();
212 handler.client_id = ids.join(",");
213 Some(Arc::new(handler))
214 }
215 async fn refresh_access_token(&self, refresh_token: &str) -> Result<OAuthTokenSet, String> {
216 token_request(
217 &self.refresh_endpoint,
218 &[
219 ("appid", &self.client_id),
220 ("grant_type", "refresh_token"),
221 ("refresh_token", refresh_token),
222 ],
223 )
224 .await
225 }
226}
227#[derive(Clone)]
228struct WeChatProfile {
229 application_mapper: Option<Arc<dyn super::OAuthProfileMapper>>,
230 endpoint: String,
231 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
232}
233#[async_trait::async_trait]
234impl OAuthUserInfoHandler for WeChatProfile {
235 fn errors_are_exceptions(&self) -> bool {
236 false
237 }
238
239 fn mapped_handler(
240 &self,
241 mapper: Arc<dyn super::OAuthProfileMapper>,
242 ) -> Option<Arc<dyn OAuthUserInfoHandler>> {
243 let mut handler = self.clone();
244 handler.mapper = None;
245 handler.application_mapper = Some(mapper);
246 Some(Arc::new(handler))
247 }
248
249 async fn get_user_info(
250 &self,
251 request: OAuthUserInfoRequest,
252 ) -> Result<OAuthUserInfoResponse, String> {
253 let openid = request
254 .raw
255 .as_ref()
256 .and_then(|raw| raw.get("openid"))
257 .filter(|value| super::remaining_profile::truthy(value))
258 .ok_or("Missing WeChat token openid")?;
259 let openid = super::remaining_profile::js_string(openid)
260 .map_err(super::remaining_profile::profile_exception)?;
261 let access_token = if super::remaining_profile::has_access_token(&request) {
262 super::remaining_profile::bearer_access_token(&request)
263 .map_err(super::remaining_profile::profile_exception)?
264 } else {
265 String::new()
266 };
267 let profile: Value = reqwest::Client::new()
268 .get(&self.endpoint)
269 .query(&[
270 ("access_token", access_token.as_str()),
271 ("openid", openid.as_str()),
272 ("lang", "zh_CN"),
273 ])
274 .send()
275 .await
276 .map_err(|e| e.to_string())?
277 .error_for_status()
278 .map_err(|e| e.to_string())?
279 .json()
280 .await
281 .map_err(|e| e.to_string())?;
282 if !super::remaining_profile::truthy(&profile)
283 || profile
284 .get("errcode")
285 .is_some_and(super::remaining_profile::truthy)
286 {
287 return Err("Missing WeChat profile".into());
288 }
289 let application_output = if let Some(mapper) = &self.application_mapper {
290 Some(
291 mapper
292 .map_profile(profile.clone())
293 .await
294 .map_err(super::remaining_profile::profile_exception)?,
295 )
296 } else {
297 None
298 };
299 let mapped = self
300 .mapper
301 .map(|mapper| mapper(profile.clone()))
302 .transpose()
303 .map_err(super::remaining_profile::profile_exception)?;
304 let raw_id = profile
305 .get("unionid")
306 .filter(|v| super::remaining_profile::truthy(v))
307 .or_else(|| {
308 profile
309 .get("openid")
310 .filter(|v| super::remaining_profile::truthy(v))
311 });
312 let id = raw_id
313 .map(super::remaining_profile::js_string)
314 .transpose()
315 .map_err(super::remaining_profile::profile_exception)?
316 .unwrap_or(openid);
317 let email = if let Some(value) = profile
318 .get("email")
319 .filter(|value| super::remaining_profile::truthy(value))
320 {
321 value.clone()
322 } else {
323 let email = format!("{id}@wechat.placeholder.invalid");
324 if !crate::authentication_helpers::is_valid_email(&email) {
325 return Err(super::remaining_profile::profile_exception(
326 "Invalid WeChat placeholder email",
327 ));
328 }
329 Value::String(email)
330 };
331 let mut output = serde_json::Map::new();
332 for (key, field) in [("name", "nickname"), ("image", "headimgurl")] {
333 if let Some(value) = profile.get(field) {
334 _ = output.insert(key.into(), value.clone());
335 }
336 }
337 _ = output.insert("email".into(), email.clone());
338 _ = output.insert("emailVerified".into(), Value::Bool(false));
339 if let Some(user) = &mapped {
340 output.extend(user.public_profile(true));
341 }
342 let user = match mapped {
343 Some(user) => user,
344 None => OAuthUserInfo {
345 additional_fields: Map::default(),
346 id,
347 name: super::remaining_profile::scalar(
348 profile
349 .get("nickname")
350 .filter(|v| super::remaining_profile::truthy(v)),
351 )?,
352 email: email.as_str().unwrap_or_default().into(),
353 image: super::remaining_profile::scalar(profile.get("headimgurl"))?,
354 email_verified: false,
355 },
356 };
357 let mut response = OAuthUserInfoResponse {
358 user_output: Some(output),
359 user,
360 data: profile,
361 };
362 if let Some(mapped) = application_output {
363 super::apply_application_mapping(&mut response, mapped)?;
364 }
365 Ok(response)
366 }
367}
368fn subject(profile: &Value) -> Result<String, String> {
369 let value = profile
370 .get("unionid")
371 .filter(|value| super::remaining_profile::truthy(value))
372 .or_else(|| profile.get("openid"));
373 super::remaining_profile::raw_subject(value)
374}