Debian Codegraph @

example/basicauth/main.go

raw
1 // Copyright 2015 The go-github AUTHORS. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 // The basicauth command demonstrates using the github.BasicAuthTransport,
7 // including handling two-factor authentication. This won't currently work for
8 // accounts that use SMS to receive one-time passwords.
9 //
10 // Deprecation Notice: GitHub will discontinue password authentication to the API.
11 // You must now authenticate to the GitHub API with an API token, such as an OAuth access token,
12 // GitHub App installation access token, or personal access token, depending on what you need to do with the token.
13 // Password authentication to the API will be removed on November 13, 2020.
14 // See the tokenauth example for details.
15 package main
16
17 import (
18 "bufio"
19 "context"
20 "fmt"
21 "os"
22 "strings"
23
24 "github.com/google/go-github/v60/github"
25 "golang.org/x/term"
26 )
27
28 func main() {
29 r := bufio.NewReader(os.Stdin)
30 fmt.Print("GitHub Username: ")
31 username, _ := r.ReadString('\n')
32
33 fmt.Print("GitHub Password: ")
34 bytePassword, _ := term.ReadPassword(int(os.Stdin.Fd()))
35 password := string(bytePassword)
36
37 tp := github.BasicAuthTransport{
38 Username: strings.TrimSpace(username),
39 Password: strings.TrimSpace(password),
40 }
41
42 client := github.NewClient(tp.Client())
43 ctx := context.Background()
44 user, _, err := client.Users.Get(ctx, "")
45
46 // Is this a two-factor auth error? If so, prompt for OTP and try again.
47 if _, ok := err.(*github.TwoFactorAuthError); ok {
48 fmt.Print("\nGitHub OTP: ")
49 otp, _ := r.ReadString('\n')
50 tp.OTP = strings.TrimSpace(otp)
51 user, _, err = client.Users.Get(ctx, "")
52 }
53
54 if err != nil {
55 fmt.Printf("\nerror: %v\n", err)
56 return
57 }
58
59 fmt.Printf("\n%v\n", github.Stringify(user))
60 }