Integrate Qiniu upload service and update configuration
- Added Qiniu configuration options to .env.example and config.go for file uploads. - Refactored main.go to include new Qiniu service and upload handler. - Updated route registration to accommodate the new upload handler. - Enhanced documentation to include references for Qiniu upload functionality. - Removed legacy authentication handler and services to streamline the codebase.
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/common/auth/service"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
// handler 层通常只做“协议转换”:
|
||||
// - 把 HTTP 请求(JSON/header 等)解析成结构体
|
||||
// - 调用 service 完成业务逻辑
|
||||
// - 把结果/错误转换成统一的 JSON 响应
|
||||
authService *service.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(authService *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
authService: authService,
|
||||
}
|
||||
}
|
||||
|
||||
type weChatLoginRequest struct {
|
||||
// binding:"required" 是 Gin 的校验标签:字段缺失或为空会导致 ShouldBindJSON 返回错误
|
||||
MiniProgramID uint `json:"mini_program_id" binding:"required"`
|
||||
Code string `json:"code" binding:"required"`
|
||||
NickName string `json:"nickname"`
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
// 使用 *int 可以区分:
|
||||
// - nil:前端没传 gender
|
||||
// - 非 nil:前端传了具体值(即使是 0)
|
||||
Gender *int `json:"gender"`
|
||||
Phone string `json:"phone"`
|
||||
}
|
||||
|
||||
func (h *AuthHandler) LoginWithWeChat(c *gin.Context) {
|
||||
// gin.Context 是每个请求的上下文对象:
|
||||
// - c.Request.Context() 是标准库 context,用于把超时/取消信号传递到 DB/HTTP 调用
|
||||
// - c.JSON(...) 用于写 JSON 响应
|
||||
var req weChatLoginRequest
|
||||
// ShouldBindJSON 会从请求体 JSON 反序列化到结构体,并根据 binding 标签做基础校验
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "invalid request payload"))
|
||||
return
|
||||
}
|
||||
|
||||
// 业务逻辑下沉到 service:这样 handler 更薄、更容易测试
|
||||
result, err := h.authService.LoginWithCode(c.Request.Context(), service.LoginRequest{
|
||||
MiniProgramID: req.MiniProgramID,
|
||||
Code: req.Code,
|
||||
NickName: req.NickName,
|
||||
AvatarURL: req.AvatarURL,
|
||||
Gender: req.Gender,
|
||||
Phone: req.Phone,
|
||||
})
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, service.ErrCodeRequired):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "code is required"))
|
||||
case errors.Is(err, service.ErrMiniProgramRequired):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "mini_program_id is required"))
|
||||
case errors.Is(err, service.ErrMiniProgramNotFound):
|
||||
c.JSON(http.StatusBadRequest, model.Error(http.StatusBadRequest, "mini program not found"))
|
||||
default:
|
||||
var apiErr *service.WeChatError
|
||||
if errors.As(err, &apiErr) {
|
||||
c.JSON(http.StatusBadGateway, model.Error(http.StatusBadGateway, apiErr.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "login failed"))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
userPayload := gin.H{
|
||||
"id": result.User.ID,
|
||||
"mini_program_id": result.User.MiniProgramID,
|
||||
"open_id": result.User.OpenID,
|
||||
"nickname": result.User.NickName,
|
||||
"avatar_url": result.User.AvatarURL,
|
||||
"gender": result.User.Gender,
|
||||
"phone": result.User.Phone,
|
||||
}
|
||||
if result.User.UnionID != "" {
|
||||
userPayload["union_id"] = result.User.UnionID
|
||||
}
|
||||
|
||||
miniProgramPayload := gin.H{
|
||||
"id": result.MiniProgram.ID,
|
||||
"name": result.MiniProgram.Name,
|
||||
"app_id": result.MiniProgram.AppID,
|
||||
}
|
||||
if result.MiniProgram.Description != "" {
|
||||
miniProgramPayload["description"] = result.MiniProgram.Description
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(gin.H{
|
||||
"user": userPayload,
|
||||
"session_key": result.SessionKey,
|
||||
"mini_program": miniProgramPayload,
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"wx_service/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrCodeRequired = errors.New("code is required")
|
||||
ErrMiniProgramRequired = errors.New("mini program id is required")
|
||||
ErrMiniProgramNotFound = errors.New("mini program not found")
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
db *gorm.DB
|
||||
miniProgramSvc *MiniProgramService
|
||||
wechatClientCache map[uint]*WeChatClient
|
||||
cacheMu sync.RWMutex
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
MiniProgramID uint
|
||||
Code string
|
||||
NickName string
|
||||
AvatarURL string
|
||||
Gender *int
|
||||
Phone string
|
||||
}
|
||||
|
||||
type LoginResult struct {
|
||||
User *model.User
|
||||
SessionKey string
|
||||
MiniProgram *model.MiniProgram
|
||||
}
|
||||
|
||||
func NewAuthService(db *gorm.DB, miniProgramSvc *MiniProgramService) *AuthService {
|
||||
return &AuthService{
|
||||
db: db,
|
||||
miniProgramSvc: miniProgramSvc,
|
||||
wechatClientCache: make(map[uint]*WeChatClient),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *AuthService) LoginWithCode(ctx context.Context, req LoginRequest) (*LoginResult, error) {
|
||||
if req.MiniProgramID == 0 {
|
||||
return nil, ErrMiniProgramRequired
|
||||
}
|
||||
if req.Code == "" {
|
||||
return nil, ErrCodeRequired
|
||||
}
|
||||
|
||||
miniProgram, err := s.miniProgramSvc.GetByID(ctx, req.MiniProgramID)
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrMiniProgramNotFound
|
||||
}
|
||||
return nil, fmt.Errorf("load mini program: %w", err)
|
||||
}
|
||||
|
||||
client := s.getWeChatClient(miniProgram)
|
||||
session, err := client.Code2Session(ctx, req.Code)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if session.OpenID == "" {
|
||||
return nil, fmt.Errorf("wechat response missing openid")
|
||||
}
|
||||
|
||||
tx := s.db.WithContext(ctx)
|
||||
var user model.User
|
||||
err = tx.Where("mini_program_id = ? AND open_id = ?", miniProgram.ID, session.OpenID).First(&user).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
user = model.User{
|
||||
MiniProgramID: miniProgram.ID,
|
||||
OpenID: session.OpenID,
|
||||
UnionID: session.UnionID,
|
||||
NickName: req.NickName,
|
||||
AvatarURL: req.AvatarURL,
|
||||
Phone: req.Phone,
|
||||
SessionKey: session.SessionKey,
|
||||
}
|
||||
if req.Gender != nil {
|
||||
user.Gender = *req.Gender
|
||||
}
|
||||
if err := tx.Create(&user).Error; err != nil {
|
||||
return nil, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
return nil, fmt.Errorf("query user: %w", err)
|
||||
} else {
|
||||
updates := map[string]interface{}{
|
||||
"session_key": session.SessionKey,
|
||||
}
|
||||
if session.UnionID != "" && session.UnionID != user.UnionID {
|
||||
updates["union_id"] = session.UnionID
|
||||
user.UnionID = session.UnionID
|
||||
}
|
||||
if req.NickName != "" && req.NickName != user.NickName {
|
||||
updates["nick_name"] = req.NickName
|
||||
user.NickName = req.NickName
|
||||
}
|
||||
if req.AvatarURL != "" && req.AvatarURL != user.AvatarURL {
|
||||
updates["avatar_url"] = req.AvatarURL
|
||||
user.AvatarURL = req.AvatarURL
|
||||
}
|
||||
if req.Phone != "" && req.Phone != user.Phone {
|
||||
updates["phone"] = req.Phone
|
||||
user.Phone = req.Phone
|
||||
}
|
||||
if req.Gender != nil && user.Gender != *req.Gender {
|
||||
updates["gender"] = *req.Gender
|
||||
user.Gender = *req.Gender
|
||||
}
|
||||
if len(updates) > 0 {
|
||||
if err := tx.Model(&user).Updates(updates).Error; err != nil {
|
||||
return nil, fmt.Errorf("update user: %w", err)
|
||||
}
|
||||
}
|
||||
user.SessionKey = session.SessionKey
|
||||
}
|
||||
|
||||
result := &LoginResult{
|
||||
User: &user,
|
||||
SessionKey: session.SessionKey,
|
||||
MiniProgram: miniProgram,
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) getWeChatClient(mp *model.MiniProgram) *WeChatClient {
|
||||
s.cacheMu.RLock()
|
||||
client, ok := s.wechatClientCache[mp.ID]
|
||||
s.cacheMu.RUnlock()
|
||||
if ok {
|
||||
return client
|
||||
}
|
||||
|
||||
newClient := NewWeChatClient(mp.AppID, mp.AppSecret, nil)
|
||||
s.cacheMu.Lock()
|
||||
s.wechatClientCache[mp.ID] = newClient
|
||||
s.cacheMu.Unlock()
|
||||
return newClient
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"wx_service/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type MiniProgramService struct {
|
||||
// service 层负责“业务能力”,通常会依赖数据库/第三方客户端等基础设施。
|
||||
// 这里通过结构体字段持有 db(依赖注入),而不是在方法里自己创建连接。
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewMiniProgramService(db *gorm.DB) *MiniProgramService {
|
||||
return &MiniProgramService{db: db}
|
||||
}
|
||||
|
||||
func (s *MiniProgramService) GetByID(ctx context.Context, id uint) (*model.MiniProgram, error) {
|
||||
// WithContext(ctx) 能把请求的超时/取消信号传递给数据库层,避免慢请求一直挂着。
|
||||
var mp model.MiniProgram
|
||||
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&mp).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &mp, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
const weChatCode2SessionURL = "https://api.weixin.qq.com/sns/jscode2session"
|
||||
|
||||
// WeChatClient 调用微信接口获取 session/openid。
|
||||
type WeChatClient struct {
|
||||
appID string
|
||||
appSecret string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
type WeChatSession struct {
|
||||
OpenID string `json:"openid"`
|
||||
UnionID string `json:"unionid"`
|
||||
SessionKey string `json:"session_key"`
|
||||
}
|
||||
|
||||
type weChatSessionResponse struct {
|
||||
WeChatSession
|
||||
ErrCode int `json:"errcode"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
}
|
||||
|
||||
// WeChatError 表示微信接口级错误。
|
||||
type WeChatError struct {
|
||||
Code int
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (e *WeChatError) Error() string {
|
||||
return fmt.Sprintf("wechat error: code=%d msg=%s", e.Code, e.Msg)
|
||||
}
|
||||
|
||||
func NewWeChatClient(appID, appSecret string, client *http.Client) *WeChatClient {
|
||||
if client == nil {
|
||||
client = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
return &WeChatClient{
|
||||
appID: appID,
|
||||
appSecret: appSecret,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *WeChatClient) Code2Session(ctx context.Context, code string) (*WeChatSession, error) {
|
||||
query := url.Values{}
|
||||
query.Set("appid", c.appID)
|
||||
query.Set("secret", c.appSecret)
|
||||
query.Set("js_code", code)
|
||||
query.Set("grant_type", "authorization_code")
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s", weChatCode2SessionURL, query.Encode()), nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build wechat request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("call wechat api: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("wechat api unexpected status: %s", resp.Status)
|
||||
}
|
||||
|
||||
var raw weChatSessionResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {
|
||||
return nil, fmt.Errorf("decode wechat response: %w", err)
|
||||
}
|
||||
|
||||
if raw.ErrCode != 0 {
|
||||
return nil, &WeChatError{Code: raw.ErrCode, Msg: raw.ErrMsg}
|
||||
}
|
||||
|
||||
return &raw.WeChatSession, nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"wx_service/internal/common/service"
|
||||
"wx_service/internal/middleware"
|
||||
"wx_service/internal/model"
|
||||
)
|
||||
|
||||
type UploadHandler struct {
|
||||
qiniuService *service.QiniuService
|
||||
}
|
||||
|
||||
func NewUploadHandler(qiniuService *service.QiniuService) *UploadHandler {
|
||||
return &UploadHandler{qiniuService: qiniuService}
|
||||
}
|
||||
|
||||
type qiniuTokenRequest struct {
|
||||
// filename 用于保留文件后缀(可选),例如:"a.png"、"video.mp4"
|
||||
Filename string `json:"filename"`
|
||||
}
|
||||
|
||||
// QiniuToken 返回七牛直传所需的 token/key/upload_url 等信息。
|
||||
// 建议放在鉴权后:用当前登录用户生成 key,避免前端写入任意路径。
|
||||
func (h *UploadHandler) QiniuToken(c *gin.Context) {
|
||||
user, ok := middleware.CurrentUser(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusUnauthorized, model.Error(http.StatusUnauthorized, "未登录或登录已过期"))
|
||||
return
|
||||
}
|
||||
|
||||
var req qiniuTokenRequest
|
||||
_ = c.ShouldBindJSON(&req) // filename 可选,解析失败也不影响生成 token
|
||||
|
||||
token, err := h.qiniuService.CreateUploadToken(user.MiniProgramID, user.ID, req.Filename)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrQiniuNotConfigured) {
|
||||
c.JSON(http.StatusServiceUnavailable, model.Error(http.StatusServiceUnavailable, "未配置七牛上传服务,请联系管理员"))
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, model.Error(http.StatusInternalServerError, "获取上传凭证失败,请稍后重试"))
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, model.Success(token))
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"wx_service/config"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrQiniuNotConfigured = errors.New("qiniu is not configured")
|
||||
)
|
||||
|
||||
type QiniuService struct {
|
||||
cfg config.QiniuConfig
|
||||
}
|
||||
|
||||
func NewQiniuService(cfg config.QiniuConfig) *QiniuService {
|
||||
return &QiniuService{cfg: cfg}
|
||||
}
|
||||
|
||||
type QiniuUploadToken struct {
|
||||
Token string `json:"token"`
|
||||
Key string `json:"key"`
|
||||
UploadURL string `json:"upload_url"`
|
||||
ExpireAt int64 `json:"expire"`
|
||||
CDNDomain string `json:"cdn_domain"`
|
||||
}
|
||||
|
||||
var extPattern = regexp.MustCompile(`^\.[a-z0-9]{1,10}$`)
|
||||
|
||||
func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filename string) (QiniuUploadToken, error) {
|
||||
if s.cfg.AccessKey == "" || s.cfg.SecretKey == "" || s.cfg.Bucket == "" {
|
||||
return QiniuUploadToken{}, ErrQiniuNotConfigured
|
||||
}
|
||||
|
||||
expireSeconds := s.cfg.TokenExpireSeconds
|
||||
if expireSeconds <= 0 {
|
||||
expireSeconds = 300
|
||||
}
|
||||
expireAt := time.Now().Add(time.Duration(expireSeconds) * time.Second).Unix()
|
||||
|
||||
ext := strings.ToLower(path.Ext(filename))
|
||||
if !extPattern.MatchString(ext) {
|
||||
ext = ""
|
||||
}
|
||||
|
||||
randomHex, err := randomHex(16)
|
||||
if err != nil {
|
||||
return QiniuUploadToken{}, fmt.Errorf("generate random key: %w", err)
|
||||
}
|
||||
|
||||
// 统一由后端生成 key,避免前端随意写入任意路径。
|
||||
// 这里按“业务前缀/小程序/用户/日期/随机名”组织,便于后期排查与管理。
|
||||
keyPrefix := strings.Trim(s.cfg.KeyPrefix, "/")
|
||||
key := fmt.Sprintf("%s/mp_%d/user_%d/%s/%s%s",
|
||||
keyPrefix,
|
||||
miniProgramID,
|
||||
userID,
|
||||
time.Now().Format("20060102"),
|
||||
randomHex,
|
||||
ext,
|
||||
)
|
||||
|
||||
putPolicy := map[string]interface{}{
|
||||
// scope = "<bucket>:<key>" 表示只允许写入指定 key(更安全)
|
||||
"scope": fmt.Sprintf("%s:%s", s.cfg.Bucket, key),
|
||||
"deadline": expireAt,
|
||||
// 上传完成后返回给前端的 JSON(七牛会做变量替换)
|
||||
"returnBody": `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"mimeType":"$(mimeType)"}`,
|
||||
}
|
||||
|
||||
policyJSON, err := json.Marshal(putPolicy)
|
||||
if err != nil {
|
||||
return QiniuUploadToken{}, fmt.Errorf("marshal put policy: %w", err)
|
||||
}
|
||||
|
||||
encodedPolicy := urlSafeBase64NoPad(policyJSON)
|
||||
sign := hmacSHA1([]byte(s.cfg.SecretKey), []byte(encodedPolicy))
|
||||
encodedSign := urlSafeBase64NoPad(sign)
|
||||
|
||||
token := fmt.Sprintf("%s:%s:%s", s.cfg.AccessKey, encodedSign, encodedPolicy)
|
||||
|
||||
return QiniuUploadToken{
|
||||
Token: token,
|
||||
Key: key,
|
||||
UploadURL: s.cfg.UploadURL,
|
||||
ExpireAt: expireAt,
|
||||
CDNDomain: s.cfg.CDNDomain,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func hmacSHA1(secret []byte, data []byte) []byte {
|
||||
mac := hmac.New(sha1.New, secret)
|
||||
mac.Write(data)
|
||||
return mac.Sum(nil)
|
||||
}
|
||||
|
||||
func urlSafeBase64NoPad(data []byte) string {
|
||||
return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(data)
|
||||
}
|
||||
|
||||
func randomHex(nBytes int) (string, error) {
|
||||
if nBytes <= 0 {
|
||||
return "", fmt.Errorf("invalid random bytes length")
|
||||
}
|
||||
buf := make([]byte, nBytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
Reference in New Issue
Block a user