60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
|
package compoment
|
||
|
|
||
|
import (
|
||
|
"github.com/golang-jwt/jwt/v5"
|
||
|
"strings"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
const Secret = "IK8MSs76Pb2VJxleTDadf1Wzu3h9QROLv0XtmnCUErYgBG5wAyjk4cioqFZHNpZG"
|
||
|
|
||
|
type JwtClaims struct {
|
||
|
ID string `json:"id"`
|
||
|
Name string `json:"name"`
|
||
|
jwt.RegisteredClaims `json:"-"`
|
||
|
}
|
||
|
|
||
|
func JWT() JwtClaims {
|
||
|
return JwtClaims{}
|
||
|
}
|
||
|
|
||
|
// GenerateToken
|
||
|
// @description: 生成token
|
||
|
// @receiver Jwt
|
||
|
// @return token
|
||
|
// @return err
|
||
|
func (j JwtClaims) GenerateToken(userId string) (token string, err error) {
|
||
|
claims := JwtClaims{
|
||
|
ID: userId,
|
||
|
RegisteredClaims: jwt.RegisteredClaims{
|
||
|
Subject: "wireguard-dashboard",
|
||
|
ExpiresAt: jwt.NewNumericDate(time.Now().Local().Add(7 * time.Hour)),
|
||
|
NotBefore: jwt.NewNumericDate(time.Now().Local()),
|
||
|
IssuedAt: jwt.NewNumericDate(time.Now().Local()),
|
||
|
},
|
||
|
}
|
||
|
|
||
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||
|
token, err = t.SignedString([]byte(Secret))
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// ParseToken
|
||
|
// @description: 解析token
|
||
|
// @receiver Jwt
|
||
|
// @return Jwt
|
||
|
// @return error
|
||
|
func (JwtClaims) ParseToken(token string) (*JwtClaims, error) {
|
||
|
tokenStr := strings.Split(token, "Bearer ")[1]
|
||
|
|
||
|
t, err := jwt.ParseWithClaims(tokenStr, &JwtClaims{}, func(token *jwt.Token) (any, error) {
|
||
|
return []byte(Secret), nil
|
||
|
})
|
||
|
|
||
|
if claims, ok := t.Claims.(*JwtClaims); ok && t.Valid {
|
||
|
return claims, nil
|
||
|
} else {
|
||
|
return nil, err
|
||
|
}
|
||
|
}
|