diff options
author | Amine Hilaly <hilalyamine@gmail.com> | 2019-05-25 15:20:30 +0200 |
---|---|---|
committer | Amine Hilaly <hilalyamine@gmail.com> | 2019-05-29 22:58:01 +0200 |
commit | 46ce1059b6977d79b37477f02f2a5028ed4f09b0 (patch) | |
tree | 9043af0df714f41ef0adbfd30f6cfe98ebd22b3b /bridge | |
parent | 2c4c0132bf8c9e9819cc9a76d4a04ed4daeedb3b (diff) | |
download | git-bug-46ce1059b6977d79b37477f02f2a5028ed4f09b0.tar.gz |
Update Github bridge configuration
Use GetRemotes in `promptURL` to suggest repo urls
Add `promptTokenOptions` to select token a configuration option
Diffstat (limited to 'bridge')
-rw-r--r-- | bridge/github/config.go | 286 |
1 files changed, 200 insertions, 86 deletions
diff --git a/bridge/github/config.go b/bridge/github/config.go index 29e50b87..f2ac750e 100644 --- a/bridge/github/config.go +++ b/bridge/github/config.go @@ -32,7 +32,7 @@ const ( ) var ( - rxGithubSplit = regexp.MustCompile(`github\.com\/([^\/]*)\/([^\/]*)`) + rxGithubURL = regexp.MustCompile(`github\.com[\/:]([^\/]*[a-z]+)\/([^\/]*[a-z]+)`) ) func (*Github) Configure(repo repository.RepoCommon, params core.BridgeParams) (core.Configuration, error) { @@ -50,13 +50,18 @@ func (*Github) Configure(repo repository.RepoCommon, params core.BridgeParams) ( project = params.Project } else if params.URL != "" { - owner, project, err = splitURL(params.URL) + _, owner, project, err = splitURL(params.URL) if err != nil { return nil, err } } else { - owner, project, err = promptURL() + remotes, err := repo.GetRemotes() + if err != nil { + return nil, err + } + + owner, project, err = promptURL(remotes) if err != nil { return nil, err } @@ -71,87 +76,19 @@ func (*Github) Configure(repo repository.RepoCommon, params core.BridgeParams) ( return nil, fmt.Errorf("invalid parameter owner: %v", owner) } - // try to get token from params if provided, else use terminal prompt - // to login and generate a token + // try to get token from params if provided, else use terminal prompt to either + // enter a token or login and generate a new one if params.Token != "" { token = params.Token } else { - fmt.Println() - fmt.Println("git-bug will now generate an access token in your Github profile. Your credential are not stored and are only used to generate the token. The token is stored in the repository git config.") - fmt.Println() - fmt.Println("Depending on your configuration the token will have one of the following scopes:") - fmt.Println(" - 'user:email': to be able to read public-only users email") - fmt.Println(" - 'repo' : to be able to read private repositories") - // fmt.Println("The token will have the \"repo\" permission, giving it read/write access to your repositories and issues. There is no narrower scope available, sorry :-|") - fmt.Println() - - isPublic, err := promptProjectVisibility() - if err != nil { - return nil, err - } - - username, err := promptUsername() - if err != nil { - return nil, err - } - - password, err := promptPassword() - if err != nil { - return nil, err - } - - var scope string - if isPublic { - // user:email is requested to be able to read public emails - // - a private email will stay private, even with this token - scope = "user:email" - } else { - // 'repo' is request to be able to read private repositories - // /!\ token will have read/write rights on every private repository you have access to - scope = "repo" - } - - // Attempt to authenticate and create a token - - note := fmt.Sprintf("git-bug - %s/%s", owner, project) - - resp, err := requestToken(note, username, password, scope) + token, err = promptTokenOptions(owner, project) if err != nil { return nil, err } - - defer resp.Body.Close() - - // Handle 2FA is needed - OTPHeader := resp.Header.Get("X-GitHub-OTP") - if resp.StatusCode == http.StatusUnauthorized && OTPHeader != "" { - otpCode, err := prompt2FA() - if err != nil { - return nil, err - } - - resp, err = requestTokenWith2FA(note, username, password, otpCode, scope) - if err != nil { - return nil, err - } - - defer resp.Body.Close() - } - - if resp.StatusCode == http.StatusCreated { - token, err = decodeBody(resp.Body) - if err != nil { - return nil, err - } - - } else { - b, _ := ioutil.ReadAll(resp.Body) - return nil, fmt.Errorf("error creating token %v: %v", resp.StatusCode, string(b)) - } } - // verifying access to project with token + // verify access to the repository with token ok, err = validateProject(owner, project, token) if err != nil { return nil, err @@ -253,6 +190,130 @@ func randomFingerprint() string { return string(b) } +func promptTokenOptions(owner, project string) (string, error) { + for { + fmt.Println() + fmt.Println("[0]: i have my own token") + fmt.Println("[1]: login and generate token") + fmt.Print("Select option: ") + + line, err := bufio.NewReader(os.Stdin).ReadString('\n') + fmt.Println() + if err != nil { + return "", err + } + + line = strings.TrimRight(line, "\n") + + index, err := strconv.Atoi(line) + if err != nil || (index != 0 && index != 1) { + fmt.Println("invalid input") + continue + } + + if index == 0 { + return promptToken() + } + + return loginAndRequestToken(owner, project) + } +} + +func promptToken() (string, error) { + for { + fmt.Print("Enter token: ") + + byteToken, err := terminal.ReadPassword(int(syscall.Stdin)) + fmt.Println() + + if err != nil { + return "", err + } + + if len(byteToken) > 0 { + return string(byteToken), nil + } + + fmt.Println("token is empty") + } +} + +func loginAndRequestToken(owner, project string) (string, error) { + fmt.Println("git-bug will now generate an access token in your Github profile. Your credential are not stored and are only used to generate the token. The token is stored in the repository git config.") + fmt.Println() + fmt.Println("Depending on your configuration the token will have one of the following scopes:") + fmt.Println(" - 'user:email': to be able to read public-only users email") + fmt.Println(" - 'repo' : to be able to read private repositories") + // fmt.Println("The token will have the \"repo\" permission, giving it read/write access to your repositories and issues. There is no narrower scope available, sorry :-|") + fmt.Println() + + // prompt project visibility to know the token scope needed for the repository + isPublic, err := promptProjectVisibility() + if err != nil { + return "", err + } + + username, err := promptUsername() + if err != nil { + return "", err + } + + password, err := promptPassword() + if err != nil { + return "", err + } + + var scope string + if isPublic { + // user:email is requested to be able to read public emails + // - a private email will stay private, even with this token + scope = "user:email" + } else { + // 'repo' is request to be able to read private repositories + // /!\ token will have read/write rights on every private repository you have access to + scope = "repo" + } + + // Attempt to authenticate and create a token + + note := fmt.Sprintf("git-bug - %s/%s", owner, project) + + resp, err := requestToken(note, username, password, scope) + if err != nil { + return "", err + } + + defer resp.Body.Close() + + // Handle 2FA is needed + OTPHeader := resp.Header.Get("X-GitHub-OTP") + if resp.StatusCode == http.StatusUnauthorized && OTPHeader != "" { + otpCode, err := prompt2FA() + if err != nil { + return "", err + } + + resp, err = requestTokenWith2FA(note, username, password, otpCode, scope) + if err != nil { + return "", err + } + + defer resp.Body.Close() + } + + if resp.StatusCode == http.StatusCreated { + token, err := decodeBody(resp.Body) + if err != nil { + return "", err + } + + return token, nil + } + + b, _ := ioutil.ReadAll(resp.Body) + return "", fmt.Errorf("error creating token %v: %v", resp.StatusCode, string(b)) +} + func promptUsername() (string, error) { for { fmt.Print("username: ") @@ -276,7 +337,45 @@ func promptUsername() (string, error) { } } -func promptURL() (string, string, error) { +func promptURL(remotes map[string]string) (string, string, error) { + validRemotes := valideGithubURLRemotes(remotes) + if len(validRemotes) > 0 { + for { + fmt.Println("\nDetected projects:") + + // print valid remote github urls + for i, remote := range validRemotes { + fmt.Printf("[%d]: %v\n", i+1, remote) + } + + fmt.Printf("\n[0]: Another project\n\n") + fmt.Printf("Select option: ") + + line, err := bufio.NewReader(os.Stdin).ReadString('\n') + if err != nil { + return "", "", err + } + + line = strings.TrimRight(line, "\n") + + index, err := strconv.Atoi(line) + if err != nil || (index < 0 && index >= len(validRemotes)) { + fmt.Println("invalid input") + continue + } + + // if user want to enter another project url break this loop + if index == 0 { + break + } + + // get owner and project with index + _, owner, project, _ := splitURL(validRemotes[index-1]) + return owner, project, nil + } + } + + // manually enter github url for { fmt.Print("Github project URL: ") @@ -291,23 +390,37 @@ func promptURL() (string, string, error) { continue } - projectOwner, projectName, err := splitURL(line) + // get owner and project from url + _, owner, project, err := splitURL(line) if err != nil { fmt.Println(err) continue } - return projectOwner, projectName, nil + return owner, project, nil } } -func splitURL(url string) (string, string, error) { - res := rxGithubSplit.FindStringSubmatch(url) +func splitURL(url string) (string, string, string, error) { + res := rxGithubURL.FindStringSubmatch(url) if res == nil { - return "", "", fmt.Errorf("bad github project url") + return "", "", "", fmt.Errorf("bad github project url") + } + + return res[0], res[1], res[2], nil +} + +func valideGithubURLRemotes(remotes map[string]string) []string { + urls := make([]string, 0, len(remotes)) + for _, url := range remotes { + // split url can work again with shortURL + shortURL, _, _, err := splitURL(url) + if err == nil { + urls = append(urls, shortURL) + } } - return res[1], res[2], nil + return urls } func validateUsername(username string) (bool, error) { @@ -334,6 +447,7 @@ func validateProject(owner, project, token string) (bool, error) { return false, err } + // need the token for private repositories req.Header.Set("Authorization", fmt.Sprintf("token %s", token)) client := &http.Client{ @@ -401,11 +515,10 @@ func prompt2FA() (string, error) { } func promptProjectVisibility() (bool, error) { - fmt.Println("[0]: public") - fmt.Println("[1]: private") - for { - fmt.Print("repository visibility type: ") + fmt.Println("[0]: public") + fmt.Println("[1]: private") + fmt.Print("repository visibility: ") line, err := bufio.NewReader(os.Stdin).ReadString('\n') fmt.Println() @@ -421,6 +534,7 @@ func promptProjectVisibility() (bool, error) { continue } + // return true for public repositories, false for private return index == 0, nil } } |