This commit is contained in:
2026-05-08 11:30:05 +08:00
commit c0ac84fac8
563 changed files with 64232 additions and 0 deletions

View File

@@ -0,0 +1,122 @@
package user
import (
"context"
"database/sql"
"fmt"
"os"
"time"
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"bd-server/app/main/model"
"bd-server/common/ctxdata"
"bd-server/common/xerr"
"bd-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
)
type BindMobileLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewBindMobileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindMobileLogic {
return &BindMobileLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *BindMobileLogic) BindMobile(req *types.BindMobileReq) (resp *types.BindMobileResp, err error) {
claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, %v", err)
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 加密手机号失败: %v", err)
}
// 先查询用户,用于后续判断是否为内部用户
var userID int64
user, err := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
// 内部用户跳过验证码验证
needVerifyCode := os.Getenv("ENV") != "development"
if needVerifyCode && user != nil && err == nil && user.Inside == 1 {
needVerifyCode = false
}
if needVerifyCode {
// 检查手机号是否在一分钟内已发送过验证码
redisKey := fmt.Sprintf("%s:%s", "bindMobile", encryptedMobile)
cacheCode, redisErr := l.svcCtx.Redis.Get(redisKey)
if redisErr != nil {
if errors.Is(redisErr, redis.Nil) {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "手机登录, 验证码过期: %s", encryptedMobile)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取验证码redis缓存失败, mobile: %s, err: %+v", encryptedMobile, redisErr)
}
if cacheCode != req.Code {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "手机登录, 验证码不正确: %s", encryptedMobile)
}
}
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, %v", err)
}
if user != nil {
// 被封禁用户禁止绑定/登录
if user.Disable == 1 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_DISABLED), "账号已被封禁")
}
if user.CancelledAt.Valid {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_CANCELLED), "账号已注销")
}
// 进行平台绑定
if claims != nil {
if claims.UserType == model.UserTypeTemp {
userTemp, err := l.svcCtx.UserTempModel.FindOne(l.ctx, claims.UserId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_TEMP_INVALID), "绑定手机号, 临时用户不存在: %d", claims.UserId)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, 读取临时用户失败: %v", err)
}
userAuth, err := l.svcCtx.UserAuthModel.FindOneByUserIdAuthType(l.ctx, user.Id, userTemp.AuthType)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "绑定手机号, 读取用户认证失败: %v", err)
}
if userAuth != nil && userAuth.AuthKey != userTemp.AuthKey {
return nil, errors.Wrapf(xerr.NewErrMsg("该手机号已绑定其他微信号"), "绑定手机号, 临时用户已注册: %s", encryptedMobile)
}
err = l.svcCtx.UserService.TempUserBindUser(l.ctx, nil, user.Id)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 临时用户绑定用户失败: %+v", err)
}
}
}
userID = user.Id
} else {
// 创建账号,并绑定手机号
userID, err = l.svcCtx.UserService.RegisterUser(l.ctx, encryptedMobile)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 注册用户失败: %+v", err)
}
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "绑定手机号, 生成token失败: %+v", err)
}
now := time.Now().Unix()
return &types.BindMobileResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}

View File

@@ -0,0 +1,157 @@
package user
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"time"
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"bd-server/app/main/model"
"bd-server/common/ctxdata"
"bd-server/common/xerr"
"bd-server/pkg/lzkit/crypto"
pkgerrors "github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type CancelOutLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewCancelOutLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CancelOutLogic {
return &CancelOutLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
// cancelledMobilePlain 生成唯一占位明文手机号11 位),用于释放真实手机号唯一约束
func cancelledMobilePlain(userID int64) string {
return fmt.Sprintf("199%09d", userID%1000000000)
}
func (l *CancelOutLogic) CancelOut(req *types.CancelOutReq) error {
userID, err := ctxdata.GetUidFromCtx(l.ctx)
if err != nil {
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.USER_NOT_FOUND), "用户不存在")
}
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户失败: %v", err)
}
if user.Disable == 1 {
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.USER_DISABLED), "账号已被封禁")
}
if user.CancelledAt.Valid {
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.USER_CANCELLED), "账号已注销")
}
if !user.Mobile.Valid || user.Mobile.String == "" {
return pkgerrors.Wrapf(xerr.NewErrMsg("请先绑定手机号后再注销账号"), "注销账号, 未绑定手机号 userId=%d", userID)
}
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile := user.Mobile.String
if os.Getenv("ENV") != "development" {
codeKey := fmt.Sprintf("%s:%s", "cancelAccount", encryptedMobile)
cacheCode, err := l.svcCtx.Redis.Get(codeKey)
if err != nil {
if errors.Is(err, redis.Nil) {
return pkgerrors.Wrapf(xerr.NewErrMsg("验证码已过期"), "注销账号, 验证码过期")
}
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "注销账号, 读取验证码失败: %v", err)
}
if cacheCode != req.Code {
return pkgerrors.Wrapf(xerr.NewErrMsg("验证码不正确"), "注销账号, 验证码不正确")
}
}
placeholderPlain := cancelledMobilePlain(userID)
placeholderEnc, err := crypto.EncryptMobile(placeholderPlain, secretKey)
if err != nil {
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "注销账号, 生成占位手机号失败: %v", err)
}
agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
}
err = l.svcCtx.UserModel.Trans(l.ctx, func(tranCtx context.Context, session sqlx.Session) error {
dbUser, err := l.svcCtx.UserModel.FindOne(tranCtx, userID)
if err != nil {
return err
}
if dbUser.CancelledAt.Valid {
return xerr.NewErrCode(xerr.USER_CANCELLED)
}
dbUser.CancelledAt = sql.NullTime{Time: time.Now(), Valid: true}
dbUser.Mobile = sql.NullString{String: placeholderEnc, Valid: true}
dbUser.Nickname = sql.NullString{String: "已注销用户", Valid: true}
dbUser.Password = sql.NullString{Valid: false}
dbUser.Info = ""
if err := l.svcCtx.UserModel.UpdateWithVersion(tranCtx, session, dbUser); err != nil {
return pkgerrors.Wrapf(err, "更新用户注销状态失败")
}
authBuilder := l.svcCtx.UserAuthModel.SelectBuilder().Where("user_id = ?", userID)
userAuths, err := l.svcCtx.UserAuthModel.FindAll(tranCtx, authBuilder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return pkgerrors.Wrapf(err, "查询用户授权失败")
}
for _, ua := range userAuths {
if err := l.svcCtx.UserAuthModel.Delete(tranCtx, session, ua.Id); err != nil {
return pkgerrors.Wrapf(err, "删除用户授权失败 id=%d", ua.Id)
}
}
queryBuilder := l.svcCtx.QueryModel.SelectBuilder().Where("user_id = ?", userID)
queries, err := l.svcCtx.QueryModel.FindAll(tranCtx, queryBuilder, "")
if err != nil && !errors.Is(err, model.ErrNotFound) {
return pkgerrors.Wrapf(err, "查询用户查询记录失败")
}
for _, q := range queries {
if err := l.svcCtx.QueryModel.Delete(tranCtx, session, q.Id); err != nil {
return pkgerrors.Wrapf(err, "删除查询记录失败 id=%d", q.Id)
}
}
if agentModel != nil {
ag, err := l.svcCtx.AgentModel.FindOne(tranCtx, agentModel.Id)
if err != nil {
return err
}
ag.Mobile = placeholderEnc
ag.WechatId = sql.NullString{Valid: false}
if err := l.svcCtx.AgentModel.UpdateWithVersion(tranCtx, session, ag); err != nil {
return pkgerrors.Wrapf(err, "更新代理占位信息失败")
}
}
return nil
})
if err != nil {
var ce *xerr.CodeError
if errors.As(err, &ce) {
return ce
}
return pkgerrors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户注销失败: %v", err)
}
return nil
}

View File

@@ -0,0 +1,83 @@
package user
import (
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"bd-server/app/main/model"
"bd-server/common/ctxdata"
"bd-server/common/xerr"
"bd-server/pkg/lzkit/crypto"
"context"
"github.com/jinzhu/copier"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type DetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DetailLogic {
return &DetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DetailLogic) Detail() (resp *types.UserInfoResp, err error) {
claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
userID := claims.UserId
userType := claims.UserType
if userType != model.UserTypeNormal {
if userType == model.UserTypeTemp {
_, err = l.svcCtx.UserTempModel.FindOne(l.ctx, userID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_TEMP_INVALID), "用户信息, 临时用户不存在, %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户信息, 查询临时用户失败, %v", err)
}
}
return &types.UserInfoResp{
UserInfo: types.User{
Id: userID,
UserType: userType,
Mobile: "",
NickName: "",
},
}, nil
}
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userID)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_NOT_FOUND), "用户信息, 用户不存在, %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户信息, 数据库查询用户信息失败, %v", err)
}
var userInfo types.User
err = copier.Copy(&userInfo, user)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 用户信息结构体复制失败, %v", err)
}
if user.Mobile.Valid {
userInfo.Mobile, err = crypto.DecryptMobile(user.Mobile.String, l.svcCtx.Config.Encrypt.SecretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 解密手机号失败, %v", err)
}
}
userInfo.UserType = claims.UserType
return &types.UserInfoResp{
UserInfo: userInfo,
}, nil
}

View File

@@ -0,0 +1,185 @@
package user
import (
"context"
"crypto/sha1"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strings"
"time"
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"bd-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type GetSignatureLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetSignatureLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSignatureLogic {
return &GetSignatureLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetSignatureLogic) GetSignature(req *types.GetSignatureReq) (resp *types.GetSignatureResp, err error) {
// 1. 获取access_token
accessToken, err := l.getAccessToken()
if err != nil {
l.Errorf("获取access_token失败: %v", err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取access_token失败: %v", err)
}
// 2. 获取jsapi_ticket
jsapiTicket, err := l.getJsapiTicket(accessToken)
if err != nil {
l.Errorf("获取jsapi_ticket失败: %v", err)
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取jsapi_ticket失败: %v", err)
}
// 3. 生成签名
timestamp := time.Now().Unix()
nonceStr := l.generateNonceStr(16)
signature := l.generateSignature(jsapiTicket, nonceStr, timestamp, req.Url)
// 4. 返回完整的JS-SDK配置信息
return &types.GetSignatureResp{
AppId: l.svcCtx.Config.WechatH5.AppID,
Timestamp: timestamp,
NonceStr: nonceStr,
Signature: signature,
}, nil
}
// getAccessToken 获取微信公众号access_token
func (l *GetSignatureLogic) getAccessToken() (string, error) {
appID := l.svcCtx.Config.WechatH5.AppID
appSecret := l.svcCtx.Config.WechatH5.AppSecret
url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appID, appSecret)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var result struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
if err = json.Unmarshal(body, &result); err != nil {
return "", err
}
if result.ErrCode != 0 {
return "", fmt.Errorf("获取access_token失败: errcode=%d, errmsg=%s", result.ErrCode, result.ErrMsg)
}
return result.AccessToken, nil
}
// getJsapiTicket 获取jsapi_ticket
func (l *GetSignatureLogic) getJsapiTicket(accessToken string) (string, error) {
url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", accessToken)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var result struct {
Ticket string `json:"ticket"`
ExpiresIn int `json:"expires_in"`
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
if err = json.Unmarshal(body, &result); err != nil {
return "", err
}
if result.ErrCode != 0 {
return "", fmt.Errorf("获取jsapi_ticket失败: errcode=%d, errmsg=%s", result.ErrCode, result.ErrMsg)
}
return result.Ticket, nil
}
// generateNonceStr 生成随机字符串
func (l *GetSignatureLogic) generateNonceStr(length int) string {
chars := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
result := make([]byte, length)
for i := 0; i < length; i++ {
result[i] = chars[i%len(chars)]
}
return string(result)
}
// generateSignature 生成签名
func (l *GetSignatureLogic) generateSignature(jsapiTicket, nonceStr string, timestamp int64, urlStr string) string {
// 对URL进行解码避免重复编码
decodedURL, err := url.QueryUnescape(urlStr)
if err != nil {
decodedURL = urlStr
}
// 构建签名字符串
params := map[string]string{
"jsapi_ticket": jsapiTicket,
"noncestr": nonceStr,
"timestamp": fmt.Sprintf("%d", timestamp),
"url": decodedURL,
}
// 对参数进行字典序排序
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
// 拼接字符串
var signStr strings.Builder
for i, k := range keys {
if i > 0 {
signStr.WriteString("&")
}
signStr.WriteString(k)
signStr.WriteString("=")
signStr.WriteString(params[k])
}
// SHA1加密
h := sha1.New()
h.Write([]byte(signStr.String()))
signature := fmt.Sprintf("%x", h.Sum(nil))
return signature
}

View File

@@ -0,0 +1,68 @@
package user
import (
"context"
"time"
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"bd-server/app/main/model"
"bd-server/common/ctxdata"
"bd-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type GetTokenLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetTokenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTokenLogic {
return &GetTokenLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetTokenLogic) GetToken() (resp *types.MobileCodeLoginResp, err error) {
claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
// 被封禁用户禁止刷新 token临时用户 ID 在 user_temp 表)
if claims.UserType == model.UserTypeTemp {
_, err := l.svcCtx.UserTempModel.FindOne(l.ctx, claims.UserId)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_TEMP_INVALID), "用户信息, 临时用户不存在, %v", err)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "用户信息, 查询临时用户失败, %v", err)
}
} else {
user, err := l.svcCtx.UserModel.FindOne(l.ctx, claims.UserId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
if user.Disable == 1 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_DISABLED), "账号已被封禁")
}
if user.CancelledAt.Valid {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_CANCELLED), "账号已注销")
}
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, claims.UserId, claims.UserType)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, %v", err)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.MobileCodeLoginResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}

View File

@@ -0,0 +1,94 @@
package user
import (
"context"
"database/sql"
"fmt"
"os"
"time"
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"bd-server/app/main/model"
"bd-server/common/xerr"
"bd-server/pkg/lzkit/crypto"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/redis"
"github.com/zeromicro/go-zero/core/logx"
)
type MobileCodeLoginLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewMobileCodeLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MobileCodeLoginLogic {
return &MobileCodeLoginLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *MobileCodeLoginLogic) MobileCodeLogin(req *types.MobileCodeLoginReq) (resp *types.MobileCodeLoginResp, err error) {
secretKey := l.svcCtx.Config.Encrypt.SecretKey
encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 加密手机号失败: %+v", err)
}
// 先查询用户,用于后续判断是否为内部用户
var userID int64
user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
// 内部用户跳过验证码验证
needVerifyCode := os.Getenv("ENV") != "development"
if needVerifyCode && user != nil && findUserErr == nil && user.Inside == 1 {
needVerifyCode = false
}
if needVerifyCode {
// 检查手机号是否在一分钟内已发送过验证码
redisKey := fmt.Sprintf("%s:%s", "login", encryptedMobile)
cacheCode, err := l.svcCtx.Redis.Get(redisKey)
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "手机登录, 验证码过期: %s", encryptedMobile)
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取验证码redis缓存失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if cacheCode != req.Code {
return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "手机登录, 验证码不正确: %s", encryptedMobile)
}
}
if findUserErr != nil && findUserErr != model.ErrNotFound {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "手机登录, 读取数据库获取用户失败, mobile: %s, err: %+v", encryptedMobile, err)
}
if user == nil {
userID, err = l.svcCtx.UserService.RegisterUser(l.ctx, encryptedMobile)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 注册用户失败: %+v", err)
}
} else {
// 被封禁用户禁止登录
if user.Disable == 1 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_DISABLED), "账号已被封禁")
}
if user.CancelledAt.Valid {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_CANCELLED), "账号已注销")
}
userID = user.Id
}
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 生成token失败 : %d", userID)
}
// 获取当前时间戳
now := time.Now().Unix()
return &types.MobileCodeLoginResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}

View File

@@ -0,0 +1,162 @@
package user
import (
"bd-server/app/main/model"
"bd-server/common/xerr"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/pkg/errors"
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type WxH5AuthLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewWxH5AuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxH5AuthLogic {
return &WxH5AuthLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *WxH5AuthLogic) WxH5Auth(req *types.WXH5AuthReq) (resp *types.WXH5AuthResp, err error) {
// Step 1: 使用code获取access_token
accessTokenResp, err := l.GetAccessToken(req.Code)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取access_token失败: %v", err)
}
// Step 2: 查找用户授权信息
userAuth, findErr := l.svcCtx.UserAuthModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxh5OpenID, accessTokenResp.Openid)
if findErr != nil && !errors.Is(findErr, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户授权失败: %v", findErr)
}
// Step 3: 处理用户信息
var userID int64
var userType int64
if userAuth != nil {
// 已存在用户,直接登录(被封禁用户禁止登录)
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userAuth.UserId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户失败: %v", err)
}
if user.Disable == 1 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_DISABLED), "账号已被封禁")
}
if user.CancelledAt.Valid {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_CANCELLED), "账号已注销")
}
userID = userAuth.UserId
userType = model.UserTypeNormal
} else {
// 检查临时用户表
userTemp, err := l.svcCtx.UserTempModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxh5OpenID, accessTokenResp.Openid)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户临时信息失败: %v", err)
}
if userTemp == nil {
// 创建临时用户记录
userTemp = &model.UserTemp{
AuthType: model.UserAuthTypeWxh5OpenID,
AuthKey: accessTokenResp.Openid,
}
result, err := l.svcCtx.UserTempModel.Insert(l.ctx, nil, userTemp)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建临时用户信息失败: %v", err)
}
userID, err = result.LastInsertId()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的临时用户ID失败: %v", err)
}
} else {
userID = userTemp.Id
}
userType = model.UserTypeTemp
}
// Step 4: 生成JWT Token
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, userType)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成JWT token失败: %v", err)
}
// Step 5: 返回登录结果
now := time.Now().Unix()
return &types.WXH5AuthResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
type AccessTokenResp struct {
AccessToken string `json:"access_token"`
Openid string `json:"openid"`
ErrCode int `json:"errcode,omitempty"`
ErrMsg string `json:"errmsg,omitempty"`
}
// GetAccessToken 通过code获取access_token
func (l *WxH5AuthLogic) GetAccessToken(code string) (*AccessTokenResp, error) {
appID := l.svcCtx.Config.WechatH5.AppID
appSecret := l.svcCtx.Config.WechatH5.AppSecret
url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appID, appSecret, code)
const (
maxRetryTimes = 3
httpTimeout = 5 * time.Second
retryDelay = 100 * time.Millisecond
)
client := &http.Client{Timeout: httpTimeout}
var lastErr error
for attempt := 1; attempt <= maxRetryTimes; attempt++ {
resp, err := client.Get(url)
if err != nil {
lastErr = err
} else {
body, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
lastErr = readErr
} else {
var accessTokenResp AccessTokenResp
if unmarshalErr := json.Unmarshal(body, &accessTokenResp); unmarshalErr != nil {
lastErr = unmarshalErr
} else {
if accessTokenResp.ErrCode != 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
"微信接口返回错误: errcode=%d, errmsg=%s",
accessTokenResp.ErrCode, accessTokenResp.ErrMsg)
}
if accessTokenResp.AccessToken == "" || accessTokenResp.Openid == "" {
return nil, errors.New("微信接口返回数据不完整")
}
return &accessTokenResp, nil
}
}
}
if attempt < maxRetryTimes {
time.Sleep(time.Duration(attempt) * retryDelay)
}
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "请求微信access_token接口失败(重试%d次): %v", maxRetryTimes, lastErr)
}

View File

@@ -0,0 +1,173 @@
package user
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"bd-server/app/main/api/internal/svc"
"bd-server/app/main/api/internal/types"
"bd-server/app/main/model"
"bd-server/common/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
)
type WxMiniAuthLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewWxMiniAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WxMiniAuthLogic {
return &WxMiniAuthLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *WxMiniAuthLogic) WxMiniAuth(req *types.WXMiniAuthReq) (resp *types.WXMiniAuthResp, err error) {
// 1. 获取session_key和openid
sessionKeyResp, err := l.GetSessionKey(req.Code)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取session_key失败: %v", err)
}
// 2. 查找用户授权信息
userAuth, err := l.svcCtx.UserAuthModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxMiniOpenID, sessionKeyResp.Openid)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户授权失败: %v", err)
}
// 3. 处理用户信息
var userID int64
var userType int64
if userAuth != nil {
// 已存在用户,直接登录(被封禁用户禁止登录)
user, err := l.svcCtx.UserModel.FindOne(l.ctx, userAuth.UserId)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户失败: %v", err)
}
if user.Disable == 1 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_DISABLED), "账号已被封禁")
}
if user.CancelledAt.Valid {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.USER_CANCELLED), "账号已注销")
}
userID = userAuth.UserId
userType = model.UserTypeNormal
} else {
// 注册临时用户
userTemp, err := l.svcCtx.UserTempModel.FindOneByAuthTypeAuthKey(l.ctx, model.UserAuthTypeWxMiniOpenID, sessionKeyResp.Openid)
if err != nil && !errors.Is(err, model.ErrNotFound) {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询用户临时信息失败: %v", err)
}
if userTemp == nil {
// 创建新的临时用户
userTemp = &model.UserTemp{}
userTemp.AuthType = model.UserAuthTypeWxMiniOpenID
userTemp.AuthKey = sessionKeyResp.Openid
result, err := l.svcCtx.UserTempModel.Insert(l.ctx, nil, userTemp)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建临时用户信息失败: %v", err)
}
// 获取新创建的临时用户ID
userID, err = result.LastInsertId()
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取新创建的临时用户ID失败: %v", err)
}
} else {
// 使用已存在的临时用户ID
userID = userTemp.Id
}
userType = model.UserTypeTemp
}
// 4. 生成JWT Token
token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, userType)
if err != nil {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "生成JWT Token失败: %v", err)
}
// 5. 返回登录结果
now := time.Now().Unix()
return &types.WXMiniAuthResp{
AccessToken: token,
AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
}, nil
}
// SessionKeyResp 小程序登录返回结构
type SessionKeyResp struct {
Openid string `json:"openid"`
SessionKey string `json:"session_key"`
Unionid string `json:"unionid,omitempty"`
ErrCode int `json:"errcode,omitempty"`
ErrMsg string `json:"errmsg,omitempty"`
}
// GetSessionKey 通过code获取小程序的session_key和openid
func (l *WxMiniAuthLogic) GetSessionKey(code string) (*SessionKeyResp, error) {
var appID string
var appSecret string
appID = l.svcCtx.Config.WechatMini.AppID
appSecret = l.svcCtx.Config.WechatMini.AppSecret
url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
appID, appSecret, code)
const (
maxRetryTimes = 3
httpTimeout = 5 * time.Second
retryDelay = 100 * time.Millisecond
)
client := &http.Client{Timeout: httpTimeout}
var lastErr error
for attempt := 1; attempt <= maxRetryTimes; attempt++ {
resp, err := client.Get(url)
if err != nil {
lastErr = err
} else {
body, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
lastErr = readErr
} else {
var sessionKeyResp SessionKeyResp
if unmarshalErr := json.Unmarshal(body, &sessionKeyResp); unmarshalErr != nil {
lastErr = unmarshalErr
} else {
// 检查微信返回的错误码
if sessionKeyResp.ErrCode != 0 {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
"微信接口返回错误: errcode=%d, errmsg=%s",
sessionKeyResp.ErrCode, sessionKeyResp.ErrMsg)
}
// 验证必要字段
if sessionKeyResp.Openid == "" || sessionKeyResp.SessionKey == "" {
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
"微信接口返回数据不完整: openid=%s, session_key=%s",
sessionKeyResp.Openid, sessionKeyResp.SessionKey)
}
return &sessionKeyResp, nil
}
}
}
if attempt < maxRetryTimes {
time.Sleep(time.Duration(attempt) * retryDelay)
}
}
return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "请求微信session_key接口失败(重试%d次): %v", maxRetryTimes, lastErr)
}