auth.go
1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package middleware
import (
"fmt"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/stores/redis"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/tool"
)
type UserAuthService struct {
redis *redis.Redis
appName string
checkAuth bool
}
func NewUserAuthService(redis *redis.Redis, appName string) UserAuthService {
return UserAuthService{
redis: redis,
appName: appName,
}
}
// Refresh 刷新缓存的User Token
func (l UserAuthService) Refresh(userId int64, token string) error {
err := l.redis.Set(l.CacheKey(userId), l.Hash(token))
if err != nil {
return err
}
return nil
}
// Compare 比较当前的Token是否已经过期
func (l UserAuthService) Compare(userId int64, token string) error {
ok, err := l.redis.Exists(l.CacheKey(userId))
if err != nil {
return err
}
if !ok {
return errors.New("Token not exists.") //l.Refresh(userId, token)
}
cacheToken, err := l.redis.Get(l.CacheKey(userId))
if err != nil {
return err
}
if !l.compare(cacheToken, token) {
return errors.New("Token is expired.")
}
return nil
}
func (l UserAuthService) compare(cacheToken, token string) bool {
if len(cacheToken) == len(token) && cacheToken == token {
return true
}
if cacheToken == l.Hash(token) {
return true
}
return false
}
// Hash token哈希编码
func (l UserAuthService) Hash(token string) string {
return tool.Md5ByString(token)
}
func (l UserAuthService) CacheKey(userId int64) string {
return fmt.Sprintf("%v:cache:%v:id:%v", l.appName, "user.auth", userId)
}