-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcredentials.go
112 lines (88 loc) · 2.57 KB
/
credentials.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
// Copyright 2015 MediaMath <http://www.mediamath.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
const userEnvVariable = "ARTIFACTORY_USER"
const passwordEnvVariable = "ARTIFACTORY_PASSWORD"
type credentials struct {
User string
Password string
}
func getCredentials(fileName string) (*credentials, error) {
user := os.Getenv(userEnvVariable)
pass := os.Getenv(passwordEnvVariable)
if fileName != "" && strings.ToLower(filepath.Ext(fileName)) == ".json" {
return getCredentialsFromJSONFile(fileName)
}
if fileName != "" {
return getCredentialsFromIniFile(fileName)
}
if user != "" && pass != "" {
return &credentials{user, pass}, nil
}
return nil, nil
}
//not a really well defined ini file, doesnt have sections or comment parsing etc. but will work for our purposes.
func getCredentialsFromIniFile(fileName string) (*credentials, error) {
fileBytes, readErr := ioutil.ReadFile(fileName)
if readErr != nil {
return nil, readErr
}
fileString := string(fileBytes)
lines := strings.Split(fileString, "\n")
var creds credentials
for _, line := range lines {
if strings.TrimSpace(line) == "" {
continue
}
key, value, parseErr := parseIniPair(line)
if parseErr != nil {
return nil, parseErr
}
if key == "user" {
creds.User = value
} else if key == "password" {
creds.Password = value
}
}
if verifyErr := verifyCredentials(creds, fmt.Sprintf("Config file must contain user and password: %v", fileString)); verifyErr != nil {
return nil, verifyErr
}
return &creds, nil
}
func parseIniPair(line string) (string, string, error) {
items := strings.Split(line, "=")
if len(items) != 2 {
return "", "", fmt.Errorf("Parse error: %v", line)
}
return strings.TrimSpace(items[0]), strings.TrimSpace(items[1]), nil
}
func getCredentialsFromJSONFile(fileName string) (*credentials, error) {
configFile, openErr := os.Open(fileName)
if openErr != nil {
return nil, openErr
}
defer configFile.Close()
var creds credentials
if parseErr := json.NewDecoder(configFile).Decode(&creds); parseErr != nil {
return nil, parseErr
}
if verifyErr := verifyCredentials(creds, `Config file must be { "user": "USERVAL", "password": "PASSVAL"}`); verifyErr != nil {
return nil, verifyErr
}
return &creds, nil
}
func verifyCredentials(creds credentials, errorText string) error {
if creds.Password == "" || creds.User == "" {
return fmt.Errorf(errorText)
}
return nil
}