fix(server): 安全加固与版本链路修复

- 微信登录改为真实 jscode2session,session_key 不再下发客户端
- 支付回调增加 HMAC 验签(X-Pay-Sign)与幂等处理,未配置密钥时拒绝回调
- 订单金额一律以服务端商品表定价,禁止客户端传入金额
- 付费许愿改为支付成功后创建,不再先许愿后付款
- 管理后台增加登录认证(ADMIN_PASSWORD + role=admin JWT + HttpOnly Cookie)
- 订单详情/取消增加本人归属校验,修复越权访问
- 版本信息改为 ldflags 注入单一链路,GoVersion 用 runtime.Version()
- 恢复 gin 默认访问日志(原 Logger 中间件输出为空)
- 加载 HTML 模板修复后台页面 500;godotenv 加载 .env.local
- CORS 支持 CORS_ORIGINS 白名单配置
This commit is contained in:
gouki
2026-08-09 00:09:24 +00:00
parent daebda22ee
commit b8c439deac
11 changed files with 549 additions and 179 deletions
+101 -31
View File
@@ -1,7 +1,12 @@
package handler
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/gin-gonic/gin"
"github.com/gouki/lunar-server/internal/config"
@@ -9,7 +14,71 @@ import (
"github.com/gouki/lunar-server/internal/service"
)
// UserLogin 用户登录
// code2Session 调用微信 jscode2session 接口换取 openid
// session_key 仅保存在服务端,绝不下发给客户端
func code2Session(code string) (openID, unionID string, err error) {
cfg := config.Load()
if cfg.Wechat.AppID == "" || cfg.Wechat.AppSecret == "" {
return "", "", fmt.Errorf("wechat appid/secret not configured")
}
query := url.Values{
"appid": {cfg.Wechat.AppID},
"secret": {cfg.Wechat.AppSecret},
"js_code": {code},
"grant_type": {"authorization_code"},
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get("https://api.weixin.qq.com/sns/jscode2session?" + query.Encode())
if err != nil {
return "", "", fmt.Errorf("jscode2session request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
if err != nil {
return "", "", fmt.Errorf("read jscode2session response failed: %w", err)
}
var result struct {
OpenID string `json:"openid"`
UnionID string `json:"unionid"`
ErrCode int `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
if err := json.Unmarshal(body, &result); err != nil {
return "", "", fmt.Errorf("parse jscode2session response failed: %w", err)
}
if result.ErrCode != 0 || result.OpenID == "" {
return "", "", fmt.Errorf("wechat auth failed: errcode=%d errmsg=%s", result.ErrCode, result.ErrMsg)
}
return result.OpenID, result.UnionID, nil
}
// upsertUser 根据 openid 获取用户,不存在则创建
func upsertUser(openID, unionID string) (*model.User, error) {
userService := service.NewUserService()
user, err := userService.GetUserByOpenID(openID)
if err != nil {
return nil, err
}
if user == nil {
user = &model.User{
OpenID: openID,
UnionID: unionID,
Nickname: "微信用户",
Status: 1,
}
if err := userService.CreateUser(user); err != nil {
return nil, err
}
}
return user, nil
}
// UserLogin 用户登录(小程序 wx.login 的 code 换取 token
func UserLogin(c *gin.Context) {
var req struct {
Code string `json:"code" binding:"required"`
@@ -23,38 +92,35 @@ func UserLogin(c *gin.Context) {
return
}
// TODO: 调用微信接口获取 openid
// 这里模拟返回
openID := "mock_openid_" + req.Code
userService := service.NewUserService()
user, err := userService.GetUserByOpenID(openID)
openID, unionID, err := code2Session(req.Code)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"msg": "服务器错误",
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"msg": "微信登录失败",
})
return
}
// 如果用户不存在,创建新用户
if user == nil {
user = &model.User{
OpenID: openID,
Nickname: "微信用户",
Status: 1,
}
if err := userService.CreateUser(user); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"msg": "创建用户失败",
})
return
}
user, err := upsertUser(openID, unionID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"msg": "创建用户失败",
})
return
}
// 禁用用户不允许登录
if user.Status != 1 {
c.JSON(http.StatusForbidden, gin.H{
"code": 403,
"msg": "账号已被禁用",
})
return
}
// 生成 token
cfg := config.Load()
userService := service.NewUserService()
token, err := userService.GenerateToken(user.ID, cfg.JWT.Secret)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -217,7 +283,7 @@ func UpdateUserProfile(c *gin.Context) {
})
}
// WechatAuth 微信授权
// WechatAuth 微信授权(仅返回 openidsession_key 属敏感凭证不下发)
func WechatAuth(c *gin.Context) {
var req struct {
Code string `json:"code" binding:"required"`
@@ -231,16 +297,20 @@ func WechatAuth(c *gin.Context) {
return
}
// TODO: 调用微信接口获取 openid 和 session_key
// 这里模拟返回
openID := "mock_openid_" + req.Code
openID, _, err := code2Session(req.Code)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"code": 401,
"msg": "微信授权失败",
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": gin.H{
"openid": openID,
"sessionKey": "mock_session_key",
"openid": openID,
},
})
}