login.go 2.1 KB

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