github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/cli/command/registry/login.go (about) 1 package registry 2 3 import ( 4 "fmt" 5 6 "golang.org/x/net/context" 7 8 "github.com/docker/docker/cli" 9 "github.com/docker/docker/cli/command" 10 "github.com/spf13/cobra" 11 ) 12 13 type loginOptions struct { 14 serverAddress string 15 user string 16 password string 17 email string 18 } 19 20 // NewLoginCommand creates a new `docker login` command 21 func NewLoginCommand(dockerCli *command.DockerCli) *cobra.Command { 22 var opts loginOptions 23 24 cmd := &cobra.Command{ 25 Use: "login [OPTIONS] [SERVER]", 26 Short: "Log in to a Docker registry", 27 Long: "Log in to a Docker registry.\nIf no server is specified, the default is defined by the daemon.", 28 Args: cli.RequiresMaxArgs(1), 29 RunE: func(cmd *cobra.Command, args []string) error { 30 if len(args) > 0 { 31 opts.serverAddress = args[0] 32 } 33 return runLogin(dockerCli, opts) 34 }, 35 } 36 37 flags := cmd.Flags() 38 flags.StringVarP(&opts.user, "username", "u", "", "Username") 39 flags.StringVarP(&opts.password, "password", "p", "", "Password") 40 41 return cmd 42 } 43 44 func runLogin(dockerCli *command.DockerCli, opts loginOptions) error { 45 ctx := context.Background() 46 clnt := dockerCli.Client() 47 48 var ( 49 serverAddress string 50 authServer = command.ElectAuthServer(ctx, dockerCli) 51 ) 52 if opts.serverAddress != "" { 53 serverAddress = opts.serverAddress 54 } else { 55 serverAddress = authServer 56 } 57 58 isDefaultRegistry := serverAddress == authServer 59 60 authConfig, err := command.ConfigureAuth(dockerCli, opts.user, opts.password, serverAddress, isDefaultRegistry) 61 if err != nil { 62 return err 63 } 64 response, err := clnt.RegistryLogin(ctx, authConfig) 65 if err != nil { 66 return err 67 } 68 if response.IdentityToken != "" { 69 authConfig.Password = "" 70 authConfig.IdentityToken = response.IdentityToken 71 } 72 if err := dockerCli.CredentialsStore(serverAddress).Store(authConfig); err != nil { 73 return fmt.Errorf("Error saving credentials: %v", err) 74 } 75 76 if response.Status != "" { 77 fmt.Fprintln(dockerCli.Out(), response.Status) 78 } 79 return nil 80 }