/
config.go
98 lines (81 loc) · 2.59 KB
/
config.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
package fusion
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
)
type fusionConfig struct {
DefaultProfile string `json:"default_profile"`
Profiles map[string]ProfileConfig `json:"profiles"`
}
type ProfileConfig struct {
ApiHost string `json:"endpoint"`
Auth `json:"auth"`
}
type Auth struct {
IssuerId string `json:"issuer_id,omitempty"`
PrivateKeyFile string `json:"private_pem_file,omitempty"`
TokenEndpoint string `json:"token_endpoint,omitempty"`
AccessToken string `json:"access_token,omitempty"`
PrivateKey string `json:"private_key,omitempty"`
PrivateKeyPassword string `json:"private_key_password,omitempty"`
}
var (
ErrNoRequiredAuthFields = errors.New("profile does not have required auth fields")
ErrNoDefaultProfileField = errors.New("config does not have required field `default_profile`")
ErrNoProfilesField = errors.New("config does not have required field `profiles`")
ErrNoProfileExists = errors.New("profile does not exist")
ErrNoProfileEndpointField = errors.New("profile does not have required field `endpoint`")
)
func GetProfileConfig(path string, profileName string) (ProfileConfig, error) {
config, err := readFusionConfig(path)
if err != nil {
return ProfileConfig{}, fmt.Errorf("cannot read fusion config: %s", err)
}
if profileName == "" {
profileName = config.DefaultProfile
}
if profileName == "" {
return ProfileConfig{}, ErrNoDefaultProfileField
}
return parseProfile(config, profileName)
}
func GetHomeConfigPath() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
configPath := filepath.Join(homeDir, ".pure", "fusion.json")
return configPath, err
}
func readFusionConfig(path string) (fusionConfig, error) {
var config fusionConfig
file, err := os.Open(path)
if err != nil {
return fusionConfig{}, err
}
defer file.Close()
err = json.NewDecoder(file).Decode(&config)
if err != nil {
return fusionConfig{}, err
}
if config.Profiles == nil {
return fusionConfig{}, ErrNoProfilesField
}
return config, nil
}
func parseProfile(config fusionConfig, profileName string) (ProfileConfig, error) {
if config.Profiles == nil {
return ProfileConfig{}, ErrNoProfilesField
}
profile, ok := config.Profiles[profileName]
if !ok {
return ProfileConfig{}, fmt.Errorf("%s. profile name: %s", ErrNoProfileExists, profileName)
}
if (profile.IssuerId == "" || profile.PrivateKeyFile == "") && profile.AccessToken == "" && profile.PrivateKey == "" {
return ProfileConfig{}, ErrNoRequiredAuthFields
}
return profile, nil
}