-
Notifications
You must be signed in to change notification settings - Fork 158
/
creds.go
84 lines (69 loc) · 1.57 KB
/
creds.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package hkclient
import (
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"github.com/bgentry/go-netrc/netrc"
)
type NetRc struct {
netrc.Netrc
}
func netRcPath() string {
if s := os.Getenv("NETRC_PATH"); s != "" {
return s
}
return filepath.Join(HomePath(), netrcFilename)
}
func LoadNetRc() (nrc *NetRc, err error) {
onrc, err := netrc.ParseFile(netRcPath())
if err != nil {
if os.IsNotExist(err) {
return &NetRc{}, nil
}
return nil, err
}
return &NetRc{*onrc}, nil
}
func (nrc *NetRc) GetCreds(apiURL *url.URL) (user, pass string, err error) {
if err != nil {
return "", "", fmt.Errorf("invalid API URL: %s", err)
}
if apiURL.Host == "" {
return "", "", fmt.Errorf("missing API host: %s", apiURL)
}
if apiURL.User != nil {
pw, _ := apiURL.User.Password()
return apiURL.User.Username(), pw, nil
}
m := nrc.FindMachine(apiURL.Host)
if m == nil {
return "", "", nil
}
return m.Login, m.Password, nil
}
func (nrc *NetRc) SaveCreds(address, user, pass string) error {
m := nrc.FindMachine(address)
if m == nil || m.IsDefault() {
m = nrc.NewMachine(address, user, pass, "")
}
m.UpdateLogin(user)
m.UpdatePassword(pass)
body, err := nrc.MarshalText()
if err != nil {
return err
}
// make sure we have a newline after the credentials
// before inserting into netRc
body = append(body, '\n')
return ioutil.WriteFile(netRcPath(), body, 0600)
}
func (nrc *NetRc) RemoveCreds(host string) error {
nrc.RemoveMachine(host)
body, err := nrc.MarshalText()
if err != nil {
return err
}
return ioutil.WriteFile(netRcPath(), body, 0600)
}