-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoken.go
More file actions
97 lines (82 loc) · 1.9 KB
/
Copy pathtoken.go
File metadata and controls
97 lines (82 loc) · 1.9 KB
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
package config
import (
"errors"
"os"
"path/filepath"
"strings"
)
const (
configDir = ".createos"
tokenFile = ".token"
)
// configPath returns the path to ~/.createos
func configPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, configDir), nil
}
// tokenPath returns the path to ~/.createos/.token
func tokenPath() (string, error) {
dir, err := configPath()
if err != nil {
return "", err
}
return filepath.Join(dir, tokenFile), nil
}
// SaveToken writes the token to ~/.createos/.token
func SaveToken(token string) error {
dir, err := configPath()
if err != nil {
return err
}
if err = os.MkdirAll(dir, 0700); err != nil {
return err
}
path, err := tokenPath()
if err != nil {
return err
}
return os.WriteFile(path, []byte(strings.TrimSpace(token)), 0600)
}
// LoadToken reads the token from ~/.createos/.token
func LoadToken() (string, error) {
path, err := tokenPath()
if err != nil {
return "", err
}
data, err := os.ReadFile(path) // #nosec G304 -- path is from tokenPath() under ~/.createos/
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return "", errors.New("you're not signed in — run 'createos login' to get started")
}
return "", err
}
return strings.TrimSpace(string(data)), nil
}
// DeleteToken removes ~/.createos/.token
func DeleteToken() error {
path, err := tokenPath()
if err != nil {
return err
}
err = os.Remove(path)
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
// tokenFileExists returns true if the API key token file exists
func tokenFileExists() bool {
path, err := tokenPath()
if err != nil {
return false
}
_, err = os.Stat(path)
return err == nil
}
// IsLoggedIn returns true if the user is signed in via API key, env var, or OAuth
func IsLoggedIn() bool {
return os.Getenv("CREATEOS_API_KEY") != "" || tokenFileExists() || HasOAuthSession()
}