61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
// Package middleware 提供 HTTP 中间件。
|
|
package middleware
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"portal-mini-go/internal/pkg/errors"
|
|
"portal-mini-go/internal/repository/miniapp"
|
|
)
|
|
|
|
const (
|
|
appIDCtxKey = "app_id"
|
|
miniIDCtxKey = "mini_id"
|
|
)
|
|
|
|
// headerAppID 是小程序在请求头中携带的微信 AppID 字段名。
|
|
const HeaderAppID = "X-App-ID"
|
|
|
|
// MiniAppAuth 校验请求头中的 app_id 是否对应一个已启用且未删除的被纳管小程序,
|
|
// 通过则将 app_id 与小程序的数据库主键注入 context,供后续 handler/service 使用。
|
|
// 用户身份最终由 (mini_id, open_id) 唯一确定。
|
|
func MiniAppAuth(repo *miniapp.Repository) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
appID := c.GetHeader(HeaderAppID)
|
|
if appID == "" {
|
|
c.Error(errors.ErrBadRequest)
|
|
c.Abort()
|
|
return
|
|
}
|
|
mp, err := repo.GetActiveByAppID(c.Request.Context(), appID)
|
|
if err != nil {
|
|
c.Error(errors.ErrNotFound)
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set(appIDCtxKey, appID)
|
|
c.Set(miniIDCtxKey, mp.ID)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// AppID 从 gin.Context 取出已校验的 appID。
|
|
func AppID(c *gin.Context) string {
|
|
if v, ok := c.Get(appIDCtxKey); ok {
|
|
if s, ok := v.(string); ok {
|
|
return s
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// MiniID 从 gin.Context 取出已校验的小程序数据库主键。
|
|
func MiniID(c *gin.Context) uint64 {
|
|
if v, ok := c.Get(miniIDCtxKey); ok {
|
|
if id, ok := v.(uint64); ok {
|
|
return id
|
|
}
|
|
}
|
|
return 0
|
|
}
|