Skip to content

Commit 177c1df

Browse files
committed
feat(auth): added authentication
uses the github cli to get a token for the api fixes #1
1 parent e9710e2 commit 177c1df

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

pkg/gist.go

+33-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
package pkg
22

33
import (
4+
"bytes"
45
"context"
56
"encoding/json"
67
"errors"
78
"io"
89
"net/http"
10+
"os/exec"
911

12+
"github.com/charmbracelet/log"
1013
"github.com/flexwie/ghs/pkg/executors"
1114
"github.com/flexwie/ghs/pkg/github"
1215
)
@@ -15,7 +18,14 @@ func SearchForGist(ctx context.Context) (*github.Gist, *github.File, error) {
1518
url := ctx.Value("apiUrl").(string)
1619
gistName := ctx.Value("gist").(string)
1720

18-
resp, err := http.Get(url)
21+
token := getGithubToken()
22+
23+
req, err := http.NewRequest("GET", url, nil)
24+
if token != "" {
25+
req.Header.Add("Authorization", token)
26+
}
27+
28+
resp, err := http.DefaultClient.Do(req)
1929
if err != nil {
2030
return nil, nil, err
2131
}
@@ -39,6 +49,28 @@ func SearchForGist(ctx context.Context) (*github.Gist, *github.File, error) {
3949
return nil, nil, errors.New("unable to find requested gist")
4050
}
4151

52+
func getGithubToken() string {
53+
cmd := exec.Command("which", "gh")
54+
if err := cmd.Run(); err != nil {
55+
log.Warn("GitHub cli is not installed. Your private gists will not be found.")
56+
return ""
57+
}
58+
59+
cmd = exec.Command("gh", "auth", "token")
60+
writer := new(bytes.Buffer)
61+
cmd.Stdout = writer
62+
63+
errOut := new(bytes.Buffer)
64+
cmd.Stderr = errOut
65+
66+
if err := cmd.Run(); err != nil {
67+
log.Warn("GitHub cli authentication failed. Your private gists will not be found.", "err", errOut.String())
68+
return ""
69+
}
70+
71+
return writer.String()
72+
}
73+
4274
func GetExecutor(ctx context.Context) (executors.Executor, error) {
4375
for _, e := range executors.ExecutorPipeline {
4476
file := ctx.Value("file").(*github.File)

0 commit comments

Comments
 (0)