github.com/openshift/moby-moby@v1.13.2-0.20170601211448-f5ec1e2936dc/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  
    39  	flags.StringVarP(&opts.user, "username", "u", "", "Username")
    40  	flags.StringVarP(&opts.password, "password", "p", "", "Password")
    41  
    42  	// Deprecated in 1.11: Should be removed in docker 1.14
    43  	flags.StringVarP(&opts.email, "email", "e", "", "Email")
    44  	flags.MarkDeprecated("email", "will be removed in 1.14.")
    45  
    46  	return cmd
    47  }
    48  
    49  func runLogin(dockerCli *command.DockerCli, opts loginOptions) error {
    50  	ctx := context.Background()
    51  	clnt := dockerCli.Client()
    52  
    53  	var (
    54  		serverAddress string
    55  		authServer    = command.ElectAuthServer(ctx, dockerCli)
    56  	)
    57  	if opts.serverAddress != "" {
    58  		serverAddress = opts.serverAddress
    59  	} else {
    60  		serverAddress = authServer
    61  	}
    62  
    63  	isDefaultRegistry := serverAddress == authServer
    64  
    65  	authConfig, err := command.ConfigureAuth(dockerCli, opts.user, opts.password, serverAddress, isDefaultRegistry)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	response, err := clnt.RegistryLogin(ctx, authConfig)
    70  	if err != nil {
    71  		return err
    72  	}
    73  	if response.IdentityToken != "" {
    74  		authConfig.Password = ""
    75  		authConfig.IdentityToken = response.IdentityToken
    76  	}
    77  	if err := dockerCli.CredentialsStore(serverAddress).Store(authConfig); err != nil {
    78  		return fmt.Errorf("Error saving credentials: %v", err)
    79  	}
    80  
    81  	if response.Status != "" {
    82  		fmt.Fprintln(dockerCli.Out(), response.Status)
    83  	}
    84  	return nil
    85  }