ntgr/internal/netrc/netrc.go

63 lines
1.8 KiB
Go
Raw Normal View History

2022-03-07 23:14:24 +00:00
package netrc
import (
"bufio"
"encoding/base64"
"fmt"
"os"
"path"
"strings"
)
type NetrcCredential struct {
Machine string
Login string
Password string
}
func (credential *NetrcCredential) HttpHost() string {
return credential.HttpHostWithPath("")
}
func (credential *NetrcCredential) HttpHostWithPath(path string) string {
return fmt.Sprintf("http://%s%s", credential.Machine, path)
}
func (credential *NetrcCredential) Base64() string {
formattedCredentials := fmt.Sprintf("%s:%s", credential.Login, credential.Password)
credentialBytes := []byte(formattedCredentials)
return base64.StdEncoding.EncodeToString(credentialBytes)
}
func ReadCredentials(host string) (NetrcCredential, error) {
credentials := NetrcCredential{Machine: host}
netrcPath := path.Join(os.Getenv("HOME"), ".netrc")
netrcFile, err := os.Open(netrcPath)
if err != nil {
return credentials, fmt.Errorf("failed to read ~/.netrc: %v", err)
}
defer netrcFile.Close()
scanner := bufio.NewScanner(netrcFile)
extractCredentials := false
for {
if !scanner.Scan() {
break
}
line := scanner.Text()
if strings.HasPrefix(line, "machine ") {
extractCredentials = strings.HasSuffix(line, credentials.Machine)
} else if strings.HasPrefix(line, "login ") && extractCredentials {
credentials.Login = strings.TrimPrefix(line, "login ")
} else if strings.HasPrefix(line, "password ") && extractCredentials {
credentials.Password = strings.TrimPrefix(line, "password ")
}
}
if credentials.Login == "" {
return credentials, fmt.Errorf("error: no login found for host \"%s\" in ~/.netrc", credentials.Machine)
}
if credentials.Password == "" {
return credentials, fmt.Errorf("error: no password found for host \"%s\" in ~/.netrc", credentials.Machine)
}
return credentials, scanner.Err()
}