...

Source file src/github.com/google/go-github/v33/example/basicauth/main.go

Documentation: github.com/google/go-github/v33/example/basicauth

     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  	"syscall"
    24  
    25  	"github.com/google/go-github/v33/github"
    26  	"golang.org/x/crypto/ssh/terminal"
    27  )
    28  
    29  func main() {
    30  	r := bufio.NewReader(os.Stdin)
    31  	fmt.Print("GitHub Username: ")
    32  	username, _ := r.ReadString('\n')
    33  
    34  	fmt.Print("GitHub Password: ")
    35  	bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
    36  	password := string(bytePassword)
    37  
    38  	tp := github.BasicAuthTransport{
    39  		Username: strings.TrimSpace(username),
    40  		Password: strings.TrimSpace(password),
    41  	}
    42  
    43  	client := github.NewClient(tp.Client())
    44  	ctx := context.Background()
    45  	user, _, err := client.Users.Get(ctx, "")
    46  
    47  	// Is this a two-factor auth error? If so, prompt for OTP and try again.
    48  	if _, ok := err.(*github.TwoFactorAuthError); ok {
    49  		fmt.Print("\nGitHub OTP: ")
    50  		otp, _ := r.ReadString('\n')
    51  		tp.OTP = strings.TrimSpace(otp)
    52  		user, _, err = client.Users.Get(ctx, "")
    53  	}
    54  
    55  	if err != nil {
    56  		fmt.Printf("\nerror: %v\n", err)
    57  		return
    58  	}
    59  
    60  	fmt.Printf("\n%v\n", github.Stringify(user))
    61  }
    62  

View as plain text