From 177c1dffda8e5fe6ca63f4e242eb8c668771421a Mon Sep 17 00:00:00 2001 From: Felix Wieland Date: Fri, 25 Aug 2023 21:11:45 +0200 Subject: [PATCH] feat(auth): added authentication uses the github cli to get a token for the api fixes #1 --- pkg/gist.go | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/pkg/gist.go b/pkg/gist.go index 2ebcf9e..062693b 100644 --- a/pkg/gist.go +++ b/pkg/gist.go @@ -1,12 +1,15 @@ package pkg import ( + "bytes" "context" "encoding/json" "errors" "io" "net/http" + "os/exec" + "github.com/charmbracelet/log" "github.com/flexwie/ghs/pkg/executors" "github.com/flexwie/ghs/pkg/github" ) @@ -15,7 +18,14 @@ func SearchForGist(ctx context.Context) (*github.Gist, *github.File, error) { url := ctx.Value("apiUrl").(string) gistName := ctx.Value("gist").(string) - resp, err := http.Get(url) + token := getGithubToken() + + req, err := http.NewRequest("GET", url, nil) + if token != "" { + req.Header.Add("Authorization", token) + } + + resp, err := http.DefaultClient.Do(req) if err != nil { return nil, nil, err } @@ -39,6 +49,28 @@ func SearchForGist(ctx context.Context) (*github.Gist, *github.File, error) { return nil, nil, errors.New("unable to find requested gist") } +func getGithubToken() string { + cmd := exec.Command("which", "gh") + if err := cmd.Run(); err != nil { + log.Warn("GitHub cli is not installed. Your private gists will not be found.") + return "" + } + + cmd = exec.Command("gh", "auth", "token") + writer := new(bytes.Buffer) + cmd.Stdout = writer + + errOut := new(bytes.Buffer) + cmd.Stderr = errOut + + if err := cmd.Run(); err != nil { + log.Warn("GitHub cli authentication failed. Your private gists will not be found.", "err", errOut.String()) + return "" + } + + return writer.String() +} + func GetExecutor(ctx context.Context) (executors.Executor, error) { for _, e := range executors.ExecutorPipeline { file := ctx.Value("file").(*github.File)