File: oauth_device.go

package info (click to toggle)
golang-github-cli-oauth 1.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 168 kB
  • sloc: makefile: 2
file content (72 lines) | stat: -rw-r--r-- 1,617 bytes parent folder | download
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
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 {
		host = GitHubHost("https://" + oa.Hostname)
	}

	code, err := device.RequestCode(httpClient, host.DeviceCodeURL, oa.ClientID, oa.Scopes)
	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()
}