Skip to content

Commit

Permalink
Manually get current user name rather than use api client (#7114)
Browse files Browse the repository at this point in the history
  • Loading branch information
samcoe committed Mar 9, 2023
1 parent 03730c2 commit 50ddb36
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions pkg/cmd/auth/shared/login_flow.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package shared

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
Expand Down Expand Up @@ -174,9 +176,8 @@ func Login(opts *LoginOptions) error {
}

if username == "" {
apiClient := api.NewClientFromHTTP(httpClient)
var err error
username, err = api.CurrentLoginName(apiClient, hostname)
username, err = getCurrentLogin(httpClient, hostname, authToken)
if err != nil {
return fmt.Errorf("error using api: %w", err)
}
Expand Down Expand Up @@ -231,3 +232,34 @@ func sshKeyUpload(httpClient *http.Client, hostname, keyFile string, title strin

return add.SSHKeyUpload(httpClient, hostname, f, title)
}

func getCurrentLogin(httpClient httpClient, hostname, authToken string) (string, error) {
query := `query UserCurrent{viewer{login}}`
reqBody, err := json.Marshal(map[string]interface{}{"query": query})
if err != nil {
return "", err
}
result := struct {
Data struct{ Viewer struct{ Login string } }
}{}
apiEndpoint := ghinstance.GraphQLEndpoint(hostname)
req, err := http.NewRequest("POST", apiEndpoint, bytes.NewBuffer(reqBody))
if err != nil {
return "", err
}
req.Header.Set("Authorization", "token "+authToken)
res, err := httpClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode > 299 {
return "", api.HandleHTTPError(res)
}
decoder := json.NewDecoder(res.Body)
err = decoder.Decode(&result)
if err != nil {
return "", err
}
return result.Data.Viewer.Login, nil
}

0 comments on commit 50ddb36

Please sign in to comment.