/
api_token_generator.go
58 lines (48 loc) · 1.49 KB
/
api_token_generator.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
package http
import (
"context"
"time"
"github.com/golang-jwt/jwt/v4"
"gopkg.in/errgo.v1"
)
type TokensService interface {
TokenExchange(ctx context.Context, token string) (string, error)
}
type APITokenGenerator struct {
APIToken string
TokensService TokensService
// Internal cache of JWT info
currentJWT string
currentJWTexp time.Time
}
type apiJWTClaims struct {
jwt.RegisteredClaims
}
func NewAPITokenGenerator(tokensService TokensService, apiToken string) *APITokenGenerator {
return &APITokenGenerator{
APIToken: apiToken,
TokensService: tokensService,
}
}
func (t *APITokenGenerator) GetAccessToken(ctx context.Context) (string, error) {
// Ask for a new JWT if there wasn't any or if the current token will expire in less than 5 minutes
if t.currentJWTexp.IsZero() || time.Until(t.currentJWTexp) < 5*time.Minute {
jwtToken, err := t.TokensService.TokenExchange(ctx, t.APIToken)
if err != nil {
return "", errgo.Notef(err, "fail to get access token")
}
token, err := jwt.ParseWithClaims(jwtToken, &apiJWTClaims{}, nil)
// If token is nil, nothing has been parsed, if it's not, err will be a
// ValidatingError we want to ignore
if token == nil {
return "", errgo.Notef(err, "fail to parse jwt token")
}
if claims, ok := token.Claims.(*apiJWTClaims); ok {
t.currentJWTexp = claims.ExpiresAt.Time
} else {
return "", errgo.Notef(err, "invalid exp date for jwt token: %v", token.Claims)
}
t.currentJWT = jwtToken
}
return t.currentJWT, nil
}