-
Notifications
You must be signed in to change notification settings - Fork 65
/
oauth_device.go
78 lines (67 loc) · 1.75 KB
/
oauth_device.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
package oauth
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"os"
"github.com/cli/browser"
"github.com/cli/oauth/api"
"github.com/cli/oauth/device"
)
// DeviceFlow captures the full OAuth Device flow, including prompting the user to copy a one-time
// code and opening their web browser, and returns an access token upon completion.
func (oa *Flow) DeviceFlow() (*api.AccessToken, error) {
httpClient := oa.HTTPClient
if httpClient == nil {
httpClient = http.DefaultClient
}
stdin := oa.Stdin
if stdin == nil {
stdin = os.Stdin
}
stdout := oa.Stdout
if stdout == nil {
stdout = os.Stdout
}
host := oa.Host
if host == nil {
parsedHost, err := NewGitHubHost("https://" + oa.Hostname)
if err != nil {
return nil, fmt.Errorf("error parsing the hostname '%s': %w", oa.Hostname, err)
}
host = parsedHost
}
code, err := device.RequestCode(httpClient, host.DeviceCodeURL,
oa.ClientID, oa.Scopes, device.WithAudience(oa.Audience))
if err != nil {
return nil, err
}
if oa.DisplayCode == nil {
fmt.Fprintf(stdout, "First, copy your one-time code: %s\n", code.UserCode)
fmt.Fprint(stdout, "Then press [Enter] to continue in the web browser... ")
_ = waitForEnter(stdin)
} else {
err := oa.DisplayCode(code.UserCode, code.VerificationURI)
if err != nil {
return nil, err
}
}
browseURL := oa.BrowseURL
if browseURL == nil {
browseURL = browser.OpenURL
}
if err = browseURL(code.VerificationURI); err != nil {
return nil, fmt.Errorf("error opening the web browser: %w", err)
}
return device.Wait(context.TODO(), httpClient, host.TokenURL, device.WaitOptions{
ClientID: oa.ClientID,
DeviceCode: code,
})
}
func waitForEnter(r io.Reader) error {
scanner := bufio.NewScanner(r)
scanner.Scan()
return scanner.Err()
}