github.com/koron/hk@v0.0.0-20150303213137-b8aeaa3ab34c/hkclient/creds.go (about)

     1  package hkclient
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"net/url"
     7  	"os"
     8  	"path/filepath"
     9  
    10  	"github.com/heroku/hk/Godeps/_workspace/src/github.com/bgentry/go-netrc/netrc"
    11  )
    12  
    13  type NetRc struct {
    14  	netrc.Netrc
    15  }
    16  
    17  func netRcPath() string {
    18  	if s := os.Getenv("NETRC_PATH"); s != "" {
    19  		return s
    20  	}
    21  
    22  	return filepath.Join(HomePath(), netrcFilename)
    23  }
    24  
    25  func LoadNetRc() (nrc *NetRc, err error) {
    26  	onrc, err := netrc.ParseFile(netRcPath())
    27  	if err != nil {
    28  		if os.IsNotExist(err) {
    29  			return &NetRc{}, nil
    30  		}
    31  		return nil, err
    32  	}
    33  
    34  	return &NetRc{*onrc}, nil
    35  }
    36  
    37  func (nrc *NetRc) GetCreds(apiURL *url.URL) (user, pass string, err error) {
    38  	if err != nil {
    39  		return "", "", fmt.Errorf("invalid API URL: %s", err)
    40  	}
    41  	if apiURL.Host == "" {
    42  		return "", "", fmt.Errorf("missing API host: %s", apiURL)
    43  	}
    44  	if apiURL.User != nil {
    45  		pw, _ := apiURL.User.Password()
    46  		return apiURL.User.Username(), pw, nil
    47  	}
    48  
    49  	m := nrc.FindMachine(apiURL.Host)
    50  	if m == nil {
    51  		return "", "", nil
    52  	}
    53  	return m.Login, m.Password, nil
    54  }
    55  
    56  func (nrc *NetRc) SaveCreds(host, user, pass string) error {
    57  	m := nrc.FindMachine(host)
    58  	if m == nil || m.IsDefault() {
    59  		m = nrc.NewMachine(host, user, pass, "")
    60  	}
    61  	m.UpdateLogin(user)
    62  	m.UpdatePassword(pass)
    63  
    64  	body, err := nrc.MarshalText()
    65  	if err != nil {
    66  		return err
    67  	}
    68  	return ioutil.WriteFile(netRcPath(), body, 0600)
    69  }
    70  
    71  func (nrc *NetRc) RemoveCreds(host string) error {
    72  	nrc.RemoveMachine(host)
    73  
    74  	body, err := nrc.MarshalText()
    75  	if err != nil {
    76  		return err
    77  	}
    78  	return ioutil.WriteFile(netRcPath(), body, 0600)
    79  }