-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
81 lines (61 loc) · 1.71 KB
/
handler.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
73
74
75
76
77
78
79
80
81
package protos
import (
"context"
"github.com/golang-jwt/jwt"
"time"
api "token/services/protos/kitex_gen/api"
)
var jwtSecret = []byte("go is the best language in the world!")
type UserJwtClaims struct {
*jwt.StandardClaims
//用户编号
id int64
}
// TokenServiceImpl implements the last service interface defined in the IDL.
type TokenServiceImpl struct{}
// UserAuthentication implements the TokenServiceImpl interface.
func (s *TokenServiceImpl) UserAuthentication(ctx context.Context, req *api.DouyinUserAuthenticationRequest) (resp *api.DouyinUserAuthenticationResponse, err error) {
resp = new(api.DouyinUserAuthenticationResponse)
// 鉴权
token := req.UserToken
if token == "" {
resp.UserId = -1
err = nil
return
}
claims, err := jwt.ParseWithClaims(token, &UserJwtClaims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil {
resp.UserId = -1
return
}
if claims == nil {
resp.UserId = -1
return
}
tokenClaim, ok := claims.Claims.(*UserJwtClaims)
// 格式正确并有效
if ok && claims.Valid {
resp.UserId = tokenClaim.id
}
return
}
// UserGetToken implements the TokenServiceImpl interface.
func (s *TokenServiceImpl) UserGetToken(ctx context.Context, req *api.DouyinUserGetTokenRequest) (resp *api.DouyinUserGetTokenResponse, err error) {
resp = new(api.DouyinUserGetTokenResponse)
id := req.UserId
expireTime := time.Now().Add(time.Hour).Unix()
claims := UserJwtClaims{
&jwt.StandardClaims{
ExpiresAt: expireTime,
Issuer: "tiktok",
},
id,
}
unsignedToken := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// ad salt
signedToken, err := unsignedToken.SignedString(jwtSecret)
resp.UserToken = signedToken
return
}