Browse Source

Merge pull request #630 from dotcloud/check_if_logged_before_pull-fix

add login check before pull user's repo
Guillaume J. Charmes 12 years ago
parent
commit
d8e60b797f
1 changed files with 42 additions and 28 deletions
  1. 42 28
      commands.go

+ 42 - 28
commands.go

@@ -623,39 +623,13 @@ func (cli *DockerCli) CmdPush(args ...string) error {
 		return nil
 	}
 
-	body, _, err := cli.call("GET", "/auth", nil)
-	if err != nil {
-		return err
-	}
-
-	var out auth.AuthConfig
-	err = json.Unmarshal(body, &out)
+	username, err := cli.checkIfLogged(*registry == "", "push")
 	if err != nil {
 		return err
 	}
 
-	// If the login failed AND we're using the index, abort
-	if *registry == "" && out.Username == "" {
-		if err := cli.CmdLogin(args...); err != nil {
-			return err
-		}
-
-		body, _, err = cli.call("GET", "/auth", nil)
-		if err != nil {
-			return err
-		}
-		err = json.Unmarshal(body, &out)
-		if err != nil {
-			return err
-		}
-
-		if out.Username == "" {
-			return fmt.Errorf("Please login prior to push. ('docker login')")
-		}
-	}
-
 	if len(strings.SplitN(name, "/", 2)) == 1 {
-		return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", out.Username, name)
+		return fmt.Errorf("Impossible to push a \"root\" repository. Please rename your repository in <user>/<repo> (ex: %s/%s)", username, name)
 	}
 
 	v := url.Values{}
@@ -686,6 +660,12 @@ func (cli *DockerCli) CmdPull(args ...string) error {
 		remote = remoteParts[0]
 	}
 
+	if strings.Contains(remote, "/") {
+		if _, err := cli.checkIfLogged(true, "pull"); err != nil {
+			return err
+		}
+	}
+
 	v := url.Values{}
 	v.Set("fromImage", remote)
 	v.Set("tag", *tag)
@@ -1173,6 +1153,40 @@ func (cli *DockerCli) CmdRun(args ...string) error {
 	return nil
 }
 
+func (cli *DockerCli) checkIfLogged(condition bool, action string) (string, error) {
+	body, _, err := cli.call("GET", "/auth", nil)
+	if err != nil {
+		return "", err
+	}
+
+	var out auth.AuthConfig
+	err = json.Unmarshal(body, &out)
+	if err != nil {
+		return "", err
+	}
+
+	// If condition AND the login failed
+	if condition && out.Username == "" {
+		if err := cli.CmdLogin(""); err != nil {
+			return "", err
+		}
+
+		body, _, err = cli.call("GET", "/auth", nil)
+		if err != nil {
+			return "", err
+		}
+		err = json.Unmarshal(body, &out)
+		if err != nil {
+			return "", err
+		}
+
+		if out.Username == "" {
+			return "", fmt.Errorf("Please login prior to %s. ('docker login')", action)
+		}
+	}
+	return out.Username, nil
+}
+
 func (cli *DockerCli) call(method, path string, data interface{}) ([]byte, int, error) {
 	var params io.Reader
 	if data != nil {