This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
token_cache_gcs.go
80 lines (65 loc) · 1.7 KB
/
token_cache_gcs.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
package gcpvault
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"cloud.google.com/go/storage"
)
type TokenCacheGCS struct {
cfg *Config
}
func (t TokenCacheGCS) GetToken(ctx context.Context) (*Token, error) {
if t.cfg.TokenCache != nil {
bucket := t.cfg.TokenCacheStorageGCS
object := t.cfg.TokenCacheKeyName
client, err := storage.NewClient(ctx)
if err != nil {
return nil, fmt.Errorf("error creating new storage client: %v", err)
}
defer client.Close()
rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
if err != nil {
// swallowing the error here since we may not have cached a token yet
return nil, nil
}
defer rc.Close()
data, err := ioutil.ReadAll(rc)
if err != nil {
return nil, fmt.Errorf("error reading: %v", err)
}
var token Token
err = json.Unmarshal(data, &token)
if err != nil {
return nil, err
}
return &token, nil
}
return nil, nil
}
func (t TokenCacheGCS) SaveToken(ctx context.Context, token Token) error {
if t.cfg.TokenCache != nil {
bucket := t.cfg.TokenCacheStorageGCS
object := t.cfg.TokenCacheKeyName
client, err := storage.NewClient(ctx)
if err != nil {
return fmt.Errorf("error creating new storage client: %v", err)
}
defer client.Close()
// Upload an object with storage.Writer.
wc := client.Bucket(bucket).Object(object).NewWriter(ctx)
wc.ContentType = "application/json"
payload, err := json.Marshal(&token)
if err != nil {
return fmt.Errorf("error mashaling: %v", err)
}
if _, err := wc.Write(payload); err != nil {
return fmt.Errorf("error writing: %v", err)
}
if err := wc.Close(); err != nil {
return fmt.Errorf("error closing: %v", err)
}
return nil
}
return nil
}