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