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,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
|
||||
}
|
||||
Reference in New Issue
Block a user