github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/client/cli/auth/login.go (about) 1 package cli 2 3 import ( 4 "bufio" 5 "fmt" 6 "os" 7 "strings" 8 "syscall" 9 10 "github.com/tickoalcantara12/micro/v3/client/cli/namespace" 11 "github.com/tickoalcantara12/micro/v3/client/cli/token" 12 "github.com/tickoalcantara12/micro/v3/client/cli/util" 13 "github.com/tickoalcantara12/micro/v3/service/auth" 14 "github.com/tickoalcantara12/micro/v3/util/report" 15 "github.com/urfave/cli/v2" 16 "golang.org/x/crypto/ssh/terminal" 17 ) 18 19 // login flow. 20 // For documentation of the flow please refer to https://github.com/micro/development/pull/223 21 func login(ctx *cli.Context) error { 22 // otherwise assume username/password login 23 24 // get the environment 25 env, err := util.GetEnv(ctx) 26 if err != nil { 27 return err 28 } 29 // get the username 30 username := ctx.String("username") 31 32 // username is blank 33 if len(username) == 0 { 34 fmt.Print("Enter username: ") 35 // read out the username from prompt if blank 36 reader := bufio.NewReader(os.Stdin) 37 username, _ = reader.ReadString('\n') 38 username = strings.TrimSpace(username) 39 } 40 41 ns, err := namespace.Get(env.Name) 42 if err != nil { 43 return err 44 } 45 46 // clear tokens and try again 47 if err := token.Remove(ctx); err != nil { 48 report.Errorf(ctx, "%v: Token remove: %v", username, err.Error()) 49 return err 50 } 51 52 password := ctx.String("password") 53 if len(password) == 0 { 54 pw, err := getPassword() 55 if err != nil { 56 return err 57 } 58 password = pw 59 fmt.Println() 60 } 61 tok, err := auth.Token(auth.WithCredentials(username, password), auth.WithTokenIssuer(ns)) 62 if err != nil { 63 report.Errorf(ctx, "%v: Getting token: %v", username, err.Error()) 64 return err 65 } 66 if err := token.Save(ctx, tok); err != nil { 67 report.Errorf(ctx, "%s: Save token: %s", username, err.Error()) 68 return err 69 } 70 71 fmt.Println("Successfully logged in.") 72 return nil 73 } 74 75 // taken from https://stackoverflow.com/questions/2137357/getpasswd-functionality-in-go 76 func getPassword() (string, error) { 77 fmt.Print("Enter password: ") 78 bytePassword, err := terminal.ReadPassword(int(syscall.Stdin)) 79 if err != nil { 80 return "", err 81 } 82 password := string(bytePassword) 83 return strings.TrimSpace(password), nil 84 } 85 86 func logout(ctx *cli.Context) error { 87 return token.Remove(ctx) 88 }