Skip to content

Commit

Permalink
Automatically create store.json file for JsonStore
Browse files Browse the repository at this point in the history
Fixes: #612
  • Loading branch information
synfinatic committed Oct 16, 2023
1 parent f178291 commit 300a1d5
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

### Bugs

* Fix bug where JsonStore was not being created #612

### New Features

* Config Wizard now prompts for `ProfileFormat` #590
Expand Down
19 changes: 13 additions & 6 deletions internal/storage/json_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ package storage

import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"

// "github.com/davecgh/go-spew/spew"
Expand All @@ -38,20 +40,24 @@ type JsonStore struct {
}

// OpenJsonStore opens our insecure JSON storage backend
func OpenJsonStore(fileName string) (*JsonStore, error) {
func OpenJsonStore(filename string) (*JsonStore, error) {
cache := JsonStore{
filename: fileName,
filename: filename,
RegisterClient: map[string]RegisterClientData{},
StartDeviceAuth: map[string]StartDeviceAuthData{},
CreateTokenResponse: map[string]CreateTokenResponse{},
RoleCredentials: map[string]RoleCredentials{},
StaticCredentials: map[string]StaticCredentials{},
}

cacheBytes, err := os.ReadFile(fileName)
if err != nil {
log.Infof("Creating new cache file: %s", fileName)
} else if len(cacheBytes) > 0 {
cacheBytes, err := os.ReadFile(filename)
if errors.Is(err, fs.ErrNotExist) {
return &cache, nil
} else if err != nil {
return &cache, fmt.Errorf("Unable to open %s: %s", filename, err.Error())
}

if len(cacheBytes) > 0 {
err = json.Unmarshal(cacheBytes, &cache)
}

Expand All @@ -66,6 +72,7 @@ func (jc *JsonStore) save() error {
log.WithError(err).Errorf("Unable to marshal json")
return err
}

err = utils.EnsureDirExists(jc.filename)
if err != nil {
return err
Expand Down
22 changes: 22 additions & 0 deletions internal/storage/json_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,28 @@ import (

const TEST_JSON_STORE_FILE = "./testdata/store.json"

func TestNewFile(t *testing.T) {
fname := "./testdata/new-store.json"
defer os.Remove(fname)
s, err := OpenJsonStore(fname)
assert.Nil(t, err)

assert.Error(t, s.GetRegisterClientData("foobar", &RegisterClientData{}))

err = s.save()
assert.Nil(t, err)
}

func TestBadFilePerms(t *testing.T) {
fname := "./testdata/new-store.json"
defer os.Remove(fname)
err := os.WriteFile(fname, []byte{}, 0000)
assert.NoError(t, err)

_, err = OpenJsonStore(fname)
assert.Error(t, err)
}

type JsonStoreTestSuite struct {
suite.Suite
json *JsonStore
Expand Down

0 comments on commit 300a1d5

Please sign in to comment.