-
Notifications
You must be signed in to change notification settings - Fork 110
/
config.go
62 lines (53 loc) · 1.27 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
package cli
import (
"encoding/json"
"os"
"path/filepath"
"github.com/golang-jwt/jwt/v4"
"go.viam.com/utils/rpc"
)
var viamDotDir = filepath.Join(os.Getenv("HOME"), ".viam")
func getCLICachePath() string {
return filepath.Join(viamDotDir, "cached_cli_config.json")
}
func configFromCache() (*Config, error) {
rd, err := os.ReadFile(getCLICachePath())
if err != nil {
return nil, err
}
var conf Config
if err := json.Unmarshal(rd, &conf); err != nil {
return nil, err
}
if err := conf.parseAuthInfo(); err != nil {
return nil, err
}
return &conf, nil
}
func removeConfigFromCache() error {
return os.Remove(getCLICachePath())
}
func storeConfigToCache(cfg *Config) error {
if err := os.MkdirAll(viamDotDir, 0o700); err != nil {
return err
}
md, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return err
}
//nolint:gosec
return os.WriteFile(getCLICachePath(), md, 0o640)
}
// Config contains stored config information for the CLI.
type Config struct {
Auth string `json:"auth"` // opaque
AuthEmail string `json:"-"`
}
func (c *Config) parseAuthInfo() error {
var claims rpc.JWTClaims
if _, _, err := jwt.NewParser().ParseUnverified(c.Auth, &claims); err != nil {
return err
}
c.AuthEmail = claims.AuthMetadata["email"]
return nil
}