login.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package login
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "github.com/docker/api/cli/cmd/mobyflags"
  19. "github.com/pkg/errors"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/api/cli/mobycli"
  22. "github.com/docker/api/client"
  23. "github.com/docker/api/errdefs"
  24. )
  25. // Command returns the login command
  26. func Command() *cobra.Command {
  27. cmd := &cobra.Command{
  28. Use: "login [OPTIONS] [SERVER]",
  29. Short: "Log in to a Docker registry or cloud backend",
  30. Long: "Log in to a Docker registry or cloud backend.\nIf no registry server is specified, the default is defined by the daemon.",
  31. Args: cobra.MaximumNArgs(1),
  32. RunE: runLogin,
  33. }
  34. // define flags for backward compatibility with com.docker.cli
  35. flags := cmd.Flags()
  36. flags.StringP("username", "u", "", "Username")
  37. flags.StringP("password", "p", "", "Password")
  38. flags.BoolP("password-stdin", "", false, "Take the password from stdin")
  39. mobyflags.AddMobyFlagsForRetrocompatibility(flags)
  40. cmd.AddCommand(AzureLoginCommand())
  41. return cmd
  42. }
  43. func runLogin(cmd *cobra.Command, args []string) error {
  44. if len(args) == 1 && !strings.Contains(args[0], ".") {
  45. backend := args[0]
  46. return errors.New("unknown backend type for cloud login: " + backend)
  47. }
  48. return mobycli.ExecCmd(cmd)
  49. }
  50. func cloudLogin(cmd *cobra.Command, backendType string, params interface{}) error {
  51. ctx := cmd.Context()
  52. cs, err := client.GetCloudService(ctx, backendType)
  53. if err != nil {
  54. return errors.Wrap(errdefs.ErrLoginFailed, "cannot connect to backend")
  55. }
  56. err = cs.Login(ctx, params)
  57. if errors.Is(err, context.Canceled) {
  58. return errors.New("login canceled")
  59. }
  60. if err != nil {
  61. return err
  62. }
  63. fmt.Println("login succeeded")
  64. return nil
  65. }