-
Notifications
You must be signed in to change notification settings - Fork 0
/
secure_storager.go
63 lines (52 loc) · 1.79 KB
/
secure_storager.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
// Package storager contains additional credential stores
// that implements the Storager interface for the shellicator lib.
package storager
import (
"encoding/base64"
"encoding/json"
"time"
"github.com/go-sharp/shellicator/errors"
"github.com/zalando/go-keyring"
"golang.org/x/oauth2"
)
// NewSecureStore creates a new secure storager.
func NewSecureStore(serviceName string) SecureStore {
return SecureStore{serviceName: serviceName}
}
// SecureStore stores and retrieves tokens in a platform dependent secure storage.
type SecureStore struct {
serviceName string
}
// RetrieveToken retrieves a token from the secure store.
func (s SecureStore) RetrieveToken(key string) (*oauth2.Token, error) {
raw, err := keyring.Get(s.serviceName, key)
if err != nil {
if err == keyring.ErrNotFound {
return nil, errors.ErrTokenNotFound
}
return nil, errors.ErrGeneric.WithWrappedError(err)
}
data, err := base64.StdEncoding.DecodeString(raw)
if err != nil {
return nil, errors.ErrGeneric.WithWrappedError(err)
}
var token oauth2.Token
if err := json.Unmarshal(data, &token); err != nil {
return nil, errors.ErrGeneric.WithWrappedError(err)
}
if token.RefreshToken == "" && !token.Expiry.After(time.Now()) {
return nil, errors.ErrTokenNotFound.WithMessage("SecureStorager: no vaild token and no refresh token found")
}
return &token, nil
}
// StoreToken stores a token in the secure store.
func (s SecureStore) StoreToken(key string, token *oauth2.Token) error {
data, err := json.Marshal(token)
if err != nil {
return errors.ErrGeneric.WithMessageAndError("secureStore set token failed", err)
}
if err := keyring.Set(s.serviceName, key, base64.StdEncoding.EncodeToString(data)); err != nil {
return errors.ErrGeneric.WithMessageAndError("secureStore set token failed", err)
}
return nil
}