github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/command/login/login.go (about) 1 package login 2 3 import ( 4 "context" 5 "fmt" 6 "net/http" 7 "os" 8 9 "github.com/henvic/wedeploycli/apihelper" 10 "github.com/henvic/wedeploycli/cmdflagsfromhost" 11 "github.com/henvic/wedeploycli/command/internal/we" 12 "github.com/henvic/wedeploycli/config" 13 "github.com/henvic/wedeploycli/fancy" 14 "github.com/henvic/wedeploycli/login" 15 "github.com/henvic/wedeploycli/projects" 16 "github.com/spf13/cobra" 17 ) 18 19 var noLaunchBrowser bool 20 21 // LoginCmd sets the user credential 22 var LoginCmd = &cobra.Command{ 23 Use: "login", 24 Short: "Login into your account", 25 Args: cobra.NoArgs, 26 PreRunE: preRun, 27 RunE: loginRun, 28 } 29 30 var setupHost = cmdflagsfromhost.SetupHost{ 31 Pattern: cmdflagsfromhost.RemotePattern, 32 } 33 34 func init() { 35 setupHost.Init(LoginCmd) 36 LoginCmd.Flags().BoolVar(&noLaunchBrowser, "no-browser", false, "Perform the operation without opening your browser") 37 } 38 39 func preRun(cmd *cobra.Command, args []string) error { 40 return setupHost.Process(context.Background(), we.Context()) 41 } 42 43 func verifyAlreadyLoggedIn(wectx config.Context) error { 44 projectsClient := projects.New(we.Context()) 45 _, err := projectsClient.List(context.Background()) 46 af, ok := err.(apihelper.APIFault) 47 48 if ok && af.Status == http.StatusUnauthorized { 49 _, _ = fmt.Fprintln(os.Stderr, fancy.Error( 50 fmt.Sprintf( 51 `Validating current token for %v on %v (%v) failed`, 52 wectx.Username(), 53 wectx.Remote(), 54 wectx.InfrastructureDomain()), 55 )) 56 return nil 57 } 58 59 return fmt.Errorf(`already logged in as %v on %v (%v) 60 Logout first with "lcp logout"`, 61 wectx.Username(), 62 wectx.Remote(), 63 wectx.InfrastructureDomain()) 64 } 65 66 func loginRun(cmd *cobra.Command, args []string) error { 67 var wectx = we.Context() 68 69 if wectx.Username() != "" { 70 if err := verifyAlreadyLoggedIn(wectx); err != nil { 71 return err 72 } 73 } 74 75 a := login.Authentication{ 76 NoLaunchBrowser: noLaunchBrowser, 77 TipCommands: true, 78 } 79 80 return a.Run(context.Background(), wectx) 81 }