67 lines
1.8 KiB
Go
67 lines
1.8 KiB
Go
package cache_user
|
|
|
|
import (
|
|
"fmt"
|
|
"servicebase/pkg/cache"
|
|
"servicebase/pkg/tools"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/anxpp/beego/logs"
|
|
"github.com/anxpp/common-utils/str"
|
|
)
|
|
|
|
const key = "user:models"
|
|
const keyToken = "user:token"
|
|
|
|
const ACCESSTOKEN_KEY_PREV = "ACCESSTOKEN_"
|
|
const ACCESSTOKEN_EXPIRE_DURATION = time.Hour * 24 * 180
|
|
|
|
func IdByToken(token string) (userId string) {
|
|
if len(token) == 0 {
|
|
return
|
|
}
|
|
var e error
|
|
if userId, e = cache.CommonClient().HGet(cache.Ctx(), keyToken, token).Result(); e != nil || len(userId) == 0 {
|
|
userId, e = cache.CommonClient().Get(cache.Ctx(), ACCESSTOKEN_KEY_PREV+token).Result()
|
|
if e != nil {
|
|
logs.Error("GetUserIdByAccessToken redisError=%v token=%v", e.Error(), token)
|
|
return
|
|
} else if len(userId) > 0 {
|
|
// 迁移token
|
|
ttl, err := cache.CommonClient().TTL(cache.Ctx(), ACCESSTOKEN_KEY_PREV+token).Result()
|
|
if err != nil {
|
|
return
|
|
}
|
|
value := fmt.Sprintf("%s#%s", userId, str.TimeToString(time.Now().Add(ttl)))
|
|
if err := cache.CommonClient().HSet(cache.Ctx(), keyToken, token, value).Err(); err == nil {
|
|
cache.CommonClient().Del(cache.Ctx(), ACCESSTOKEN_KEY_PREV+token)
|
|
}
|
|
}
|
|
} else {
|
|
arr := strings.Split(userId, "#")
|
|
if len(arr) != 2 {
|
|
_ = IdTokenDel(token)
|
|
return ""
|
|
}
|
|
over := tools.StrToDateTime(arr[1])
|
|
if over.Before(time.Now()) {
|
|
_ = IdTokenDel(token)
|
|
return ""
|
|
}
|
|
userId = arr[0]
|
|
}
|
|
return
|
|
}
|
|
|
|
func IdTokenSet(token, userId string) (e error) {
|
|
value := fmt.Sprintf("%s#%s", userId, str.TimeToString(time.Now().Add(ACCESSTOKEN_EXPIRE_DURATION)))
|
|
return cache.CommonClient().HSet(cache.Ctx(), keyToken, token, value).Err()
|
|
}
|
|
|
|
func IdTokenDel(token string) (e error) {
|
|
_, e = cache.CommonClient().HDel(cache.Ctx(), keyToken, token).Result()
|
|
cache.CommonClient().Del(cache.Ctx(), ACCESSTOKEN_KEY_PREV+token)
|
|
return
|
|
}
|