/
token.go
72 lines (57 loc) · 2.05 KB
/
token.go
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
69
70
71
72
// @Author: Ciusyan 2023/2/6
package impl
import (
"context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"time"
"github.com/Go-To-Byte/DouSheng/dou-kit/constant"
"github.com/Go-To-Byte/DouSheng/auth-service/apps/token"
)
var (
DefaultTokenDuration = 10 * time.Minute
)
func (s *tokenServiceImpl) IssueToken(ctx context.Context, req *token.IssueTokenRequest) (*token.Token, error) {
newToken := token.NewToken(req, DefaultTokenDuration)
_, err := s.col.InsertOne(ctx, newToken)
if err != nil {
return nil, status.Errorf(codes.Unavailable, "颁发Token失败:%s", err.Error())
}
return newToken, nil
}
func (s *tokenServiceImpl) ValidateToken(ctx context.Context, req *token.ValidateTokenRequest) (*token.Token, error) {
// 获取 Token
tk, err := s.get(ctx, req.AccessToken)
if err != nil {
s.log.Errorf("token: ValidateToken出现错误:%s", err.Error())
return nil, status.Error(codes.Unknown,
constant.Code2Msg(constant.ERROR_TOKEN_VALIDATE))
}
// 校验过期时间[采取双Token的机制]
if !tk.IsExpired(tk.AccessTokenExpiredAt) {
return tk, nil
}
// 来到这里说明 Access_Token 过期了,再看看 Refresh_Token
if tk.IsExpired(tk.RefreshTokenExpiredAt) {
return nil, status.Error(codes.Unauthenticated,
constant.Code2Msg(constant.WRONG_TOKEN_EXPIRED))
}
// 来到这里说明 Access_Token 过期了,Refresh_Token 没过期
if err = s.update(ctx, tk.Extend(DefaultTokenDuration)); err != nil {
s.log.Errorf("token: ValidateToken出现错误:%s", err.Error())
return nil, status.Error(codes.Unknown,
constant.Code2Msg(constant.ERROR_TOKEN_VALIDATE))
}
return tk, nil
}
func (s *tokenServiceImpl) GetUIDFromTk(ctx context.Context, req *token.ValidateTokenRequest) (*token.UIDResponse, error) {
tk, err := s.get(ctx, req.AccessToken)
if err != nil {
s.log.Errorf("token: ValidateToken出现错误:%s", err.Error())
return nil, status.Error(codes.Unknown,
constant.Code2Msg(constant.ERROR_ACQUIRE))
}
resp := token.NewUIDResponse()
resp.UserId = tk.GetUserId()
return resp, nil
}