2022-08-16 15:30:23 +00:00
|
|
|
package jwt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2023-02-10 08:10:40 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/app/repo"
|
2022-10-17 08:32:31 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
2022-08-16 15:30:23 +00:00
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt/v4"
|
|
|
|
)
|
|
|
|
|
|
|
|
type JWT struct {
|
|
|
|
SigningKey []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
type JwtRequest struct {
|
|
|
|
BaseClaims
|
|
|
|
BufferTime int64
|
|
|
|
jwt.RegisteredClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
type CustomClaims struct {
|
|
|
|
BaseClaims
|
|
|
|
BufferTime int64
|
|
|
|
jwt.RegisteredClaims
|
|
|
|
}
|
|
|
|
|
|
|
|
type BaseClaims struct {
|
|
|
|
ID uint
|
|
|
|
Name string
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewJWT() *JWT {
|
2023-02-10 08:10:40 +00:00
|
|
|
settingRepo := repo.NewISettingRepo()
|
|
|
|
jwtSign, _ := settingRepo.Get(settingRepo.WithByKey("JWTSigningKey"))
|
2022-08-16 15:30:23 +00:00
|
|
|
return &JWT{
|
2023-02-10 08:10:40 +00:00
|
|
|
[]byte(jwtSign.Value),
|
2022-08-16 15:30:23 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-08 10:47:15 +00:00
|
|
|
func (j *JWT) CreateClaims(baseClaims BaseClaims, ttl int) CustomClaims {
|
2022-08-16 15:30:23 +00:00
|
|
|
claims := CustomClaims{
|
|
|
|
BaseClaims: baseClaims,
|
2022-09-08 10:47:15 +00:00
|
|
|
BufferTime: constant.JWTBufferTime,
|
2022-08-16 15:30:23 +00:00
|
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
2022-09-08 10:47:15 +00:00
|
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(ttl))),
|
|
|
|
Issuer: constant.JWTIssuer,
|
2022-08-16 15:30:23 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
return claims
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j *JWT) CreateToken(request CustomClaims) (string, error) {
|
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, &request)
|
|
|
|
return token.SignedString(j.SigningKey)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j *JWT) ParseToken(tokenStr string) (*JwtRequest, error) {
|
|
|
|
token, err := jwt.ParseWithClaims(tokenStr, &JwtRequest{}, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
return j.SigningKey, nil
|
|
|
|
})
|
|
|
|
if err != nil || token == nil {
|
|
|
|
return nil, constant.ErrTokenParse
|
|
|
|
}
|
|
|
|
if claims, ok := token.Claims.(*JwtRequest); ok && token.Valid {
|
|
|
|
return claims, nil
|
|
|
|
}
|
|
|
|
return nil, constant.ErrTokenParse
|
|
|
|
}
|