-
Notifications
You must be signed in to change notification settings - Fork 80
/
config.go
101 lines (85 loc) · 2.17 KB
/
config.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package google
import (
"errors"
"net/http"
"net/url"
"strings"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
storage "google.golang.org/api/storage/v1"
"github.com/graymeta/stow"
)
// Kind represents the name of the location/storage type.
const Kind = "google"
const (
// The service account json blob
ConfigJSON = "json"
ConfigProjectId = "project_id"
ConfigScopes = "scopes"
)
func init() {
validatefn := func(config stow.Config) error {
_, ok := config.Config(ConfigJSON)
if !ok {
return errors.New("missing JSON configuration")
}
_, ok = config.Config(ConfigProjectId)
if !ok {
return errors.New("missing Project ID")
}
return nil
}
makefn := func(config stow.Config) (stow.Location, error) {
_, ok := config.Config(ConfigJSON)
if !ok {
return nil, errors.New("missing JSON configuration")
}
_, ok = config.Config(ConfigProjectId)
if !ok {
return nil, errors.New("missing Project ID")
}
// Create a new client
client, err := newGoogleStorageClient(config)
if err != nil {
return nil, err
}
// Create a location with given config and client
loc := &Location{
config: config,
client: client,
}
return loc, nil
}
kindfn := func(u *url.URL) bool {
return u.Scheme == Kind
}
stow.Register(Kind, makefn, kindfn, validatefn)
}
// Attempts to create a session based on the information given.
func newGoogleStorageClient(config stow.Config) (*storage.Service, error) {
json, _ := config.Config(ConfigJSON)
var httpClient *http.Client
scopes := []string{storage.DevstorageReadWriteScope}
if s, ok := config.Config(ConfigScopes); ok && s != "" {
scopes = strings.Split(s, ",")
}
if json != "" {
jwtConf, err := google.JWTConfigFromJSON([]byte(json), scopes...)
if err != nil {
return nil, err
}
httpClient = jwtConf.Client(context.Background())
} else {
creds, err := google.FindDefaultCredentials(context.Background(), strings.Join(scopes, ","))
if err != nil {
return nil, err
}
httpClient = oauth2.NewClient(context.Background(), creds.TokenSource)
}
service, err := storage.New(httpClient)
if err != nil {
return nil, err
}
return service, nil
}