Integrate unfinished server-rs refactor worklists
This commit is contained in:
@@ -19,6 +19,7 @@ use sha2::{Digest, Sha256};
|
||||
use shared_kernel::{new_uuid_simple_string, normalize_optional_string, normalize_required_string};
|
||||
use time::{Duration, OffsetDateTime};
|
||||
use tracing::{info, warn};
|
||||
use url::Url;
|
||||
|
||||
pub const ACCESS_TOKEN_ALGORITHM: Algorithm = Algorithm::HS256;
|
||||
pub const DEFAULT_ACCESS_TOKEN_TTL_SECONDS: u64 = 2 * 60 * 60;
|
||||
@@ -35,6 +36,12 @@ pub const DEFAULT_SMS_VALID_TIME_SECONDS: u64 = 300;
|
||||
pub const DEFAULT_SMS_INTERVAL_SECONDS: u64 = 60;
|
||||
pub const DEFAULT_SMS_DUPLICATE_POLICY: u8 = 1;
|
||||
pub const DEFAULT_SMS_CASE_AUTH_POLICY: u8 = 1;
|
||||
pub const DEFAULT_WECHAT_AUTHORIZE_ENDPOINT: &str = "https://open.weixin.qq.com/connect/qrconnect";
|
||||
pub const DEFAULT_WECHAT_IN_APP_AUTHORIZE_ENDPOINT: &str =
|
||||
"https://open.weixin.qq.com/connect/oauth2/authorize";
|
||||
pub const DEFAULT_WECHAT_ACCESS_TOKEN_ENDPOINT: &str =
|
||||
"https://api.weixin.qq.com/sns/oauth2/access_token";
|
||||
pub const DEFAULT_WECHAT_USER_INFO_ENDPOINT: &str = "https://api.weixin.qq.com/sns/userinfo";
|
||||
|
||||
type HmacSha1 = Hmac<Sha1>;
|
||||
|
||||
@@ -159,6 +166,60 @@ pub struct SmsVerifyCodeRequest {
|
||||
pub provider_out_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum WechatAuthScene {
|
||||
Desktop,
|
||||
WechatInApp,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WechatAuthConfig {
|
||||
pub enabled: bool,
|
||||
pub provider: String,
|
||||
pub app_id: Option<String>,
|
||||
pub app_secret: Option<String>,
|
||||
pub authorize_endpoint: String,
|
||||
pub access_token_endpoint: String,
|
||||
pub user_info_endpoint: String,
|
||||
pub mock_user_id: String,
|
||||
pub mock_union_id: Option<String>,
|
||||
pub mock_display_name: String,
|
||||
pub mock_avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct WechatIdentityProfile {
|
||||
pub provider_uid: String,
|
||||
pub provider_union_id: Option<String>,
|
||||
pub display_name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum WechatProvider {
|
||||
Disabled,
|
||||
Mock(MockWechatProvider),
|
||||
Real(RealWechatProvider),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MockWechatProvider {
|
||||
mock_user_id: String,
|
||||
mock_union_id: Option<String>,
|
||||
mock_display_name: String,
|
||||
mock_avatar_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RealWechatProvider {
|
||||
client: Client,
|
||||
app_id: String,
|
||||
app_secret: String,
|
||||
authorize_endpoint: String,
|
||||
access_token_endpoint: String,
|
||||
user_info_endpoint: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum SmsAuthProvider {
|
||||
Mock(MockSmsAuthProvider),
|
||||
@@ -202,6 +263,54 @@ pub enum SmsProviderError {
|
||||
Upstream(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum WechatProviderError {
|
||||
Disabled,
|
||||
MissingCode,
|
||||
InvalidConfig(String),
|
||||
InvalidCallback(String),
|
||||
RequestFailed(String),
|
||||
DeserializeFailed(String),
|
||||
Upstream(String),
|
||||
MissingProfile(String),
|
||||
}
|
||||
|
||||
// 鉴权平台错误统一先归类,api-server 再决定 HTTP status 和错误 envelope。
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AuthPlatformErrorKind {
|
||||
InvalidConfig,
|
||||
InvalidClaims,
|
||||
SignFailed,
|
||||
VerifyFailed,
|
||||
CookieConfig,
|
||||
HashFailed,
|
||||
InvalidVerifyCode,
|
||||
Disabled,
|
||||
MissingCode,
|
||||
InvalidCallback,
|
||||
RequestFailed,
|
||||
DeserializeFailed,
|
||||
MissingProfile,
|
||||
Upstream,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct WechatAccessTokenResponse {
|
||||
access_token: Option<String>,
|
||||
openid: Option<String>,
|
||||
unionid: Option<String>,
|
||||
errmsg: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct WechatUserInfoResponse {
|
||||
openid: Option<String>,
|
||||
unionid: Option<String>,
|
||||
nickname: Option<String>,
|
||||
headimgurl: Option<String>,
|
||||
errmsg: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct AliyunSendSmsVerifyCodeResponse {
|
||||
// 阿里云 RPC 原始 JSON 使用首字母大写字段名,这里必须显式映射,避免把成功响应误判成空值。
|
||||
@@ -512,6 +621,257 @@ impl SmsAuthProvider {
|
||||
}
|
||||
}
|
||||
|
||||
impl WechatAuthConfig {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
enabled: bool,
|
||||
provider: String,
|
||||
app_id: Option<String>,
|
||||
app_secret: Option<String>,
|
||||
authorize_endpoint: String,
|
||||
access_token_endpoint: String,
|
||||
user_info_endpoint: String,
|
||||
mock_user_id: String,
|
||||
mock_union_id: Option<String>,
|
||||
mock_display_name: String,
|
||||
mock_avatar_url: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
enabled,
|
||||
provider,
|
||||
app_id,
|
||||
app_secret,
|
||||
authorize_endpoint,
|
||||
access_token_endpoint,
|
||||
user_info_endpoint,
|
||||
mock_user_id,
|
||||
mock_union_id,
|
||||
mock_display_name,
|
||||
mock_avatar_url,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WechatProvider {
|
||||
pub fn new(config: WechatAuthConfig) -> Self {
|
||||
if !config.enabled {
|
||||
return Self::Disabled;
|
||||
}
|
||||
|
||||
if config.provider.trim().eq_ignore_ascii_case("mock") {
|
||||
return Self::Mock(MockWechatProvider {
|
||||
mock_user_id: config.mock_user_id,
|
||||
mock_union_id: config.mock_union_id,
|
||||
mock_display_name: config.mock_display_name,
|
||||
mock_avatar_url: config.mock_avatar_url,
|
||||
});
|
||||
}
|
||||
|
||||
let Some(app_id) = config.app_id else {
|
||||
return Self::Disabled;
|
||||
};
|
||||
let Some(app_secret) = config.app_secret else {
|
||||
return Self::Disabled;
|
||||
};
|
||||
|
||||
Self::Real(RealWechatProvider {
|
||||
client: Client::new(),
|
||||
app_id,
|
||||
app_secret,
|
||||
authorize_endpoint: config.authorize_endpoint,
|
||||
access_token_endpoint: config.access_token_endpoint,
|
||||
user_info_endpoint: config.user_info_endpoint,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_authorization_url(
|
||||
&self,
|
||||
callback_url: &str,
|
||||
state: &str,
|
||||
scene: &WechatAuthScene,
|
||||
) -> Result<String, WechatProviderError> {
|
||||
match self {
|
||||
Self::Disabled => Err(WechatProviderError::Disabled),
|
||||
Self::Mock(_) => build_mock_wechat_authorization_url(callback_url, state),
|
||||
Self::Real(provider) => provider.build_authorization_url(callback_url, state, scene),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn resolve_callback_profile(
|
||||
&self,
|
||||
code: Option<&str>,
|
||||
mock_code: Option<&str>,
|
||||
) -> Result<WechatIdentityProfile, WechatProviderError> {
|
||||
match self {
|
||||
Self::Disabled => Err(WechatProviderError::Disabled),
|
||||
Self::Mock(provider) => Ok(provider.resolve_callback_profile(mock_code)),
|
||||
Self::Real(provider) => provider.resolve_callback_profile(code).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MockWechatProvider {
|
||||
fn resolve_callback_profile(&self, mock_code: Option<&str>) -> WechatIdentityProfile {
|
||||
let provider_uid = mock_code
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or(self.mock_user_id.as_str())
|
||||
.to_string();
|
||||
WechatIdentityProfile {
|
||||
provider_uid,
|
||||
provider_union_id: self.mock_union_id.clone(),
|
||||
display_name: Some(self.mock_display_name.clone()),
|
||||
avatar_url: self.mock_avatar_url.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RealWechatProvider {
|
||||
fn build_authorization_url(
|
||||
&self,
|
||||
callback_url: &str,
|
||||
state: &str,
|
||||
scene: &WechatAuthScene,
|
||||
) -> Result<String, WechatProviderError> {
|
||||
let endpoint = match scene {
|
||||
WechatAuthScene::Desktop => &self.authorize_endpoint,
|
||||
WechatAuthScene::WechatInApp => DEFAULT_WECHAT_IN_APP_AUTHORIZE_ENDPOINT,
|
||||
};
|
||||
let mut url = Url::parse(endpoint).map_err(|error| {
|
||||
WechatProviderError::InvalidConfig(format!("微信授权地址非法:{error}"))
|
||||
})?;
|
||||
url.query_pairs_mut()
|
||||
.append_pair("appid", &self.app_id)
|
||||
.append_pair("redirect_uri", callback_url)
|
||||
.append_pair("response_type", "code")
|
||||
.append_pair(
|
||||
"scope",
|
||||
match scene {
|
||||
WechatAuthScene::Desktop => "snsapi_login",
|
||||
WechatAuthScene::WechatInApp => "snsapi_userinfo",
|
||||
},
|
||||
)
|
||||
.append_pair("state", state);
|
||||
Ok(format!("{url}#wechat_redirect"))
|
||||
}
|
||||
|
||||
async fn resolve_callback_profile(
|
||||
&self,
|
||||
code: Option<&str>,
|
||||
) -> Result<WechatIdentityProfile, WechatProviderError> {
|
||||
let code = code
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or(WechatProviderError::MissingCode)?;
|
||||
|
||||
let mut access_token_url = Url::parse(&self.access_token_endpoint).map_err(|error| {
|
||||
WechatProviderError::InvalidConfig(format!("微信 access_token 地址非法:{error}"))
|
||||
})?;
|
||||
access_token_url
|
||||
.query_pairs_mut()
|
||||
.append_pair("appid", &self.app_id)
|
||||
.append_pair("secret", &self.app_secret)
|
||||
.append_pair("code", code)
|
||||
.append_pair("grant_type", "authorization_code");
|
||||
|
||||
let access_token_payload = self
|
||||
.client
|
||||
.get(access_token_url.as_str())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| {
|
||||
warn!(error = %error, "微信 access_token 请求失败");
|
||||
WechatProviderError::RequestFailed(
|
||||
"微信登录失败:access_token 请求失败".to_string(),
|
||||
)
|
||||
})?
|
||||
.json::<WechatAccessTokenResponse>()
|
||||
.await
|
||||
.map_err(|error| {
|
||||
warn!(error = %error, "微信 access_token 响应解析失败");
|
||||
WechatProviderError::DeserializeFailed(
|
||||
"微信登录失败:access_token 响应非法".to_string(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let access_token = access_token_payload
|
||||
.access_token
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
WechatProviderError::Upstream(format!(
|
||||
"微信登录失败:{}",
|
||||
access_token_payload
|
||||
.errmsg
|
||||
.unwrap_or_else(|| "缺少 access_token".to_string())
|
||||
))
|
||||
})?;
|
||||
let openid = access_token_payload
|
||||
.openid
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
WechatProviderError::MissingProfile("微信登录失败:缺少 openid".to_string())
|
||||
})?;
|
||||
|
||||
let mut user_info_url = Url::parse(&self.user_info_endpoint).map_err(|error| {
|
||||
WechatProviderError::InvalidConfig(format!("微信用户信息地址非法:{error}"))
|
||||
})?;
|
||||
user_info_url
|
||||
.query_pairs_mut()
|
||||
.append_pair("access_token", &access_token)
|
||||
.append_pair("openid", &openid)
|
||||
.append_pair("lang", "zh_CN");
|
||||
|
||||
let user_info_payload = self
|
||||
.client
|
||||
.get(user_info_url.as_str())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| {
|
||||
warn!(error = %error, "微信用户信息请求失败");
|
||||
WechatProviderError::RequestFailed("微信登录失败:用户信息请求失败".to_string())
|
||||
})?
|
||||
.json::<WechatUserInfoResponse>()
|
||||
.await
|
||||
.map_err(|error| {
|
||||
warn!(error = %error, "微信用户信息响应解析失败");
|
||||
WechatProviderError::DeserializeFailed("微信登录失败:用户信息响应非法".to_string())
|
||||
})?;
|
||||
|
||||
let provider_uid = user_info_payload
|
||||
.openid
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.ok_or_else(|| {
|
||||
WechatProviderError::Upstream(format!(
|
||||
"微信登录失败:{}",
|
||||
user_info_payload
|
||||
.errmsg
|
||||
.unwrap_or_else(|| "缺少 openid".to_string())
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(WechatIdentityProfile {
|
||||
provider_uid,
|
||||
provider_union_id: user_info_payload.unionid.or(access_token_payload.unionid),
|
||||
display_name: user_info_payload.nickname,
|
||||
avatar_url: user_info_payload.headimgurl,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn build_mock_wechat_authorization_url(
|
||||
callback_url: &str,
|
||||
state: &str,
|
||||
) -> Result<String, WechatProviderError> {
|
||||
let mut callback = Url::parse(callback_url).map_err(|error| {
|
||||
WechatProviderError::InvalidCallback(format!("微信回调地址非法:{error}"))
|
||||
})?;
|
||||
callback
|
||||
.query_pairs_mut()
|
||||
.append_pair("mock_code", "wx-mock-code")
|
||||
.append_pair("state", state);
|
||||
Ok(callback.to_string())
|
||||
}
|
||||
|
||||
impl MockSmsAuthProvider {
|
||||
async fn send_code(
|
||||
&self,
|
||||
@@ -1262,10 +1622,154 @@ impl fmt::Display for SmsProviderError {
|
||||
|
||||
impl Error for SmsProviderError {}
|
||||
|
||||
impl fmt::Display for WechatProviderError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Disabled => f.write_str("微信登录暂未启用"),
|
||||
Self::MissingCode => f.write_str("缺少微信授权 code"),
|
||||
Self::InvalidConfig(message)
|
||||
| Self::InvalidCallback(message)
|
||||
| Self::RequestFailed(message)
|
||||
| Self::DeserializeFailed(message)
|
||||
| Self::Upstream(message)
|
||||
| Self::MissingProfile(message) => f.write_str(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for WechatProviderError {}
|
||||
|
||||
impl JwtError {
|
||||
pub fn kind(&self) -> AuthPlatformErrorKind {
|
||||
match self {
|
||||
Self::InvalidConfig(_) => AuthPlatformErrorKind::InvalidConfig,
|
||||
Self::InvalidClaims(_) => AuthPlatformErrorKind::InvalidClaims,
|
||||
Self::SignFailed(_) => AuthPlatformErrorKind::SignFailed,
|
||||
Self::VerifyFailed(_) => AuthPlatformErrorKind::VerifyFailed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RefreshCookieError {
|
||||
pub fn kind(&self) -> AuthPlatformErrorKind {
|
||||
match self {
|
||||
Self::InvalidConfig(_) => AuthPlatformErrorKind::CookieConfig,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PasswordHashError {
|
||||
pub fn kind(&self) -> AuthPlatformErrorKind {
|
||||
match self {
|
||||
Self::HashFailed(_) => AuthPlatformErrorKind::HashFailed,
|
||||
Self::VerifyFailed(_) => AuthPlatformErrorKind::VerifyFailed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SmsProviderError {
|
||||
pub fn kind(&self) -> AuthPlatformErrorKind {
|
||||
match self {
|
||||
Self::InvalidConfig(_) => AuthPlatformErrorKind::InvalidConfig,
|
||||
Self::InvalidVerifyCode => AuthPlatformErrorKind::InvalidVerifyCode,
|
||||
Self::Upstream(_) => AuthPlatformErrorKind::Upstream,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WechatProviderError {
|
||||
pub fn kind(&self) -> AuthPlatformErrorKind {
|
||||
match self {
|
||||
Self::Disabled => AuthPlatformErrorKind::Disabled,
|
||||
Self::MissingCode => AuthPlatformErrorKind::MissingCode,
|
||||
Self::InvalidConfig(_) => AuthPlatformErrorKind::InvalidConfig,
|
||||
Self::InvalidCallback(_) => AuthPlatformErrorKind::InvalidCallback,
|
||||
Self::RequestFailed(_) => AuthPlatformErrorKind::RequestFailed,
|
||||
Self::DeserializeFailed(_) => AuthPlatformErrorKind::DeserializeFailed,
|
||||
Self::Upstream(_) => AuthPlatformErrorKind::Upstream,
|
||||
Self::MissingProfile(_) => AuthPlatformErrorKind::MissingProfile,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auth_platform_error_kind_is_stable_for_adapter_mapping() {
|
||||
assert_eq!(
|
||||
JwtError::InvalidClaims("JWT roles 至少包含一个角色").kind(),
|
||||
AuthPlatformErrorKind::InvalidClaims
|
||||
);
|
||||
assert_eq!(
|
||||
PasswordHashError::VerifyFailed("密码校验失败".to_string()).kind(),
|
||||
AuthPlatformErrorKind::VerifyFailed
|
||||
);
|
||||
assert_eq!(
|
||||
SmsProviderError::InvalidVerifyCode.kind(),
|
||||
AuthPlatformErrorKind::InvalidVerifyCode
|
||||
);
|
||||
assert_eq!(
|
||||
WechatProviderError::MissingCode.kind(),
|
||||
AuthPlatformErrorKind::MissingCode
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mock_wechat_provider_builds_callback_authorization_url() {
|
||||
let provider = WechatProvider::new(WechatAuthConfig::new(
|
||||
true,
|
||||
"mock".to_string(),
|
||||
None,
|
||||
None,
|
||||
DEFAULT_WECHAT_AUTHORIZE_ENDPOINT.to_string(),
|
||||
DEFAULT_WECHAT_ACCESS_TOKEN_ENDPOINT.to_string(),
|
||||
DEFAULT_WECHAT_USER_INFO_ENDPOINT.to_string(),
|
||||
"wx-user-001".to_string(),
|
||||
Some("wx-union-001".to_string()),
|
||||
"微信测试用户".to_string(),
|
||||
Some("https://example.test/avatar.png".to_string()),
|
||||
));
|
||||
|
||||
let authorization_url = provider
|
||||
.build_authorization_url(
|
||||
"http://127.0.0.1:3000/api/auth/wechat/callback",
|
||||
"state_001",
|
||||
&WechatAuthScene::Desktop,
|
||||
)
|
||||
.expect("mock authorization url should build");
|
||||
|
||||
assert!(authorization_url.contains("mock_code=wx-mock-code"));
|
||||
assert!(authorization_url.contains("state=state_001"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mock_wechat_provider_resolves_identity_profile() {
|
||||
let provider = WechatProvider::new(WechatAuthConfig::new(
|
||||
true,
|
||||
"mock".to_string(),
|
||||
None,
|
||||
None,
|
||||
DEFAULT_WECHAT_AUTHORIZE_ENDPOINT.to_string(),
|
||||
DEFAULT_WECHAT_ACCESS_TOKEN_ENDPOINT.to_string(),
|
||||
DEFAULT_WECHAT_USER_INFO_ENDPOINT.to_string(),
|
||||
"wx-user-001".to_string(),
|
||||
Some("wx-union-001".to_string()),
|
||||
"微信测试用户".to_string(),
|
||||
None,
|
||||
));
|
||||
|
||||
let profile = provider
|
||||
.resolve_callback_profile(None, Some("wx-code-001"))
|
||||
.await
|
||||
.expect("mock profile should resolve");
|
||||
|
||||
assert_eq!(profile.provider_uid, "wx-code-001");
|
||||
assert_eq!(profile.provider_union_id.as_deref(), Some("wx-union-001"));
|
||||
assert_eq!(profile.display_name.as_deref(), Some("微信测试用户"));
|
||||
}
|
||||
|
||||
fn build_jwt_config() -> JwtConfig {
|
||||
JwtConfig::new(
|
||||
"https://auth.genarrative.local".to_string(),
|
||||
|
||||
Reference in New Issue
Block a user