Skip to content

Commit 35f18b6

Browse files
committed
gh auth login
1 parent b4ffced commit 35f18b6

File tree

13 files changed

+896
-38
lines changed

13 files changed

+896
-38
lines changed

api/client.go

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package api
33
import (
44
"bytes"
55
"encoding/json"
6+
"errors"
67
"fmt"
78
"io"
89
"io/ioutil"
@@ -195,19 +196,18 @@ func (err HTTPError) Error() string {
195196
return fmt.Sprintf("HTTP %d (%s)", err.StatusCode, err.RequestURL)
196197
}
197198

198-
// Returns whether or not scopes are present, appID, and error
199-
func (c Client) HasScopes(wantedScopes ...string) (bool, string, error) {
200-
url := "https://api.github.com/user"
201-
req, err := http.NewRequest("GET", url, nil)
199+
func (c Client) HasMinimumScopes(hostname string) (bool, error) {
200+
apiEndpoint := ghinstance.RESTPrefix(hostname)
201+
202+
req, err := http.NewRequest("GET", apiEndpoint, nil)
202203
if err != nil {
203-
return false, "", err
204+
return false, err
204205
}
205206

206207
req.Header.Set("Content-Type", "application/json; charset=utf-8")
207-
208208
res, err := c.http.Do(req)
209209
if err != nil {
210-
return false, "", err
210+
return false, err
211211
}
212212

213213
defer func() {
@@ -218,26 +218,36 @@ func (c Client) HasScopes(wantedScopes ...string) (bool, string, error) {
218218
}()
219219

220220
if res.StatusCode != 200 {
221-
return false, "", handleHTTPError(res)
221+
return false, handleHTTPError(res)
222222
}
223223

224-
appID := res.Header.Get("X-Oauth-Client-Id")
225224
hasScopes := strings.Split(res.Header.Get("X-Oauth-Scopes"), ",")
226225

227-
found := 0
226+
search := map[string]bool{
227+
"repo": false,
228+
"read:org": false,
229+
"admin:org": false,
230+
}
231+
228232
for _, s := range hasScopes {
229-
for _, w := range wantedScopes {
230-
if w == strings.TrimSpace(s) {
231-
found++
232-
}
233-
}
233+
search[strings.TrimSpace(s)] = true
234234
}
235235

236-
if found == len(wantedScopes) {
237-
return true, appID, nil
236+
errorMsgs := []string{}
237+
if !search["repo"] {
238+
errorMsgs = append(errorMsgs, "missing required scope 'repo'")
238239
}
239240

240-
return false, appID, nil
241+
if !search["read:org"] && !search["admin:org"] {
242+
errorMsgs = append(errorMsgs, "missing required scope 'read:org'")
243+
}
244+
245+
if len(errorMsgs) > 0 {
246+
return false, errors.New(strings.Join(errorMsgs, ";"))
247+
}
248+
249+
return true, nil
250+
241251
}
242252

243253
// GraphQL performs a GraphQL request and parses the response

command/root.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ import (
2222
"github.com/cli/cli/internal/ghrepo"
2323
"github.com/cli/cli/internal/run"
2424
apiCmd "github.com/cli/cli/pkg/cmd/api"
25+
authCmd "github.com/cli/cli/pkg/cmd/auth"
26+
authLoginCmd "github.com/cli/cli/pkg/cmd/auth/login"
2527
gistCreateCmd "github.com/cli/cli/pkg/cmd/gist/create"
2628
prCheckoutCmd "github.com/cli/cli/pkg/cmd/pr/checkout"
2729
prDiffCmd "github.com/cli/cli/pkg/cmd/pr/diff"
@@ -134,6 +136,9 @@ func init() {
134136
RootCmd.AddCommand(gistCmd)
135137
gistCmd.AddCommand(gistCreateCmd.NewCmdCreate(cmdFactory, nil))
136138

139+
RootCmd.AddCommand(authCmd.Cmd)
140+
authCmd.Cmd.AddCommand(authLoginCmd.NewCmdLogin(cmdFactory, nil))
141+
137142
resolvedBaseRepo := func() (ghrepo.Interface, error) {
138143
httpClient, err := cmdFactory.HttpClient()
139144
if err != nil {

internal/config/config_setup.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99

1010
"github.com/cli/cli/api"
1111
"github.com/cli/cli/auth"
12+
"github.com/cli/cli/utils"
1213
)
1314

1415
var (
@@ -67,7 +68,7 @@ func authFlow(oauthHost, notice string) (string, string, error) {
6768
}
6869

6970
fmt.Fprintln(os.Stderr, notice)
70-
fmt.Fprintf(os.Stderr, "Press Enter to open %s in your browser... ", flow.Hostname)
71+
fmt.Fprintf(os.Stderr, "- %s to open %s in your browser... ", utils.Bold("Press Enter"), flow.Hostname)
7172
_ = waitForEnter(os.Stdin)
7273
token, err := flow.ObtainAccessToken()
7374
if err != nil {
@@ -83,7 +84,8 @@ func authFlow(oauthHost, notice string) (string, string, error) {
8384
}
8485

8586
func AuthFlowComplete() {
86-
fmt.Fprintln(os.Stderr, "Authentication complete. Press Enter to continue... ")
87+
fmt.Fprintf(os.Stderr, "%s Authentication complete. %s to continue...\n",
88+
utils.GreenCheck(), utils.Bold("Press Enter"))
8789
_ = waitForEnter(os.Stdin)
8890
}
8991

pkg/cmd/auth/auth.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package auth
2+
3+
import (
4+
"github.com/spf13/cobra"
5+
)
6+
7+
var Cmd = &cobra.Command{
8+
Use: "auth <command>",
9+
Short: "Login, logout, and refresh your authentication",
10+
Long: `Manage gh's authentication state.`,
11+
// TODO this all doesn't exist yet
12+
//Example: heredoc.Doc(`
13+
// $ gh auth login
14+
// $ gh auth status
15+
// $ gh auth refresh --scopes gist
16+
// $ gh auth logout
17+
//`),
18+
}

pkg/cmd/auth/login/client.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package login
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
7+
"github.com/cli/cli/api"
8+
"github.com/cli/cli/internal/config"
9+
)
10+
11+
func validateHostCfg(hostname string, cfg config.Config) error {
12+
apiClient, err := clientFromCfg(hostname, cfg)
13+
if err != nil {
14+
return err
15+
}
16+
17+
_, err = apiClient.HasMinimumScopes(hostname)
18+
if err != nil {
19+
return fmt.Errorf("could not validate token: %w", err)
20+
}
21+
22+
return nil
23+
}
24+
25+
var clientFromCfg = func(hostname string, cfg config.Config) (*api.Client, error) {
26+
var opts []api.ClientOption
27+
28+
token, err := cfg.Get(hostname, "oauth_token")
29+
if err != nil {
30+
return nil, err
31+
}
32+
33+
if token == "" {
34+
return nil, fmt.Errorf("no token found in config for %s", hostname)
35+
}
36+
37+
opts = append(opts,
38+
// no access to Version so the user agent is more generic here.
39+
api.AddHeader("User-Agent", "GitHub CLI"),
40+
api.AddHeaderFunc("Authorization", func(req *http.Request) (string, error) {
41+
return fmt.Sprintf("token %s", token), nil
42+
}),
43+
)
44+
45+
httpClient := api.NewHTTPClient(opts...)
46+
47+
return api.NewClientFromHTTP(httpClient), nil
48+
}

0 commit comments

Comments
 (0)