-
Notifications
You must be signed in to change notification settings - Fork 215
/
login.go
258 lines (235 loc) · 6.23 KB
/
login.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
package main
import (
"errors"
"fmt"
"net/url"
"os"
"time"
"github.com/dickeyxxx/speakeasy"
"github.com/toqueteos/webbrowser"
)
var loginTopic = &Topic{
Name: "login",
Description: "login with your Heroku credentials.",
}
var loginCmd = &Command{
Topic: "login",
Description: "login with your Heroku credentials.",
Flags: []Flag{
{Name: "sso", Description: "login for enterprise users under SSO"},
},
Run: login,
}
var authLoginCmd = &Command{
Topic: "auth",
Command: "login",
Description: "login with your Heroku credentials.",
Flags: []Flag{
{Name: "sso", Description: "login for enterprise users under SSO"},
},
Run: login,
}
func login(ctx *Context) {
if os.Getenv("HEROKU_API_KEY") != "" {
Warn("HEROKU_API_KEY is set")
}
if ctx.Flags["sso"] == true {
ssoLogin()
} else {
interactiveLogin()
}
}
func ssoLogin() {
url := os.Getenv("SSO_URL")
if url == "" {
org := os.Getenv("HEROKU_ORGANIZATION")
for org == "" {
org = getString("Enter your organization name: ")
}
url = "https://sso.heroku.com/saml/" + org + "/init?cli=true"
}
Err("Opening browser for login...")
err := webbrowser.Open(url)
if err != nil {
Errln(" " + err.Error() + ".\nNavigate to " + cyan(url))
} else {
Errln(" done")
}
token := getPassword("Enter your access token (typing will be hidden): ")
user := getUserFromToken(token)
if user == "" {
ExitIfError(errors.New("Access token invalid."), false)
}
saveOauthToken(user, token)
Println("Logged in as " + cyan(user))
}
func getUserFromToken(token string) string {
req := apiRequest(token)
req.Method = "GET"
req.Uri = req.Uri + "/account"
res, err := req.Do()
ExitIfError(err, false)
if res.StatusCode != 200 {
return ""
}
var doc map[string]interface{}
res.Body.FromJsonTo(&doc)
return doc["email"].(string)
}
func interactiveLogin() {
if apiHost() == "api.heroku.com" {
Println("Enter your Heroku credentials.")
} else {
Printf("Enter your Heroku credentials for %s.\n", apiHost())
}
email := getString("Email: ")
password := getPassword("Password (typing will be hidden): ")
token, err := v2login(email, password, "")
// TODO: use createOauthToken (v3 API)
// token, err := createOauthToken(email, password, "")
ExitIfError(err, false)
saveOauthToken(email, token)
Println("Logged in as " + cyan(email))
}
func saveOauthToken(email, token string) {
netrc := getNetrc()
netrc.RemoveMachine(apiHost())
netrc.RemoveMachine(httpGitHost())
netrc.AddMachine(apiHost(), email, token)
netrc.AddMachine(httpGitHost(), email, token)
ExitIfError(netrc.Save(), false)
}
func getString(prompt string) string {
var s string
Err(prompt)
if _, err := fmt.Scanln(&s); err != nil {
if err.Error() == "unexpected newline" {
return getString(prompt)
}
if err.Error() == "EOF" {
Errln()
os.Exit(1)
}
ExitIfError(err, false)
}
return s
}
func getPassword(prompt string) string {
password, err := speakeasy.Ask(prompt)
if err != nil {
if err.Error() == "The handle is invalid." {
Errln(`Login is currently incompatible with git bash/cygwin
In the meantime, login via cmd.exe
https://github.com/heroku/heroku-cli/issues/84`)
Exit(1)
} else {
ExitIfError(err, false)
}
}
return password
}
func v2login(email, password, secondFactor string) (string, error) {
req := apiRequestBase("")
req.Method = "POST"
req.Uri = req.Uri + "/login"
req.ContentType = "application/x-www-form-urlencoded"
req.ShowDebug = false
data := url.Values{}
data.Set("username", email)
data.Set("password", password)
req.Body = data.Encode()
if secondFactor != "" {
req.AddHeader("Heroku-Two-Factor-Code", secondFactor)
}
res, err := req.Do()
ExitIfError(err, false)
switch res.StatusCode {
case 200:
var response struct {
APIKey string `json:"api_key"`
}
ExitIfError(res.Body.FromJsonTo(&response), false)
return response.APIKey, nil
case 401:
var response struct {
Error string `json:"error"`
}
ExitIfError(res.Body.FromJsonTo(&response), false)
return "", errors.New(response.Error)
case 403:
return v2login(email, password, getString("Two-factor code: "))
case 404:
return "", errors.New("Authentication failed.\nEmail or password is not valid.\nCheck your credentials on https://dashboard.heroku.com")
default:
body, err := res.Body.ToString()
PrintError(err, false)
return "", fmt.Errorf("Invalid response from API.\nHTTP %d\n%s\n\nAre you behind a proxy?\nhttps://devcenter.heroku.com/articles/using-the-cli#using-an-http-proxy", res.StatusCode, body)
}
}
func createOauthToken(email, password, secondFactor string) (string, error) {
req := apiRequest("")
req.Method = "POST"
req.Uri = req.Uri + "/oauth/authorizations"
req.BasicAuthUsername = email
req.BasicAuthPassword = password
req.Body = map[string]interface{}{
"scope": []string{"global"},
"description": "Toolbelt CLI login from " + time.Now().UTC().Format(time.RFC3339),
"expires_in": 60 * 60 * 24 * 30, // 30 days
}
if secondFactor != "" {
req.AddHeader("Heroku-Two-Factor-Code", secondFactor)
}
res, err := req.Do()
ExitIfError(err, false)
type Doc struct {
ID string
Message string
AccessToken struct {
Token string
} `json:"access_token"`
}
var doc Doc
res.Body.FromJsonTo(&doc)
if doc.ID == "two_factor" {
return createOauthToken(email, password, getString("Two-factor code: "))
}
if res.StatusCode != 201 {
return "", errors.New(doc.Message)
}
return doc.AccessToken.Token, nil
}
var authTokenCmd = &Command{
Topic: "auth",
Command: "token",
Description: "display your API token.",
NeedsAuth: true,
Run: func(ctx *Context) {
Println(ctx.APIToken)
},
}
var logoutTopic = &Topic{
Name: "logout",
Description: "clear your local Heroku credentials",
}
var logoutCmd = &Command{
Topic: "logout",
Description: "clear your local Heroku credentials",
Run: logout,
}
var authLogoutCmd = &Command{
Topic: "auth",
Command: "logout",
Description: "clear your local Heroku credentials",
Run: logout,
}
func logout(ctx *Context) {
if os.Getenv("HEROKU_API_KEY") != "" {
Warn("HEROKU_API_KEY is set")
}
netrc := getNetrc()
netrc.RemoveMachine(apiHost())
netrc.RemoveMachine(httpGitHost())
ExitIfError(netrc.Save(), false)
Println("Local credentails cleared.")
}