45 lines
1.0 KiB
Go
45 lines
1.0 KiB
Go
|
|
package middleware
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"net/http"
|
|||
|
|
|
|||
|
|
"soul-api/internal/auth"
|
|||
|
|
"soul-api/internal/config"
|
|||
|
|
|
|||
|
|
"github.com/gin-gonic/gin"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
const adminClaimsKey = "admin_claims"
|
|||
|
|
|
|||
|
|
// AdminAuth 管理端鉴权:校验 JWT(Authorization: Bearer 或 Cookie admin_session),未登录返回 401;通过则设置 admin_claims 到 context
|
|||
|
|
func AdminAuth() gin.HandlerFunc {
|
|||
|
|
return func(c *gin.Context) {
|
|||
|
|
cfg := config.Get()
|
|||
|
|
if cfg == nil {
|
|||
|
|
c.Next()
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
token := auth.GetAdminJWTFromRequest(c.Request)
|
|||
|
|
claims, ok := auth.ParseAdminJWT(token, cfg.AdminSessionSecret)
|
|||
|
|
if !ok {
|
|||
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"success": false, "error": "未授权访问,请先登录"})
|
|||
|
|
return
|
|||
|
|
}
|
|||
|
|
c.Set(adminClaimsKey, claims)
|
|||
|
|
c.Next()
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// GetAdminClaims 从 context 获取 admin claims(需在 AdminAuth 之后调用)
|
|||
|
|
func GetAdminClaims(c *gin.Context) *auth.AdminClaims {
|
|||
|
|
v, ok := c.Get(adminClaimsKey)
|
|||
|
|
if !ok || v == nil {
|
|||
|
|
return nil
|
|||
|
|
}
|
|||
|
|
claims, ok := v.(*auth.AdminClaims)
|
|||
|
|
if !ok {
|
|||
|
|
return nil
|
|||
|
|
}
|
|||
|
|
return claims
|
|||
|
|
}
|