Store local credentials as structured JSON
This commit is contained in:
1 parent
6029850d08
commit
b73becb579
2 files changed
+34
-7
No files matched your search
@@ -22,6 +22,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
@@ -47,6 +48,11 @@ func tokenPath() string {
|
||||
return "token.txt"
|
||||
}
|
||||
|
||||
// tokenFile is token.txt's on-disk shape.
|
||||
type tokenFile struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
func randomHex(n int) (string, error) {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
@@ -68,15 +74,22 @@ func resolveToken(cfg config) (token string, generated bool, err error) {
|
||||
}
|
||||
path := tokenPath()
|
||||
if data, rerr := os.ReadFile(path); rerr == nil {
|
||||
if t := strings.TrimSpace(string(data)); t != "" {
|
||||
return t, false, nil
|
||||
var tf tokenFile
|
||||
if jerr := json.Unmarshal(data, &tf); jerr == nil {
|
||||
if t := strings.TrimSpace(tf.Token); t != "" {
|
||||
return t, false, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
t, gerr := randomHex(tokenBytes)
|
||||
if gerr != nil {
|
||||
return "", false, fmt.Errorf("couldn't generate a token: %w", gerr)
|
||||
}
|
||||
if werr := os.WriteFile(path, []byte(t), 0600); werr != nil {
|
||||
blob, merr := json.MarshalIndent(tokenFile{Token: t}, "", " ")
|
||||
if merr != nil {
|
||||
return "", false, fmt.Errorf("couldn't encode token.txt: %w", merr)
|
||||
}
|
||||
if werr := os.WriteFile(path, blob, 0600); werr != nil {
|
||||
return "", false, fmt.Errorf("couldn't save token.txt: %w", werr)
|
||||
}
|
||||
return t, true, nil
|
||||
|
||||
Reference in new issue
Block a user