A CLI for tangled.sh
1package auth
2
3import (
4 "encoding/json"
5 "net/http"
6 "net/http/cookiejar"
7 "net/url"
8
9 "github.com/zalando/go-keyring"
10)
11
12const service = "knit://"
13
14// NewClient creates a new http.Client with the appropriate authentication set
15func NewClient(host string, handle string) (*http.Client, error) {
16 cookies, err := getCookies(host, handle)
17 if err != nil {
18 return nil, err
19 }
20
21 // cookiejar.New can't fail
22 jar, _ := cookiejar.New(nil)
23
24 u := &url.URL{
25 Scheme: "https",
26 Host: host,
27 }
28 jar.SetCookies(u, cookies)
29
30 return &http.Client{Jar: jar}, nil
31}
32
33// SaveCookies serializes the cookies and saves them to the system keyring
34func SaveCookies(cookies []*http.Cookie, host string, handle string) error {
35 if len(cookies) == 0 {
36 return nil
37 }
38 data, err := json.Marshal(cookies)
39 if err != nil {
40 return err
41 }
42 return keyring.Set(service+host, handle, string(data))
43}
44
45func getCookies(host string, handle string) ([]*http.Cookie, error) {
46 s, err := keyring.Get(service+host, handle)
47 if err != nil {
48 return nil, err
49 }
50
51 var cookies []*http.Cookie
52 if err := json.Unmarshal([]byte(s), &cookies); err != nil {
53 return nil, err
54 }
55
56 return cookies, nil
57}