1Panel/backend/middleware/jwt.go

45 lines
1.2 KiB
Go
Raw Normal View History

2022-08-16 23:30:23 +08:00
package middleware
import (
2022-09-08 18:47:15 +08:00
"strconv"
2022-08-16 23:30:23 +08:00
"time"
"github.com/1Panel-dev/1Panel/backend/app/api/v1/helper"
"github.com/1Panel-dev/1Panel/backend/app/repo"
"github.com/1Panel-dev/1Panel/backend/constant"
"github.com/1Panel-dev/1Panel/backend/global"
jwtUtils "github.com/1Panel-dev/1Panel/backend/utils/jwt"
2022-08-16 23:30:23 +08:00
"github.com/golang-jwt/jwt/v4"
"github.com/gin-gonic/gin"
)
func JwtAuth() gin.HandlerFunc {
return func(c *gin.Context) {
c.Set("authMethod", "")
2022-09-08 18:47:15 +08:00
token := c.Request.Header.Get(constant.JWTHeaderName)
2022-08-16 23:30:23 +08:00
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.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
2022-09-08 18:47:15 +08:00
settingRepo := repo.NewISettingRepo()
setting, err := settingRepo.Get(settingRepo.WithByKey("SessionTimeout"))
if err != nil {
global.LOG.Errorf("create operation record failed, err: %v", err)
}
lifeTime, _ := strconv.Atoi(setting.Value)
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(lifeTime)))
2022-08-16 23:30:23 +08:00
}
c.Set("claims", claims)
c.Set("authMethod", constant.AuthMethodJWT)
c.Next()
}
}