Files
affiliate_dash/backend/internal/middleware/auth.go
T
2026-07-20 14:58:57 +08:00

73 lines
1.4 KiB
Go

package middleware
import (
"strings"
"affiliate_dash/internal/pkg/jwt"
"affiliate_dash/internal/pkg/response"
"github.com/gin-gonic/gin"
)
const (
CtxUserID = "user_id"
CtxUsername = "username"
CtxRole = "role"
)
func Auth(jm *jwt.Manager) gin.HandlerFunc {
return func(c *gin.Context) {
auth := c.GetHeader("Authorization")
if auth == "" {
response.Unauthorized(c, "未登录")
c.Abort()
return
}
parts := strings.SplitN(auth, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
response.Unauthorized(c, "无效的认证头")
c.Abort()
return
}
claims, err := jm.Parse(parts[1])
if err != nil {
response.Unauthorized(c, "登录已过期,请重新登录")
c.Abort()
return
}
c.Set(CtxUserID, claims.UserID)
c.Set(CtxUsername, claims.Username)
c.Set(CtxRole, claims.Role)
c.Next()
}
}
func RequireRole(roles ...string) gin.HandlerFunc {
set := make(map[string]struct{}, len(roles))
for _, r := range roles {
set[r] = struct{}{}
}
return func(c *gin.Context) {
role, _ := c.Get(CtxRole)
roleStr, _ := role.(string)
if _, ok := set[roleStr]; !ok {
response.Forbidden(c, "权限不足")
c.Abort()
return
}
c.Next()
}
}
func GetUserID(c *gin.Context) uint {
v, _ := c.Get(CtxUserID)
id, _ := v.(uint)
return id
}
func GetRole(c *gin.Context) string {
v, _ := c.Get(CtxRole)
role, _ := v.(string)
return role
}