609f7d06cf
- pets-fe: 微信原生小程序(首页/计划/记录/报告/社区/引导), 服务端驱动、无假数据;弹层改用 scroll-view,打开时隐藏自定义 tabBar - pets-be: Gin + GORM(MySQL, sundynix_ 前缀) + MinIO,统一响应/分页, 微信 code2session 登录,provider-neutral AI(DeepSeek),go:embed React 后台 - 修复:分段选择类型不匹配(字符串 vs 数字)导致选不中 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
78 lines
1.5 KiB
Go
78 lines
1.5 KiB
Go
package middleware
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/sundynix/pets-be/pkg/errcode"
|
|
appjwt "github.com/sundynix/pets-be/pkg/jwt"
|
|
"github.com/sundynix/pets-be/pkg/response"
|
|
)
|
|
|
|
// gin.Context 中存放身份的 key
|
|
const (
|
|
CtxUserID = "userID"
|
|
CtxAdminID = "adminID"
|
|
CtxName = "name"
|
|
)
|
|
|
|
func bearer(c *gin.Context) string {
|
|
h := c.GetHeader("Authorization")
|
|
if h == "" {
|
|
return ""
|
|
}
|
|
if strings.HasPrefix(h, "Bearer ") {
|
|
return strings.TrimPrefix(h, "Bearer ")
|
|
}
|
|
return h
|
|
}
|
|
|
|
// AuthUser 小程序用户鉴权
|
|
func AuthUser(jm *appjwt.Manager) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
claims, err := jm.Parse(bearer(c))
|
|
if err != nil || claims.Kind != appjwt.KindUser {
|
|
response.Abort(c, errcode.ErrUnauthized, "")
|
|
return
|
|
}
|
|
c.Set(CtxUserID, claims.ID)
|
|
c.Set(CtxName, claims.Name)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// AuthAdmin 后台管理员鉴权
|
|
func AuthAdmin(jm *appjwt.Manager) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
claims, err := jm.Parse(bearer(c))
|
|
if err != nil || claims.Kind != appjwt.KindAdmin {
|
|
response.Abort(c, errcode.ErrUnauthized, "")
|
|
return
|
|
}
|
|
c.Set(CtxAdminID, claims.ID)
|
|
c.Set(CtxName, claims.Name)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// UserID 从上下文取当前用户 ID
|
|
func UserID(c *gin.Context) uint {
|
|
if v, ok := c.Get(CtxUserID); ok {
|
|
if id, ok := v.(uint); ok {
|
|
return id
|
|
}
|
|
}
|
|
return 0
|
|
}
|
|
|
|
// AdminID 从上下文取当前管理员 ID
|
|
func AdminID(c *gin.Context) uint {
|
|
if v, ok := c.Get(CtxAdminID); ok {
|
|
if id, ok := v.(uint); ok {
|
|
return id
|
|
}
|
|
}
|
|
return 0
|
|
}
|