-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.go
65 lines (52 loc) · 1.26 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
package rest
import (
"context"
"errors"
)
type Token struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
Type string `json:"token_type"`
ClientID string
Expires int `json:"expires_in"`
}
type tokenValue int
type withToken struct {
context.Context
token *Token
}
var (
ErrNoClientID = errors.New("no client_id has been provided for token renewal")
ErrNoRefreshToken = errors.New("no refresh token is available and access token has expired")
)
func (w *withToken) Value(v any) any {
if _, ok := v.(tokenValue); ok {
return w.token
}
return w.Context.Value(v)
}
func (t *Token) Use(ctx context.Context) context.Context {
return &withToken{ctx, t}
}
func (t *Token) renew(ctx context.Context) error {
// perform renew of token via OAuth2:token endpoint
ctx = &withToken{ctx, nil} // set token to nil
if t.ClientID == "" {
return ErrNoClientID
}
if t.RefreshToken == "" {
return ErrNoRefreshToken
}
req := map[string]any{
"grant_type": "refresh_token",
"client_id": t.ClientID,
"refresh_token": t.RefreshToken,
"noraw": true,
}
err := Apply(ctx, "OAuth2:token", "POST", req, t)
if err != nil {
return err
}
// Apply will have updated AccessToken
return nil
}