1Panel/core/middleware/jwt.go

51 lines
1.3 KiB
Go
Raw Normal View History

2024-07-19 19:04:11 +08:00
package middleware
import (
"fmt"
2024-07-25 18:13:57 +08:00
"strings"
"github.com/1Panel-dev/1Panel/core/app/api/v2/helper"
2024-07-19 19:04:11 +08:00
"github.com/1Panel-dev/1Panel/core/constant"
jwtUtils "github.com/1Panel-dev/1Panel/core/utils/jwt"
"github.com/gin-gonic/gin"
)
func JwtAuth() gin.HandlerFunc {
return func(c *gin.Context) {
2024-07-25 18:13:57 +08:00
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/core/auth") {
c.Next()
return
}
2024-07-19 19:04:11 +08:00
token := c.Request.Header.Get(constant.JWTHeaderName)
if token == "" {
c.Next()
return
}
j := jwtUtils.NewJWT()
claims, err := j.ParseToken(token)
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrTypeInternalServer, err)
return
}
if claims.BaseClaims.IsAgent {
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/agent/") {
c.Set("claims", claims)
c.Set("authMethod", constant.AuthMethodJWT)
c.Next()
return
} else {
helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrTypeInternalServer, fmt.Errorf("err token from request"))
return
}
}
if strings.HasPrefix(c.Request.URL.Path, "/api/v2/agent/") {
helper.ErrorWithDetail(c, constant.CodeErrUnauthorized, constant.ErrTypeInternalServer, fmt.Errorf("err token from request"))
return
}
2024-07-19 19:04:11 +08:00
c.Set("claims", claims)
c.Set("authMethod", constant.AuthMethodJWT)
c.Next()
}
}