-
Notifications
You must be signed in to change notification settings - Fork 14
/
oauth.go
296 lines (283 loc) · 9.04 KB
/
oauth.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// Package main (oauth.go) :
// Get accesstoken using refreshtoken, and confirm condition of accesstoken.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"ggsrun/utl"
gettokenbyserviceaccount "github.com/tanaikech/go-gettokenbyserviceaccount"
)
// Goauth :
func (a *AuthContainer) goauth() *AuthContainer {
if a.useServiceAccount != "" {
if err := a.getAtFromSa(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
a.Msg = append(a.Msg, "Service Account was used.")
return a
}
if len(a.GgsrunCfg.Clientid) > 0 &&
len(a.GgsrunCfg.Clientsecret) > 0 &&
len(a.GgsrunCfg.Refreshtoken) > 0 {
if (a.InitVal.pstart.Unix()-a.GgsrunCfg.Expiresin) > 0 ||
len(a.GgsrunCfg.Accesstoken) == 0 {
a.getAtoken().makecfgfile()
} else {
if a.InitVal.update {
a.makecfgfile()
}
}
} else {
a.readClientSecret().getNewAccesstoken().makecfgfile()
}
a.Msg = append(a.Msg, "Access Token was was used.")
return a
}
// ReAuth :
func (a *AuthContainer) reAuth() {
a.readClientSecret().getNewAccesstoken().makecfgfile()
}
// makecfgfile :
func (a *AuthContainer) makecfgfile() {
btok, _ := json.MarshalIndent(a.GgsrunCfg, "", "\t")
var path string
if a.InitVal.usedDir == "work" {
path = a.InitVal.workdir
} else if a.InitVal.usedDir == "env" {
path = a.InitVal.cfgdir
} else {
fmt.Fprintf(os.Stderr, "Error: directory. '%s'\n", a.InitVal.usedDir)
os.Exit(1)
}
ioutil.WriteFile(filepath.Join(path, cfgFile), btok, 0777)
}
// getAtoken : Retrieves accesstoken from refreshtoken.
func (a *AuthContainer) getAtoken() *AuthContainer {
a.Msg = append(a.Msg, "Got a new accesstoken.")
values := url.Values{}
values.Set("client_id", a.GgsrunCfg.Clientid)
values.Set("client_secret", a.GgsrunCfg.Clientsecret)
values.Set("refresh_token", a.GgsrunCfg.Refreshtoken)
values.Set("grant_type", "refresh_token")
r := &utl.RequestParams{
Method: "POST",
APIURL: oauthurl + "token",
Data: strings.NewReader(values.Encode()),
Contenttype: "application/x-www-form-urlencoded",
Accesstoken: "",
Dtime: 10,
}
body, err := r.FetchAPI()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v. %s\n", err, body)
fmt.Println("Hint: If you use old ggsrun.cfg, please remove it and run 'ggsrun auth'. Then try again.")
os.Exit(1)
}
json.Unmarshal(body, &a.Atoken)
a.GgsrunCfg.Accesstoken = a.Atoken.Accesstoken
a.GgsrunCfg.Expiresin = a.chkAtoken() - 360 // 6 minutes as adjustment time
return a
}
// chkAtoken : For AuthContainer
func (a *AuthContainer) chkAtoken() int64 {
r := &utl.RequestParams{
Method: "GET",
APIURL: chkatutl + "tokeninfo?access_token=" + a.GgsrunCfg.Accesstoken,
Data: nil,
Contenttype: "application/x-www-form-urlencoded",
Accesstoken: "",
Dtime: 10,
}
body, err := r.FetchAPI()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v. ", err)
os.Exit(1)
}
json.Unmarshal(body, &a.ChkAt)
if len(a.ChkAt.Error) > 0 {
a.getAtoken()
}
exp, _ := strconv.ParseInt(a.ChkAt.Exp, 10, 64)
return exp
}
// chkAtoken : For ExecutionContainer
func (e *ExecutionContainer) chkAtoken() *ChkAt {
r := &utl.RequestParams{
Method: "GET",
APIURL: chkatutl + "tokeninfo?access_token=" + e.GgsrunCfg.Accesstoken,
Data: nil,
Contenttype: "application/x-www-form-urlencoded",
Accesstoken: "",
Dtime: 10,
}
body, _ := r.FetchAPI()
var c ChkAt
json.Unmarshal(body, &c)
return &c
}
func (a *AuthContainer) chkRedirectURI() bool {
for _, e := range a.Cs.Cid.Redirecturis {
if strings.Contains(e, "localhost") {
return true
}
}
return false
}
func (a *AuthContainer) getCode() (string, error) {
p := a.InitVal.Port
if !a.chkRedirectURI() {
return "", fmt.Errorf("go manual mode")
}
fmt.Printf("\n### This is a automatic input mode.\n### Please follow opened browser, login Google and click authentication.\n### It will move to a manual mode if you wait for 30 seconds under this situation.\n")
a.Cs.Cid.Redirecturis = append(a.Cs.Cid.Redirecturis, "http://localhost:"+strconv.Itoa(p)+"/")
codepara := url.Values{}
codepara.Set("client_id", a.Cs.Cid.ClientID)
codepara.Set("redirect_uri", a.Cs.Cid.Redirecturis[len(a.Cs.Cid.Redirecturis)-1])
codepara.Set("scope", strings.Join(a.GgsrunCfg.Scopes, " "))
codepara.Set("response_type", "code")
codepara.Set("approval_prompt", "force")
codepara.Set("access_type", "offline")
codeurl := oauthurl + "auth?" + codepara.Encode()
s := &serverInfToGetCode{
Response: make(chan authCode, 1),
Start: make(chan bool, 1),
End: make(chan bool, 1),
}
defer func() {
s.End <- true
}()
go func(port int) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
if len(code) == 0 {
fmt.Fprintf(w, `<html><head><title>ggsrun status</title></head><body><p>Erorr.</p></body></html>`)
s.Response <- authCode{Err: fmt.Errorf("not found code")}
return
}
fmt.Fprintf(w, `<html><head><title>ggsrun status</title></head><body><p>The authentication was done. Please close this page.</p></body></html>`)
s.Response <- authCode{Code: code}
})
var err error
Listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
if err != nil {
s.Response <- authCode{Err: err}
return
}
server := http.Server{}
server.Handler = mux
go server.Serve(Listener)
s.Start <- true
<-s.End
Listener.Close()
s.Response <- authCode{Err: err}
// return
}(p)
<-s.Start
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("open", strings.Replace(codeurl, "&", `\&`, -1))
case "linux":
cmd = exec.Command("xdg-open", strings.Replace(codeurl, "&", `\&`, -1))
case "windows":
cmd = exec.Command("cmd", "/c", "start", strings.Replace(codeurl, "&", `^&`, -1))
default:
return "", fmt.Errorf("go manual mode")
}
if err := cmd.Start(); err != nil {
return "", fmt.Errorf("go manual mode")
}
var result authCode
select {
case result = <-s.Response:
case <-time.After(time.Duration(30) * time.Second): // After 30 s, move to manual mode.
return "", fmt.Errorf("go manual mode")
}
if result.Err != nil {
return "", fmt.Errorf("go manual mode")
}
return result.Code, nil
}
// getNewAccesstoken : Retrieve accesstoken when there is no refreshtoken.
func (a *AuthContainer) getNewAccesstoken() *AuthContainer {
var code string
var err error
fmt.Printf("\n### Since %s is not found, the authorization process is launched.", cfgFile)
code, err = a.getCode()
if err != nil {
codepara := url.Values{}
codepara.Set("client_id", a.Cs.Cid.ClientID)
codepara.Set("redirect_uri", a.Cs.Cid.Redirecturis[0])
codepara.Set("scope", strings.Join(a.GgsrunCfg.Scopes, " "))
codepara.Set("response_type", "code")
codepara.Set("approval_prompt", "force")
codepara.Set("access_type", "offline")
codeurl := oauthurl + "auth?" + codepara.Encode()
fmt.Printf("\n### This is a manual input mode.\n### Please input code retrieved by importing following URL to your browser.\n\n"+
"[URL]==> %v\n"+
"[CODE]==>", codeurl)
if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Error: %v.\n", err)
}
a.Cs.Cid.Redirecturis = append(a.Cs.Cid.Redirecturis, a.Cs.Cid.Redirecturis[0])
}
tokenparams := url.Values{}
tokenparams.Set("client_id", a.Cs.Cid.ClientID)
tokenparams.Set("client_secret", a.Cs.Cid.Clientsecret)
tokenparams.Set("redirect_uri", a.Cs.Cid.Redirecturis[len(a.Cs.Cid.Redirecturis)-1])
tokenparams.Set("code", code)
tokenparams.Set("grant_type", "authorization_code")
r := &utl.RequestParams{
Method: "POST",
APIURL: oauthurl + "token",
Data: strings.NewReader(tokenparams.Encode()),
Contenttype: "application/x-www-form-urlencoded",
Accesstoken: "",
Dtime: 10,
}
body, err := r.FetchAPI()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: [ %v ] - Code is wrong. ", err)
os.Exit(1)
}
json.Unmarshal(body, &a.Atoken)
a.GgsrunCfg.Clientid = a.Cs.Cid.ClientID
a.GgsrunCfg.Clientsecret = a.Cs.Cid.Clientsecret
a.GgsrunCfg.Refreshtoken = a.Atoken.Refreshtoken
a.GgsrunCfg.Accesstoken = a.Atoken.Accesstoken
a.GgsrunCfg.Expiresin = a.chkAtoken() - 360 // 6 minutes as adjustment time
return a
}
// getAtFromSa : Retrieve access token from Service Account
func (a *AuthContainer) getAtFromSa() error {
credentialsData, err := ioutil.ReadFile(a.useServiceAccount)
if err != nil {
return err
}
para := struct {
PrivateKey string `json:"private_key"`
ClientEmail string `json:"client_email"`
}{}
json.Unmarshal(credentialsData, ¶)
scopes := strings.Join(a.Scopes, " ")
res, err := gettokenbyserviceaccount.Do(para.PrivateKey, para.ClientEmail, "", scopes)
if err != nil {
return err
}
a.GgsrunCfg.Accesstoken = res.AccessToken
return nil
}