59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Credentials struct {
|
|
AccessKey string `json:"access_key"`
|
|
SecretKey string `json:"secret_key"`
|
|
Token string `json:"token"`
|
|
BaseURL string `json:"base_url,omitempty"`
|
|
SavedAt time.Time `json:"saved_at"`
|
|
}
|
|
|
|
func (c Credentials) Validate() error {
|
|
if strings.TrimSpace(c.AccessKey) == "" {
|
|
return errors.New("access_key is required")
|
|
}
|
|
if strings.TrimSpace(c.SecretKey) == "" {
|
|
return errors.New("secret_key is required")
|
|
}
|
|
if strings.TrimSpace(c.Token) == "" {
|
|
return errors.New("token is required")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func LoadCredentials(path string) (Credentials, error) {
|
|
b, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return Credentials{}, err
|
|
}
|
|
var c Credentials
|
|
if err := json.Unmarshal(b, &c); err != nil {
|
|
return Credentials{}, err
|
|
}
|
|
return c, c.Validate()
|
|
}
|
|
|
|
func SaveCredentials(path string, c Credentials) error {
|
|
if err := c.Validate(); err != nil {
|
|
return err
|
|
}
|
|
c.SavedAt = time.Now()
|
|
b, err := json.MarshalIndent(c, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
|
return err
|
|
}
|
|
return os.WriteFile(path, b, 0o600)
|
|
}
|