logout.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/docker/docker/registry"
  8. "github.com/spf13/cobra"
  9. )
  10. // NewLogoutCommand creates a new `docker login` command
  11. func NewLogoutCommand(dockerCli *command.DockerCli) *cobra.Command {
  12. cmd := &cobra.Command{
  13. Use: "logout [SERVER]",
  14. Short: "Log out from a Docker registry",
  15. Long: "Log out from a Docker registry.\nIf no server is specified, the default is defined by the daemon.",
  16. Args: cli.RequiresMaxArgs(1),
  17. RunE: func(cmd *cobra.Command, args []string) error {
  18. var serverAddress string
  19. if len(args) > 0 {
  20. serverAddress = args[0]
  21. }
  22. return runLogout(dockerCli, serverAddress)
  23. },
  24. }
  25. return cmd
  26. }
  27. func runLogout(dockerCli *command.DockerCli, serverAddress string) error {
  28. ctx := context.Background()
  29. var isDefaultRegistry bool
  30. if serverAddress == "" {
  31. serverAddress = command.ElectAuthServer(ctx, dockerCli)
  32. isDefaultRegistry = true
  33. }
  34. var (
  35. loggedIn bool
  36. regsToLogout []string
  37. hostnameAddress = serverAddress
  38. regsToTry = []string{serverAddress}
  39. )
  40. if !isDefaultRegistry {
  41. hostnameAddress = registry.ConvertToHostname(serverAddress)
  42. // the tries below are kept for backward compatibility where a user could have
  43. // saved the registry in one of the following format.
  44. regsToTry = append(regsToTry, hostnameAddress, "http://"+hostnameAddress, "https://"+hostnameAddress)
  45. }
  46. // check if we're logged in based on the records in the config file
  47. // which means it couldn't have user/pass cause they may be in the creds store
  48. for _, s := range regsToTry {
  49. if _, ok := dockerCli.ConfigFile().AuthConfigs[s]; ok {
  50. loggedIn = true
  51. regsToLogout = append(regsToLogout, s)
  52. }
  53. }
  54. if !loggedIn {
  55. fmt.Fprintf(dockerCli.Out(), "Not logged in to %s\n", hostnameAddress)
  56. return nil
  57. }
  58. fmt.Fprintf(dockerCli.Out(), "Removing login credentials for %s\n", hostnameAddress)
  59. for _, r := range regsToLogout {
  60. if err := dockerCli.CredentialsStore(r).Erase(r); err != nil {
  61. fmt.Fprintf(dockerCli.Err(), "WARNING: could not erase credentials: %v\n", err)
  62. }
  63. }
  64. return nil
  65. }