login.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package login
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/pkg/errors"
  7. "github.com/spf13/cobra"
  8. "github.com/docker/api/cli/dockerclassic"
  9. "github.com/docker/api/client"
  10. "github.com/docker/api/errdefs"
  11. )
  12. // Command returns the login command
  13. func Command() *cobra.Command {
  14. cmd := &cobra.Command{
  15. Use: "login [OPTIONS] [SERVER] | login azure",
  16. Short: "Log in to a Docker registry",
  17. Long: "Log in to a Docker registry or cloud backend.\nIf no registry server is specified, the default is defined by the daemon.",
  18. Args: cobra.MaximumNArgs(1),
  19. RunE: runLogin,
  20. }
  21. // define flags for backward compatibility with docker-classic
  22. flags := cmd.Flags()
  23. flags.StringP("username", "u", "", "Username")
  24. flags.StringP("password", "p", "", "Password")
  25. flags.BoolP("password-stdin", "", false, "Take the password from stdin")
  26. return cmd
  27. }
  28. func runLogin(cmd *cobra.Command, args []string) error {
  29. if len(args) == 1 && !strings.Contains(args[0], ".") {
  30. backend := args[0]
  31. switch backend {
  32. case "azure":
  33. return cloudLogin(cmd, "aci")
  34. default:
  35. return errors.New("unknown backend type for cloud login: " + backend)
  36. }
  37. }
  38. return dockerclassic.ExecCmd(cmd)
  39. }
  40. func cloudLogin(cmd *cobra.Command, backendType string) error {
  41. ctx := cmd.Context()
  42. cs, err := client.GetCloudService(ctx, backendType)
  43. if err != nil {
  44. return errors.Wrap(errdefs.ErrLoginFailed, "cannot connect to backend")
  45. }
  46. err = cs.Login(ctx, nil)
  47. if errors.Is(err, context.Canceled) {
  48. return errors.New("login canceled")
  49. }
  50. if err != nil {
  51. return err
  52. }
  53. fmt.Println("login succeeded")
  54. return nil
  55. }