forked from RiotGames/key-conjurer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
321 lines (256 loc) · 6.56 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package main
import (
"encoding/csv"
"encoding/json"
"errors"
"io"
"os"
"path/filepath"
"sort"
"time"
"strings"
"golang.org/x/oauth2"
)
type TokenSet struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
IDToken string `json:"id_token"`
Expiry time.Time `json:"expiry"`
TokenType string `json:"token_type"`
}
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
Alias string `json:"alias"`
MostRecentRole string `json:"most_recent_role"`
}
func (a *Account) NormalizeName() string {
magicPrefixes := []string{"AWS - ", "Tencent - "}
name := a.Name
for _, prefix := range magicPrefixes {
name = strings.TrimPrefix(name, prefix)
}
return name
}
func (a *Account) IsNameMatch(name string) bool {
// Purposefully not checking the lowercase version of app.Alias
// as the user should match the alias provided
if strings.EqualFold(a.Name, name) {
return true
}
if strings.EqualFold(a.NormalizeName(), name) {
return true
}
if a.Alias == name {
return true
}
return false
}
type accountSet struct {
accounts map[string]*Account
}
// need support Aws and Tencent
func generateDefaultAlias(name string) string {
magicPrefixes := []string{"AWS -", "Tencent -", "Tencent Cloud -"}
for _, prefix := range magicPrefixes {
name = strings.TrimPrefix(name, prefix)
name = strings.TrimSpace(name)
}
return strings.ToLower(strings.ReplaceAll(name, " ", "-"))
}
func (a *accountSet) ForEach(f func(id string, account Account, alias string)) {
// Golang does not maintain the order of maps, so we create a slice which is sorted instead.
var accounts []*Account
for _, acc := range a.accounts {
accounts = append(accounts, acc)
}
sort.SliceStable(accounts, func(i, j int) bool {
return accounts[i].Name < accounts[j].Name
})
for _, acc := range accounts {
f(acc.ID, *acc, acc.Alias)
}
}
// Add adds an account to the set.
func (a *accountSet) Add(id string, account Account) {
// TODO: This is bad
if a.accounts == nil {
a.accounts = make(map[string]*Account)
}
a.accounts[id] = &account
}
// Unalias will remove all aliases for an account that matches the given name or given alias.
func (a *accountSet) Unalias(name string) bool {
for _, acc := range a.accounts {
if acc.IsNameMatch(name) {
acc.Alias = ""
return true
}
}
return false
}
func (a accountSet) Resolve(name string) (*Account, bool) {
for k, acc := range a.accounts {
if k == name {
return acc, true
}
if acc.IsNameMatch(name) {
return acc, true
}
}
return nil, false
}
func (a accountSet) Alias(id, name string) bool {
entry, ok := a.accounts[id]
if !ok {
return false
}
entry.Alias = name
return true
}
func (a *accountSet) MarshalJSON() ([]byte, error) {
return json.Marshal(a.accounts)
}
func (a *accountSet) UnmarshalJSON(buf []byte) error {
var m map[string]Account
if err := json.Unmarshal(buf, &m); err != nil {
return err
}
// Now we just need to copy each entry into the set itself
for id, val := range m {
a.Add(id, val)
}
return nil
}
func (a *accountSet) ReplaceWith(other []Account) {
if a.accounts == nil {
a.accounts = make(map[string]*Account)
}
m := map[string]struct{}{}
for _, acc := range other {
clone := acc
// Preserve the alias if the account ID is the same and it already exists
if entry, ok := a.accounts[acc.ID]; ok {
// The name is the only thing that might change.
entry.Name = acc.Name
} else {
a.accounts[acc.ID] = &clone
}
m[acc.ID] = struct{}{}
}
for k := range a.accounts {
if _, ok := m[k]; !ok {
delete(a.accounts, k)
}
}
}
func (a accountSet) WriteTable(w io.Writer, withHeaders bool) {
tbl := csv.NewWriter(w)
tbl.Comma = '\t'
if withHeaders {
tbl.Write([]string{"id", "name", "alias"})
}
a.ForEach(func(id string, acc Account, alias string) {
tbl.Write([]string{id, acc.Name, alias})
})
tbl.Flush()
}
// Config stores all information related to the user
type Config struct {
Accounts *accountSet `json:"accounts"`
TTL uint `json:"ttl"`
TimeRemaining uint `json:"time_remaining"`
Tokens *TokenSet `json:"tokens"`
LastUsedAccount *string `json:"last_used_account"`
}
func (c Config) GetOAuthToken() (*TokenSet, bool) {
return c.Tokens, c.Tokens != nil
}
func HasTokenExpired(tok *TokenSet) bool {
if tok == nil {
return true
}
if tok.Expiry.IsZero() {
return false
}
return time.Now().After(tok.Expiry)
}
func (c *Config) SaveOAuthToken(tok *oauth2.Token) error {
if tok == nil {
c.Tokens = nil
return nil
}
idToken, _ := tok.Extra("id_token").(string)
tok2 := TokenSet{
AccessToken: tok.AccessToken,
RefreshToken: tok.RefreshToken,
TokenType: tok.TokenType,
Expiry: tok.Expiry,
IDToken: idToken,
}
c.Tokens = &tok2
return nil
}
// Write writes the config to the file provided overwriting the file if it exists
func (c *Config) Write(w io.Writer) error {
enc := json.NewEncoder(w)
return enc.Encode(c)
}
// Reader populates all member values of config using default values where needed
func (c *Config) Read(reader io.Reader) error {
dec := json.NewDecoder(reader)
// If we encounter an end of file, use the default values and don't treat it as an error
// This also conveniently allows someone to use /dev/null for the config file.
if err := dec.Decode(c); err != nil && !errors.Is(err, io.EOF) {
return err
}
if c.Accounts == nil {
c.Accounts = &accountSet{}
}
if c.TTL < 1 {
c.TTL = DefaultTTL
}
return nil
}
func (c *Config) AddAccount(id string, account Account) {
if c.Accounts == nil {
c.Accounts = &accountSet{accounts: make(map[string]*Account)}
}
c.Accounts.Add(id, account)
}
func (c *Config) Alias(id, name string) {
acc, ok := c.Accounts.Resolve(id)
if !ok {
return
}
acc.Alias = name
}
func (c *Config) Unalias(name string) {
acc, ok := c.Accounts.Resolve(name)
if !ok {
return
}
acc.Alias = ""
}
func (c *Config) FindAccount(name string) (*Account, bool) {
if c.Accounts == nil {
return &Account{}, false
}
val, ok := c.Accounts.Resolve(name)
if ok {
return val, true
}
return &Account{}, false
}
func (c *Config) UpdateAccounts(entries []Account) {
c.Accounts.ReplaceWith(entries)
}
func (c *Config) DumpAccounts(w io.Writer, withHeaders bool) {
c.Accounts.WriteTable(w, withHeaders)
}
func EnsureConfigFileExists(fp string) (io.ReadWriteCloser, error) {
if err := os.MkdirAll(filepath.Dir(fp), os.ModeDir|os.FileMode(0755)); err != nil {
return nil, err
}
return os.OpenFile(fp, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
}