feat: 实现 C 端完整认证系统(client-auth-system)

实现面向个人客户的 7 个认证接口(A1-A7),覆盖资产验证、
微信公众号/小程序登录、手机号绑定/换绑、退出登录完整流程。

主要变更:
- 新增 PersonalCustomerOpenID 模型,支持多 AppID 多 OpenID 管理
- 实现有状态 JWT(JWT + Redis 双重校验),支持服务端主动失效
- 扩展微信 SDK:小程序 Code2Session + 3 个 DB 动态工厂函数
- 实现 A1 资产验证 IP 限流(30/min)和 A4 三层验证码限流
- 新增 7 个错误码(1180-1186)和 6 个 Redis Key 函数
- 注册 /api/c/v1/auth/* 下 7 个端点并更新 OpenAPI 文档
- 数据库迁移 000083:新建 tb_personal_customer_openid 表
This commit is contained in:
2026-03-19 11:33:41 +08:00
parent ec86dbf463
commit df76e33105
35 changed files with 4348 additions and 1362 deletions

View File

@@ -91,6 +91,10 @@ middleware:
expiration: "1m"
storage: "memory"
# 客户端配置
client:
require_phone_binding: true # 是否要求个人客户绑定手机号
# 短信服务配置
sms:
gateway_url: "" # 可选JUNHONG_SMS_GATEWAY_URL

View File

@@ -53,6 +53,49 @@ func RedisShopSubordinatesKey(shopID uint) string {
return fmt.Sprintf("shop:subordinates:%d", shopID)
}
// ========================================
// 个人客户认证相关 Redis Key
// ========================================
// RedisPersonalCustomerTokenKey 生成个人客户登录令牌的 Redis 键
// 用途:有状态 JWT存储当前有效 token 字符串,支持服务端主动失效
// 过期时间:与 JWT 过期时间一致
func RedisPersonalCustomerTokenKey(customerID uint) string {
return fmt.Sprintf("personal:customer:token:%d", customerID)
}
// RedisClientAuthRateLimitIPKey 生成 C 端资产验证 IP 限流键
// 用途A1 接口 IP 级限频 30 次/分钟
// 过期时间1 分钟
func RedisClientAuthRateLimitIPKey(ip string) string {
return fmt.Sprintf("client:auth:ratelimit:ip:%s", ip)
}
// RedisClientSendCodePhoneLimitKey 生成验证码手机号冷却键
// 用途A4 接口同手机号 60 秒冷却
// 过期时间60 秒
func RedisClientSendCodePhoneLimitKey(phone string) string {
return fmt.Sprintf("client:auth:sendcode:phone:limit:%s", phone)
}
// RedisClientSendCodeIPHourKey 生成验证码 IP 小时限流键
// 用途A4 接口同 IP 每小时 20 次
// 过期时间1 小时
func RedisClientSendCodeIPHourKey(ip string) string {
return fmt.Sprintf("client:auth:sendcode:ip:hour:%s", ip)
}
// RedisClientSendCodePhoneDayKey 生成验证码手机号日限流键
// 用途A4 接口同手机号每日 10 次
// 过期时间:当日剩余时间
func RedisClientSendCodePhoneDayKey(phone string) string {
return fmt.Sprintf("client:auth:sendcode:phone:day:%s", phone)
}
// ========================================
// 验证码相关 Redis Key
// ========================================
// RedisVerificationCodeKey 生成验证码的 Redis 键
// 用途:存储手机验证码
// 过期时间5 分钟

View File

@@ -141,6 +141,15 @@ const (
CodeFuiouCallbackInvalid = 1174 // 富友回调签名验证失败
CodeNoPaymentConfig = 1175 // 当前无可用的支付配置
// C端认证相关错误 (1180-1199)
CodeAssetNotFound = 1180 // 资产不存在A1 资产验证失败)
CodeWechatConfigUnavailable = 1181 // 微信配置不可用(无激活配置)
CodeSmsSendFailed = 1182 // 短信发送失败
CodeVerificationCodeInvalid = 1183 // 验证码错误或已过期
CodePhoneAlreadyBound = 1184 // 手机号已被其他客户绑定
CodeAlreadyBoundPhone = 1185 // 当前客户已绑定手机号,不可重复绑定
CodeOldPhoneMismatch = 1186 // 旧手机号与当前绑定不匹配
// 服务端错误 (2000-2999) -> 5xx HTTP 状态码
CodeInternalError = 2001 // 内部服务器错误
CodeDatabaseError = 2002 // 数据库错误
@@ -258,6 +267,13 @@ var allErrorCodes = []int{
CodeFuiouPayFailed,
CodeFuiouCallbackInvalid,
CodeNoPaymentConfig,
CodeAssetNotFound,
CodeWechatConfigUnavailable,
CodeSmsSendFailed,
CodeVerificationCodeInvalid,
CodePhoneAlreadyBound,
CodeAlreadyBoundPhone,
CodeOldPhoneMismatch,
CodeInternalError,
CodeDatabaseError,
CodeRedisError,
@@ -373,6 +389,13 @@ var errorMessages = map[int]string{
CodeFuiouPayFailed: "支付发起失败,请重试",
CodeFuiouCallbackInvalid: "支付回调签名验证失败",
CodeNoPaymentConfig: "当前无可用的支付配置,请联系管理员",
CodeAssetNotFound: "资产不存在",
CodeWechatConfigUnavailable: "微信配置不可用",
CodeSmsSendFailed: "短信发送失败",
CodeVerificationCodeInvalid: "验证码错误或已过期",
CodePhoneAlreadyBound: "手机号已被其他客户绑定",
CodeAlreadyBoundPhone: "当前客户已绑定手机号,不可重复绑定",
CodeOldPhoneMismatch: "旧手机号与当前绑定不匹配",
CodeInvalidCredentials: "用户名或密码错误",
CodeAccountLocked: "账号已锁定",
CodePasswordExpired: "密码已过期",

View File

@@ -2,9 +2,12 @@ package wechat
import (
"fmt"
"os"
"github.com/ArtisanCloud/PowerWeChat/v3/src/kernel"
"github.com/ArtisanCloud/PowerWeChat/v3/src/officialAccount"
"github.com/ArtisanCloud/PowerWeChat/v3/src/payment"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/pkg/config"
"github.com/redis/go-redis/v9"
"go.uber.org/zap"
@@ -49,3 +52,115 @@ func NewOfficialAccountApp(cfg *config.Config, cache kernel.CacheInterface, logg
logger.Info("微信公众号应用初始化成功", zap.String("app_id", oaCfg.AppID))
return app, nil
}
// NewOfficialAccountAppFromConfig 从数据库配置创建微信公众号应用实例
func NewOfficialAccountAppFromConfig(wechatConfig *model.WechatConfig, cache kernel.CacheInterface, logger *zap.Logger) (*officialAccount.OfficialAccount, error) {
if wechatConfig == nil {
return nil, fmt.Errorf("微信配置不能为空")
}
if wechatConfig.OaAppID == "" || wechatConfig.OaAppSecret == "" {
return nil, fmt.Errorf("微信公众号配置不完整:缺少 oa_app_id 或 oa_app_secret")
}
userConfig := &officialAccount.UserConfig{
AppID: wechatConfig.OaAppID,
Secret: wechatConfig.OaAppSecret,
Cache: cache,
}
if wechatConfig.OaToken != "" {
userConfig.Token = wechatConfig.OaToken
}
if wechatConfig.OaAesKey != "" {
userConfig.AESKey = wechatConfig.OaAesKey
}
app, err := officialAccount.NewOfficialAccount(userConfig)
if err != nil {
logger.Error("创建微信公众号应用失败", zap.Error(err))
return nil, fmt.Errorf("创建微信公众号应用失败: %w", err)
}
logger.Info("微信公众号应用初始化成功", zap.String("app_id", wechatConfig.OaAppID))
return app, nil
}
// NewMiniAppServiceFromConfig 从数据库配置创建小程序服务实例
func NewMiniAppServiceFromConfig(wechatConfig *model.WechatConfig, logger *zap.Logger) (*MiniAppService, error) {
if wechatConfig == nil {
return nil, fmt.Errorf("微信配置不能为空")
}
if wechatConfig.MiniappAppID == "" || wechatConfig.MiniappAppSecret == "" {
return nil, fmt.Errorf("小程序配置不完整:缺少 miniapp_app_id 或 miniapp_app_secret")
}
return NewMiniAppService(wechatConfig.MiniappAppID, wechatConfig.MiniappAppSecret, logger), nil
}
// NewPaymentAppFromConfig 从数据库配置创建微信支付应用实例
func NewPaymentAppFromConfig(wechatConfig *model.WechatConfig, appID string, cache kernel.CacheInterface, logger *zap.Logger) (*payment.Payment, error) {
if wechatConfig == nil {
return nil, fmt.Errorf("微信配置不能为空")
}
if appID == "" {
return nil, fmt.Errorf("appID 不能为空")
}
if wechatConfig.WxMchID == "" || wechatConfig.WxAPIV3Key == "" || wechatConfig.WxSerialNo == "" {
return nil, fmt.Errorf("微信支付配置不完整:缺少 wx_mch_id/wx_api_v3_key/wx_serial_no")
}
certPath, err := writeWechatPemTempFile("wechat_cert_*.pem", wechatConfig.WxCertContent)
if err != nil {
return nil, fmt.Errorf("写入微信支付证书失败: %w", err)
}
keyPath, err := writeWechatPemTempFile("wechat_key_*.pem", wechatConfig.WxKeyContent)
if err != nil {
return nil, fmt.Errorf("写入微信支付私钥失败: %w", err)
}
userConfig := &payment.UserConfig{
AppID: appID,
MchID: wechatConfig.WxMchID,
MchApiV3Key: wechatConfig.WxAPIV3Key,
Key: wechatConfig.WxAPIV2Key,
CertPath: certPath,
KeyPath: keyPath,
SerialNo: wechatConfig.WxSerialNo,
Cache: cache,
NotifyURL: wechatConfig.WxNotifyURL,
}
app, err := payment.NewPayment(userConfig)
if err != nil {
logger.Error("创建微信支付应用失败", zap.Error(err))
return nil, fmt.Errorf("创建微信支付应用失败: %w", err)
}
logger.Info("微信支付应用初始化成功",
zap.String("app_id", appID),
zap.String("mch_id", wechatConfig.WxMchID),
)
return app, nil
}
func writeWechatPemTempFile(pattern, content string) (string, error) {
if content == "" {
return "", fmt.Errorf("证书内容不能为空")
}
file, err := os.CreateTemp("", pattern)
if err != nil {
return "", err
}
if _, err = file.WriteString(content); err != nil {
file.Close()
return "", err
}
if err = file.Close(); err != nil {
return "", err
}
return file.Name(), nil
}

97
pkg/wechat/miniapp.go Normal file
View File

@@ -0,0 +1,97 @@
package wechat
import (
"context"
"encoding/json"
"net/http"
"net/url"
"time"
"github.com/break/junhong_cmp_fiber/pkg/errors"
"go.uber.org/zap"
)
const miniAppCode2SessionURL = "https://api.weixin.qq.com/sns/jscode2session"
// MiniAppServiceInterface 微信小程序服务接口
type MiniAppServiceInterface interface {
Code2Session(ctx context.Context, code string) (openID, unionID, sessionKey string, err error)
}
// MiniAppService 微信小程序服务实现
type MiniAppService struct {
appID string
appSecret string
client *http.Client
logger *zap.Logger
}
// NewMiniAppService 创建微信小程序服务
func NewMiniAppService(appID, appSecret string, logger *zap.Logger) *MiniAppService {
return &MiniAppService{
appID: appID,
appSecret: appSecret,
client: &http.Client{
Timeout: 10 * time.Second,
},
logger: logger,
}
}
type code2SessionResponse struct {
OpenID string `json:"openid"`
UnionID string `json:"unionid"`
SessionKey string `json:"session_key"`
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
// Code2Session 通过小程序 code 换取 openid/session_key
func (s *MiniAppService) Code2Session(ctx context.Context, code string) (openID, unionID, sessionKey string, err error) {
if code == "" {
return "", "", "", errors.New(errors.CodeInvalidParam, "授权码不能为空")
}
if s.appID == "" || s.appSecret == "" {
return "", "", "", errors.New(errors.CodeWechatConfigUnavailable, "小程序配置不完整")
}
params := url.Values{}
params.Set("appid", s.appID)
params.Set("secret", s.appSecret)
params.Set("js_code", code)
params.Set("grant_type", "authorization_code")
req, reqErr := http.NewRequestWithContext(ctx, http.MethodGet, miniAppCode2SessionURL+"?"+params.Encode(), nil)
if reqErr != nil {
s.logger.Error("构建小程序 Code2Session 请求失败", zap.Error(reqErr))
return "", "", "", errors.Wrap(errors.CodeWechatOAuthFailed, reqErr, "构建微信请求失败")
}
resp, doErr := s.client.Do(req)
if doErr != nil {
s.logger.Error("调用小程序 Code2Session 失败", zap.Error(doErr))
return "", "", "", errors.Wrap(errors.CodeWechatOAuthFailed, doErr, "调用微信接口失败")
}
defer resp.Body.Close()
var result code2SessionResponse
if decodeErr := json.NewDecoder(resp.Body).Decode(&result); decodeErr != nil {
s.logger.Error("解析小程序 Code2Session 响应失败", zap.Error(decodeErr))
return "", "", "", errors.Wrap(errors.CodeWechatOAuthFailed, decodeErr, "解析微信响应失败")
}
if result.ErrCode != 0 {
s.logger.Error("小程序 Code2Session 返回错误",
zap.Int("errcode", result.ErrCode),
zap.String("errmsg", result.ErrMsg),
)
return "", "", "", errors.New(errors.CodeWechatOAuthFailed)
}
if result.OpenID == "" || result.SessionKey == "" {
s.logger.Error("小程序 Code2Session 响应缺少关键字段", zap.String("open_id", result.OpenID))
return "", "", "", errors.New(errors.CodeWechatOAuthFailed, "微信返回数据不完整")
}
return result.OpenID, result.UnionID, result.SessionKey, nil
}

View File

@@ -42,5 +42,6 @@ type UserInfo struct {
var (
_ Service = (*OfficialAccountService)(nil)
_ OfficialAccountServiceInterface = (*OfficialAccountService)(nil)
_ MiniAppServiceInterface = (*MiniAppService)(nil)
_ PaymentServiceInterface = (*PaymentService)(nil)
)