-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathauth_token.go
81 lines (71 loc) · 1.58 KB
/
auth_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
73
74
75
76
77
78
79
80
81
package coze
import (
"context"
"time"
)
type Auth interface {
Token(ctx context.Context) (string, error)
}
var (
_ Auth = &tokenAuthImpl{}
_ Auth = &jwtOAuthImpl{}
)
// tokenAuthImpl implements the Auth interface with fixed access token.
type tokenAuthImpl struct {
accessToken string
}
// NewTokenAuth creates a new token authentication instance.
func NewTokenAuth(accessToken string) Auth {
return &tokenAuthImpl{
accessToken: accessToken,
}
}
func NewJWTAuth(client *JWTOAuthClient, opt *GetJWTAccessTokenReq) Auth {
ttl := 900
if opt == nil {
return &jwtOAuthImpl{
TTL: ttl,
client: client,
}
}
if opt.TTL > 0 {
ttl = opt.TTL
}
return &jwtOAuthImpl{
TTL: ttl,
Scope: opt.Scope,
SessionName: opt.SessionName,
client: client,
}
}
// Token returns the access token.
func (r *tokenAuthImpl) Token(ctx context.Context) (string, error) {
return r.accessToken, nil
}
type jwtOAuthImpl struct {
TTL int
SessionName *string
Scope *Scope
client *JWTOAuthClient
accessToken *string
expireIn int64
}
func (r *jwtOAuthImpl) needRefresh() bool {
return r.accessToken == nil || time.Now().Unix() > r.expireIn
}
func (r *jwtOAuthImpl) Token(ctx context.Context) (string, error) {
if !r.needRefresh() {
return ptrValue(r.accessToken), nil
}
resp, err := r.client.GetAccessToken(ctx, &GetJWTAccessTokenReq{
TTL: r.TTL,
SessionName: r.SessionName,
Scope: r.Scope,
})
if err != nil {
return "", err
}
r.accessToken = ptr(resp.AccessToken)
r.expireIn = resp.ExpiresIn
return resp.AccessToken, nil
}