48 lines
1.2 KiB
Go
48 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"everypublish/server/internal/api/response"
|
|
"everypublish/server/internal/auth"
|
|
"everypublish/server/internal/config"
|
|
)
|
|
|
|
// AuthRequired 校验访问令牌并把声明写入上下文
|
|
func AuthRequired(cfg *config.Config) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
header := c.GetHeader("Authorization")
|
|
if !strings.HasPrefix(header, "Bearer ") {
|
|
response.Fail(c, http.StatusUnauthorized, 1002, "未登录或令牌缺失")
|
|
c.Abort()
|
|
return
|
|
}
|
|
claims, err := auth.ParseAccess(cfg.JWTSecret, strings.TrimPrefix(header, "Bearer "))
|
|
if err != nil {
|
|
response.Fail(c, http.StatusUnauthorized, 1002, "令牌无效或已过期")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set("uid", claims.UID)
|
|
c.Set("wsid", claims.WorkspaceID)
|
|
c.Set("role", claims.Role)
|
|
c.Set("mrole", claims.MemberRole)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// AdminRequired 平台管理员守卫(D7 挂载 admin 路由)
|
|
func AdminRequired() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if c.GetString("role") != "admin" {
|
|
response.Fail(c, http.StatusForbidden, 1003, "无平台管理权限")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|