:art:用户接口处理完毕

This commit is contained in:
coward
2024-03-07 15:11:29 +08:00
parent 1c0a128855
commit 097505df99
17 changed files with 2079 additions and 59 deletions

View File

@@ -1,9 +1,15 @@
package compoment
import (
"context"
"errors"
"fmt"
"gitee.ltd/lxh/logger/log"
"github.com/golang-jwt/jwt/v5"
"strings"
"time"
"wireguard-dashboard/client"
"wireguard-dashboard/constant"
)
const Secret = "IK8MSs76Pb2VJxleTDadf1Wzu3h9QROLv0XtmnCUErYgBG5wAyjk4cioqFZHNpZG"
@@ -36,6 +42,12 @@ func (j JwtClaims) GenerateToken(userId string) (token string, err error) {
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err = t.SignedString([]byte(Secret))
if err != nil {
log.Errorf("生成token失败: %v", err.Error())
return "", errors.New("生成token失败")
}
client.Redis.Set(context.Background(), fmt.Sprintf("%s:%s", constant.Token, userId), token, 7*time.Hour)
return
}
@@ -52,8 +64,28 @@ func (JwtClaims) ParseToken(token string) (*JwtClaims, error) {
})
if claims, ok := t.Claims.(*JwtClaims); ok && t.Valid {
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错误")
}
return claims, nil
} else {
return nil, err
}
}
// 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()
}