Lee-WineList/oauth2/handle/token_gen.go
2023-04-27 15:56:12 +08:00

66 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handle
import (
"Lee-WineList/client"
"Lee-WineList/common/constant"
"context"
"encoding/json"
"fmt"
"git.echol.cn/loser/logger/log"
"github.com/go-oauth2/oauth2/v4"
"github.com/google/uuid"
"strings"
)
func NewAccessGenerate() *AccessGenerate {
return &AccessGenerate{}
}
type AccessGenerate struct {
}
// Token 手动实现Token生成直接生成UUID替换掉自带的那个憨得一批的长长的字符串
func (ag *AccessGenerate) Token(ctx context.Context, data *oauth2.GenerateBasic, isGenRefresh bool) (string, string, error) {
u, _ := uuid.NewUUID()
access := strings.ReplaceAll(u.String(), "-", "")
refresh := ""
if isGenRefresh {
u, _ = uuid.NewUUID()
refresh = strings.ReplaceAll(u.String(), "-", "")
}
// 生成新的,清理掉旧的
ag.clearOldToken(ctx, data.UserID)
// 返回结果
return access, refresh, nil
}
// 清理掉旧的Token和RefreshToken
func (ag *AccessGenerate) clearOldToken(ctx context.Context, userId string) {
rdsKey := constant.OAuth2RedisKey + "*-*"
// 获取所有符合条件的Key
keys, err := client.Redis.Keys(ctx, rdsKey).Result()
if err != nil {
log.Errorf("清理失败,跳过清理")
return
}
for _, key := range keys {
dataStr, err := client.Redis.Get(ctx, key).Result()
if err != nil {
continue
}
var m map[string]any
if err = json.Unmarshal([]byte(dataStr), &m); err != nil {
continue
}
// 找到匹配的数据
if m["UserID"] == userId {
// 删除AccessToken
client.Redis.Del(ctx, fmt.Sprintf("%v%v", constant.OAuth2RedisKey, m["Access"]))
client.Redis.Del(ctx, fmt.Sprintf("%v%v", constant.OAuth2RedisKey, m["Refresh"]))
client.Redis.Del(ctx, key)
continue
}
}
}