-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
65 lines (54 loc) · 1.61 KB
/
auth.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 gcssync
import (
"code.google.com/p/goauth2/oauth"
"code.google.com/p/google-api-go-client/storage/v1"
"fmt"
"net/http"
)
// ServiceConfig holds all informations about the bucket and project
type ServiceConfig struct {
ProjectID string
BucketName string
}
// Client is connected to Google Cloud Storage bucket
type Client struct {
service *storage.Service
projectID string
bucketName string
}
// GetBucketname return the name of the bucket the client is connected to
func (c *Client) GetBucketname() string {
return c.bucketName
}
// NewClient connects to and authenficates against Google Cloud Storage
func NewClient(oauthConfig *oauth.Config, authCode string, serviceConfig *ServiceConfig) (*Client, error) {
transport := &oauth.Transport{
Config: oauthConfig,
Transport: http.DefaultTransport,
}
token, err := oauthConfig.TokenCache.Token()
if err != nil {
if authCode == "" {
url := oauthConfig.AuthCodeURL("")
fmt.Println("Visit URL to get a code then run again with -code=YOUR_CODE")
fmt.Println(url)
return &Client{}, fmt.Errorf("Could not get auth code")
}
token, err = transport.Exchange(authCode)
if err != nil {
return &Client{}, fmt.Errorf("Could not exchange token: %s", err.Error())
}
fmt.Printf("Token cached %s\n", oauthConfig.TokenCache)
}
transport.Token = token
httpClient := transport.Client()
service, err := storage.New(httpClient)
if err != nil {
return &Client{}, fmt.Errorf("Could not init client: %s", err.Error())
}
return &Client{
service: service,
projectID: serviceConfig.ProjectID,
bucketName: serviceConfig.BucketName,
}, nil
}