This repository was archived by the owner on Aug 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
77 lines (64 loc) · 1.71 KB
/
auth.go
File metadata and controls
77 lines (64 loc) · 1.71 KB
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
package gcloudsql
import (
"encoding/json"
"os/exec"
"strings"
"sync"
"time"
)
// AccessToken : Struct for storing relevant gcloud access token data
type AccessToken struct {
lock *sync.Mutex
token string
expireTime time.Time
IssuedTo string `json:"issued_to"`
Audience string `json:"audience"`
UserID string `json:"user_id"`
Scope string `json:"scope"`
ExpiresIn int `json:"expires_in"`
Email string `json:"email"`
VerifiedEmail bool `json:"verified_email"`
AccessType string `json:"access_type"`
}
// GenerateAccessToken : Generates an AccessToken by using the gcloud command
func GenerateAccessToken() (at AccessToken, err error) {
var accessTokenCmd = []string{"auth", "application-default", "print-access-token"}
output, err := exec.Command("gcloud", accessTokenCmd...).Output()
if err != nil {
return
}
at = AccessToken{
token: strings.TrimSpace(string(output)),
}
requestTmpl := TemplatedHTTPRequest{
urlText: tokenRequestURLTemplate,
urlData: struct {
AccessToken string
}{
at.token,
},
headers: map[string]string{
"Content-Type": "application/json",
},
}
request, err := NewHTTPRequest("GET", requestTmpl)
if err != nil {
return
}
err = ParseHTTPRequest(request, &at)
return
}
// IsExpired : returns whether or not the AccessToken is expired
func (at AccessToken) IsExpired() bool {
return at.expireTime.Before(time.Now())
}
func (at AccessToken) String() string {
bytes, _ := json.MarshalIndent(at, "", "\t")
return string(bytes)
}
func (at *AccessToken) getExpireTime() {
at.lock.Lock()
at.expireTime = time.Now()
at.expireTime.Add(time.Duration(at.ExpiresIn) * time.Second)
at.lock.Unlock()
}