wireguard-dashboard/component/jwt.go

95 lines
2.4 KiB
Go
Raw Normal View History

2024-03-07 17:32:38 +08:00
package component
2024-03-07 11:03:46 +08:00
import (
2024-03-07 15:11:29 +08:00
"context"
"errors"
"fmt"
"gitee.ltd/lxh/logger/log"
2024-03-07 11:03:46 +08:00
"github.com/golang-jwt/jwt/v5"
"strings"
"time"
2024-03-07 15:11:29 +08:00
"wireguard-dashboard/client"
"wireguard-dashboard/constant"
2024-03-07 11:03:46 +08:00
)
const Secret = "IK8MSs76Pb2VJxleTDadf1Wzu3h9QROLv0XtmnCUErYgBG5wAyjk4cioqFZHNpZG"
type JwtClaims struct {
ID string `json:"id"`
jwt.RegisteredClaims `json:"-"`
}
func JWT() JwtClaims {
return JwtClaims{}
}
// GenerateToken
// @description: 生成token
// @receiver Jwt
// @return token
// @return err
2024-03-13 17:05:02 +08:00
func (j JwtClaims) GenerateToken(userId string) (token string, expireTime *jwt.NumericDate, err error) {
timeNow := time.Now().Local()
expireTime = jwt.NewNumericDate(timeNow.Add(7 * time.Hour))
notBefore := jwt.NewNumericDate(timeNow)
issuedAt := jwt.NewNumericDate(timeNow)
2024-03-07 11:03:46 +08:00
claims := JwtClaims{
ID: userId,
RegisteredClaims: jwt.RegisteredClaims{
Subject: "wireguard-dashboard",
2024-03-13 17:05:02 +08:00
ExpiresAt: expireTime,
NotBefore: notBefore,
IssuedAt: issuedAt,
2024-03-07 11:03:46 +08:00
},
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err = t.SignedString([]byte(Secret))
2024-03-07 15:11:29 +08:00
if err != nil {
log.Errorf("生成token失败: %v", err.Error())
2024-03-13 17:05:02 +08:00
return "", nil, errors.New("生成token失败")
2024-03-07 15:11:29 +08:00
}
client.Redis.Set(context.Background(), fmt.Sprintf("%s:%s", constant.Token, userId), token, 7*time.Hour)
2024-03-07 11:03:46 +08:00
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 {
2024-03-07 15:11:29 +08:00
userToken, err := client.Redis.Get(context.Background(), fmt.Sprintf("%s:%s", constant.Token, claims.ID)).Result()
if err != nil {
log.Errorf("缓存中用户[%s]的token查找失败: %v", claims.ID, err.Error())
return nil, errors.New("token不存在")
}
if userToken != tokenStr {
log.Errorf("token不一致")
return nil, errors.New("token错误")
}
2024-03-07 11:03:46 +08:00
return claims, nil
} else {
return nil, err
}
}
2024-03-07 15:11:29 +08:00
// Logout
// @description: 退出登陆
// @receiver JwtClaims
// @param userId
// @return err
func (j JwtClaims) Logout(userId string) (err error) {
return client.Redis.Del(context.Background(), fmt.Sprintf("%s:%s", constant.Token, userId)).Err()
}