-
Notifications
You must be signed in to change notification settings - Fork 0
/
token_source.go
81 lines (64 loc) · 1.4 KB
/
token_source.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 appstore
import (
"crypto/ecdsa"
"fmt"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
)
type Config struct {
KeyID string
IssuerID string
PrivateKey []byte
ExpireAfter time.Duration
}
type TokenSource interface {
Token() (string, error)
}
func NewTokenSource(config Config) (TokenSource, error) {
pk, err := jwt.ParseECPrivateKeyFromPEM(config.PrivateKey)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %w", err)
}
return &tokenSource{
config: config,
pk: pk,
}, nil
}
type tokenSource struct {
sync.Mutex
config Config
pk *ecdsa.PrivateKey
bearer string
expireAt time.Time
}
func (ts *tokenSource) Token() (string, error) {
ts.Lock()
defer ts.Unlock()
if ts.isExpired() {
return ts.refresh()
}
return ts.bearer, nil
}
func (ts *tokenSource) isExpired() bool {
return time.Now().After(ts.expireAt)
}
func (ts *tokenSource) refresh() (string, error) {
iat := time.Now()
exp := iat.Add(ts.config.ExpireAfter)
token := jwt.NewWithClaims(jwt.SigningMethodES256, jwt.MapClaims{
"iss": ts.config.IssuerID,
"iat": iat.Unix(),
"exp": exp.Unix(),
"aud": "appstoreconnect-v1",
// "scope": []string{},
})
token.Header["kid"] = ts.config.KeyID
bearer, err := token.SignedString(ts.pk)
if err != nil {
return "", fmt.Errorf("failed to sign token: %w", err)
}
ts.bearer = bearer
ts.expireAt = exp
return bearer, nil
}