From 6b404f56c913c56a119532dc4dc376fe2e82dd89 Mon Sep 17 00:00:00 2001 From: lash Date: Thu, 16 Jan 2025 11:34:48 +0000 Subject: [PATCH 1/6] Factor out command parse and exec logic --- devtools/admin/admin_numbers.json | 7 -- devtools/admin/commands/seed.go | 47 -------------- devtools/admin/main.go | 67 +++++++++++++++++-- handlers/application/menuhandler.go | 1 + internal/cmd/cmd.go | 99 +++++++++++++++++++++++++++++ 5 files changed, 162 insertions(+), 59 deletions(-) delete mode 100644 devtools/admin/admin_numbers.json delete mode 100644 devtools/admin/commands/seed.go create mode 100644 internal/cmd/cmd.go diff --git a/devtools/admin/admin_numbers.json b/devtools/admin/admin_numbers.json deleted file mode 100644 index ca58a23..0000000 --- a/devtools/admin/admin_numbers.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "admins": [ - { - "phonenumber" : "" - } - ] -} \ No newline at end of file diff --git a/devtools/admin/commands/seed.go b/devtools/admin/commands/seed.go deleted file mode 100644 index ec639b5..0000000 --- a/devtools/admin/commands/seed.go +++ /dev/null @@ -1,47 +0,0 @@ -package commands - -import ( - "context" - "encoding/json" - "os" - - "git.defalsify.org/vise.git/logging" - "git.grassecon.net/grassrootseconomics/sarafu-vise/store" -) - -var ( - logg = logging.NewVanilla().WithDomain("adminstore") -) - -type Admin struct { - PhoneNumber string `json:"phonenumber"` -} - -type Config struct { - Admins []Admin `json:"admins"` -} - -func Seed(ctx context.Context) error { - var config Config - adminstore, err := store.NewAdminStore(ctx, "../admin_numbers") - store := adminstore.FsStore - if err != nil { - return err - } - defer store.Close() - data, err := os.ReadFile("admin_numbers.json") - if err != nil { - return err - } - if err := json.Unmarshal(data, &config); err != nil { - return err - } - for _, admin := range config.Admins { - err := store.Put(ctx, []byte(admin.PhoneNumber), []byte("1")) - if err != nil { - logg.Printf(logging.LVL_DEBUG, "Failed to insert admin number", admin.PhoneNumber) - return err - } - } - return nil -} diff --git a/devtools/admin/main.go b/devtools/admin/main.go index defbbf6..f65440b 100644 --- a/devtools/admin/main.go +++ b/devtools/admin/main.go @@ -2,16 +2,73 @@ package main import ( "context" - "log" + "flag" + "fmt" + "os" + "path" - "git.grassecon.net/grassrootseconomics/sarafu-vise/devtools/admin/commands" + "git.defalsify.org/vise.git/logging" + "git.defalsify.org/vise.git/asm" + + "git.grassecon.net/grassrootseconomics/sarafu-vise/config" + "git.grassecon.net/grassrootseconomics/visedriver/storage" + "git.grassecon.net/grassrootseconomics/sarafu-vise/internal/cmd" +) + +var ( + logg = logging.NewVanilla().WithContextKey("SessionId") + scriptDir = path.Join("services", "registration") ) func main() { - ctx := context.Background() - err := commands.Seed(ctx) + config.LoadConfig() + + var sessionId string + var connStr string + + flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") + flag.StringVar(&connStr, "c", "", "connection string") + flag.Parse() + + + if connStr == "" { + connStr = config.DbConn() + } + connData, err := storage.ToConnData(connStr) if err != nil { - log.Fatalf("Failed to initialize a list of admins with error %s", err) + fmt.Fprintf(os.Stderr, "connstr err: %v\n", err) + os.Exit(1) + } + ctx := context.Background() + ctx = context.WithValue(ctx, "SessionId", sessionId) + + pfp := path.Join(scriptDir, "pp.csv") + flagParser := asm.NewFlagParser().WithDebug() + _, err = flagParser.Load(pfp) + if err != nil { + fmt.Fprintf(os.Stderr, "flagparser fail: %v\n", err) + os.Exit(1) + } + + x := cmd.NewCmd(connData, sessionId, flagParser) + err = x.Parse(flag.Args()) + if err != nil { + fmt.Fprintf(os.Stderr, "cmd parse fail: %v\n", err) + os.Exit(1) + } + + logg.Infof("start command", "conn", connData, "subcmd", x) + + menuStorageService := storage.NewMenuStorageService(connData, "") + if err != nil { + fmt.Fprintf(os.Stderr, "menu storage service error: %v\n", err) + os.Exit(1) + } + + err = x.Exec(ctx, menuStorageService) + if err != nil { + fmt.Fprintf(os.Stderr, "cmd exec error: %v\n", err) + os.Exit(1) } } diff --git a/handlers/application/menuhandler.go b/handlers/application/menuhandler.go index 28f6854..abdef28 100644 --- a/handlers/application/menuhandler.go +++ b/handlers/application/menuhandler.go @@ -37,6 +37,7 @@ var ( translationDir = path.Join(scriptDir, "locale") ) +// TODO: this is only in use in testing, should be moved to test domain and/or replaced by asm.FlagParser // FlagManager handles centralized flag management type FlagManager struct { parser *asm.FlagParser diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go new file mode 100644 index 0000000..3bc817f --- /dev/null +++ b/internal/cmd/cmd.go @@ -0,0 +1,99 @@ +package cmd + +import ( + "context" + "fmt" + + "git.defalsify.org/vise.git/asm" + "git.defalsify.org/vise.git/logging" + "git.grassecon.net/grassrootseconomics/visedriver/storage" +) + +var ( + logg = logging.NewVanilla().WithDomain("cmd").WithContextKey("SessionId") +) + +type Cmd struct { + sessionId string + conn storage.ConnData + flagParser *asm.FlagParser + cmd int + enable bool + exec func(ctx context.Context, ss storage.StorageService) error +} + +func NewCmd(conn storage.ConnData, sessionId string, flagParser *asm.FlagParser) *Cmd { + return &Cmd{ + conn: conn, + sessionId: sessionId, + flagParser: flagParser, + } +} + +func (c *Cmd) Exec(ctx context.Context, ss storage.StorageService) error { + return c.exec(ctx, ss) +} + +func (c *Cmd) execAdmin(ctx context.Context, ss storage.StorageService) error { + pe, err := ss.GetPersister(ctx) + if err != nil { + return err + } + err = pe.Load(c.sessionId) + if err != nil { + return err + } + defer func() { + err := pe.Save(c.sessionId) + if err != nil { + logg.ErrorCtxf(ctx, "failed persister save: %v", err) + } + }() + + st := pe.GetState() + flag, err := c.flagParser.GetFlag("flag_admin_privilege") + if err != nil { + return err + } + if c.enable { + logg.InfoCtxf(ctx, "setting admin flag", "flag", flag) + st.SetFlag(flag) + } else { + st.ResetFlag(flag) + } + return nil +} + +func (c *Cmd) parseCmdAdmin(cmd string, param string, more []string) (bool, error) { + if cmd == "admin" { + if param == "1" { + c.enable = true + } else if param != "0" { + return false, fmt.Errorf("invalid parameter: %v", param) + } + c.exec = c.execAdmin + return true, nil + } + return false, nil +} + +func (c *Cmd) Parse(args []string) error { + if len(args) < 2 { + return fmt.Errorf("Wrong number of arguments: %v", args) + } + cmd := args[0] + param := args[1] + args = args[2:] + + r, err := c.parseCmdAdmin(cmd, param, args) + if err != nil { + return err + } + if r { + return nil + } + + return fmt.Errorf("unknown subcommand: %s", cmd) +} + + -- 2.45.2 From 879baa03fcfa5a7fdf07edb5bd853791525b9521 Mon Sep 17 00:00:00 2001 From: lash Date: Thu, 16 Jan 2025 13:50:18 +0000 Subject: [PATCH 2/6] Use FlagManager instead of asm flagparser directly --- devtools/admin/main.go | 7 +- handlers/application/menuhandler.go | 14 ++-- handlers/application/menuhandler_test.go | 102 +++++++++++------------ handlers/local.go | 17 ++-- internal/cmd/cmd.go | 6 +- 5 files changed, 71 insertions(+), 75 deletions(-) diff --git a/devtools/admin/main.go b/devtools/admin/main.go index f65440b..3ef0466 100644 --- a/devtools/admin/main.go +++ b/devtools/admin/main.go @@ -8,11 +8,11 @@ import ( "path" "git.defalsify.org/vise.git/logging" - "git.defalsify.org/vise.git/asm" "git.grassecon.net/grassrootseconomics/sarafu-vise/config" "git.grassecon.net/grassrootseconomics/visedriver/storage" "git.grassecon.net/grassrootseconomics/sarafu-vise/internal/cmd" + "git.grassecon.net/grassrootseconomics/sarafu-vise/handlers/application" ) var ( @@ -41,10 +41,9 @@ func main() { } ctx := context.Background() ctx = context.WithValue(ctx, "SessionId", sessionId) - + pfp := path.Join(scriptDir, "pp.csv") - flagParser := asm.NewFlagParser().WithDebug() - _, err = flagParser.Load(pfp) + flagParser, err := application.NewFlagManager(pfp) if err != nil { fmt.Fprintf(os.Stderr, "flagparser fail: %v\n", err) os.Exit(1) diff --git a/handlers/application/menuhandler.go b/handlers/application/menuhandler.go index abdef28..d03d68b 100644 --- a/handlers/application/menuhandler.go +++ b/handlers/application/menuhandler.go @@ -40,7 +40,7 @@ var ( // TODO: this is only in use in testing, should be moved to test domain and/or replaced by asm.FlagParser // FlagManager handles centralized flag management type FlagManager struct { - parser *asm.FlagParser + *asm.FlagParser } // NewFlagManager creates a new FlagManager instance @@ -52,13 +52,17 @@ func NewFlagManager(csvPath string) (*FlagManager, error) { } return &FlagManager{ - parser: parser, + FlagParser: parser, }, nil } +func (fm *FlagManager) SetDebug() { + fm.FlagParser = fm.FlagParser.WithDebug() +} + // GetFlag retrieves a flag value by its label func (fm *FlagManager) GetFlag(label string) (uint32, error) { - return fm.parser.GetFlag(label) + return fm.FlagParser.GetFlag(label) } type MenuHandlers struct { @@ -67,7 +71,7 @@ type MenuHandlers struct { ca cache.Memory userdataStore store.DataStore adminstore *store.AdminStore - flagManager *asm.FlagParser + flagManager *FlagManager accountService remote.AccountService prefixDb storedb.PrefixDb profile *profile.Profile @@ -75,7 +79,7 @@ type MenuHandlers struct { } // NewHandlers creates a new instance of the Handlers struct with the provided dependencies. -func NewMenuHandlers(appFlags *asm.FlagParser, userdataStore db.Db, adminstore *store.AdminStore, accountService remote.AccountService, replaceSeparatorFunc func(string) string) (*MenuHandlers, error) { +func NewMenuHandlers(appFlags *FlagManager, userdataStore db.Db, adminstore *store.AdminStore, accountService remote.AccountService, replaceSeparatorFunc func(string) string) (*MenuHandlers, error) { if userdataStore == nil { return nil, fmt.Errorf("cannot create handler with nil userdata store") } diff --git a/handlers/application/menuhandler_test.go b/handlers/application/menuhandler_test.go index 3244ce4..f981d7c 100644 --- a/handlers/application/menuhandler_test.go +++ b/handlers/application/menuhandler_test.go @@ -84,7 +84,7 @@ func TestNewMenuHandlers(t *testing.T) { // Test case for valid UserDataStore t.Run("Valid UserDataStore", func(t *testing.T) { - handlers, err := NewMenuHandlers(fm.parser, store, nil, &accountService, mockReplaceSeparator) + handlers, err := NewMenuHandlers(fm, store, nil, &accountService, mockReplaceSeparator) if err != nil { t.Fatalf("expected no error, got %v", err) } @@ -108,7 +108,7 @@ func TestNewMenuHandlers(t *testing.T) { // Test case for nil UserDataStore t.Run("Nil UserDataStore", func(t *testing.T) { - handlers, err := NewMenuHandlers(fm.parser, nil, nil, &accountService, mockReplaceSeparator) + handlers, err := NewMenuHandlers(fm, nil, nil, &accountService, mockReplaceSeparator) if err == nil { t.Fatal("expected an error, got none") } @@ -161,7 +161,7 @@ func TestInit(t *testing.T) { setup: func() (*MenuHandlers, context.Context) { pe := persist.NewPersister(testStore).WithSession(sessionId).WithContent(st, ca) h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, adminstore: adminstore, pe: pe, } @@ -177,7 +177,7 @@ func TestInit(t *testing.T) { setup: func() (*MenuHandlers, context.Context) { pe := persist.NewPersister(testStore).WithSession("0712345678").WithContent(st, ca) h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, adminstore: adminstore, pe: pe, } @@ -193,7 +193,7 @@ func TestInit(t *testing.T) { setup: func() (*MenuHandlers, context.Context) { pe := persist.NewPersister(testStore).WithSession(sessionId).WithContent(st, ca) h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, adminstore: adminstore, pe: pe, } @@ -256,7 +256,7 @@ func TestCreateAccount(t *testing.T) { h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } mockAccountService.On("CreateAccount").Return(tt.serverResponse, nil) @@ -320,7 +320,7 @@ func TestSaveFirstname(t *testing.T) { // Create the MenuHandlers instance with the mock store h := &MenuHandlers{ userdataStore: store, - flagManager: fm.parser, + flagManager: fm, st: mockState, } @@ -365,7 +365,7 @@ func TestSaveFamilyname(t *testing.T) { h := &MenuHandlers{ userdataStore: store, st: mockState, - flagManager: fm.parser, + flagManager: fm, } // Call the method @@ -408,7 +408,7 @@ func TestSaveYoB(t *testing.T) { // Create the MenuHandlers instance with the mock store h := &MenuHandlers{ userdataStore: store, - flagManager: fm.parser, + flagManager: fm, st: mockState, } @@ -452,7 +452,7 @@ func TestSaveLocation(t *testing.T) { // Create the MenuHandlers instance with the mock store h := &MenuHandlers{ userdataStore: store, - flagManager: fm.parser, + flagManager: fm, st: mockState, } @@ -496,7 +496,7 @@ func TestSaveOfferings(t *testing.T) { // Create the MenuHandlers instance with the mock store h := &MenuHandlers{ userdataStore: store, - flagManager: fm.parser, + flagManager: fm, st: mockState, } @@ -564,7 +564,7 @@ func TestSaveGender(t *testing.T) { h := &MenuHandlers{ userdataStore: store, st: mockState, - flagManager: fm.parser, + flagManager: fm, } expectedResult := resource.Result{} @@ -595,11 +595,11 @@ func TestSaveTemporaryPin(t *testing.T) { log.Fatal(err) } - flag_incorrect_pin, _ := fm.parser.GetFlag("flag_incorrect_pin") + flag_incorrect_pin, _ := fm.GetFlag("flag_incorrect_pin") // Create the MenuHandlers instance with the mock flag manager h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, userdataStore: store, } @@ -812,7 +812,7 @@ func TestSetLanguage(t *testing.T) { // Create the MenuHandlers instance with the mock flag manager h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, userdataStore: store, st: mockState, } @@ -846,7 +846,7 @@ func TestResetAllowUpdate(t *testing.T) { log.Fatal(err) } - flag_allow_update, _ := fm.parser.GetFlag("flag_allow_update") + flag_allow_update, _ := fm.GetFlag("flag_allow_update") // Define test cases tests := []struct { @@ -867,7 +867,7 @@ func TestResetAllowUpdate(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // Create the MenuHandlers instance with the mock flag manager h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, } // Call the method @@ -888,7 +888,7 @@ func TestResetAccountAuthorized(t *testing.T) { log.Fatal(err) } - flag_account_authorized, _ := fm.parser.GetFlag("flag_account_authorized") + flag_account_authorized, _ := fm.GetFlag("flag_account_authorized") // Define test cases tests := []struct { @@ -909,7 +909,7 @@ func TestResetAccountAuthorized(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // Create the MenuHandlers instance with the mock flag manager h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, } // Call the method @@ -933,8 +933,8 @@ func TestIncorrectPinReset(t *testing.T) { log.Fatal(err) } - flag_incorrect_pin, _ := fm.parser.GetFlag("flag_incorrect_pin") - flag_account_blocked, _ := fm.parser.GetFlag("flag_account_blocked") + flag_incorrect_pin, _ := fm.GetFlag("flag_incorrect_pin") + flag_account_blocked, _ := fm.GetFlag("flag_account_blocked") ctx = context.WithValue(ctx, "SessionId", sessionId) @@ -992,7 +992,7 @@ func TestIncorrectPinReset(t *testing.T) { // Create the MenuHandlers instance with the mock flag manager h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, userdataStore: store, } @@ -1014,7 +1014,7 @@ func TestResetIncorrectYob(t *testing.T) { log.Fatal(err) } - flag_incorrect_date_format, _ := fm.parser.GetFlag("flag_incorrect_date_format") + flag_incorrect_date_format, _ := fm.GetFlag("flag_incorrect_date_format") // Define test cases tests := []struct { @@ -1035,7 +1035,7 @@ func TestResetIncorrectYob(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // Create the MenuHandlers instance with the mock flag manager h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, } // Call the method @@ -1073,7 +1073,7 @@ func TestAuthorize(t *testing.T) { h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, st: mockState, } @@ -1141,12 +1141,12 @@ func TestVerifyYob(t *testing.T) { // Create required mocks mockAccountService := new(mocks.MockAccountService) mockState := state.NewState(16) - flag_incorrect_date_format, _ := fm.parser.GetFlag("flag_incorrect_date_format") + flag_incorrect_date_format, _ := fm.GetFlag("flag_incorrect_date_format") ctx := context.WithValue(context.Background(), "SessionId", sessionId) h := &MenuHandlers{ accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, st: mockState, } @@ -1206,14 +1206,14 @@ func TestVerifyCreatePin(t *testing.T) { mockAccountService := new(mocks.MockAccountService) mockState := state.NewState(16) - flag_valid_pin, _ := fm.parser.GetFlag("flag_valid_pin") - flag_pin_mismatch, _ := fm.parser.GetFlag("flag_pin_mismatch") - flag_pin_set, _ := fm.parser.GetFlag("flag_pin_set") + flag_valid_pin, _ := fm.GetFlag("flag_valid_pin") + flag_pin_mismatch, _ := fm.GetFlag("flag_pin_mismatch") + flag_pin_set, _ := fm.GetFlag("flag_pin_set") h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, st: mockState, } @@ -1307,7 +1307,7 @@ func TestCheckAccountStatus(t *testing.T) { h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } err = store.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(tt.publicKey)) @@ -1347,7 +1347,7 @@ func TestTransactionReset(t *testing.T) { h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } tests := []struct { name string @@ -1387,14 +1387,14 @@ func TestResetTransactionAmount(t *testing.T) { t.Logf(err.Error()) } - flag_invalid_amount, _ := fm.parser.GetFlag("flag_invalid_amount") + flag_invalid_amount, _ := fm.GetFlag("flag_invalid_amount") mockAccountService := new(mocks.MockAccountService) h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } tests := []struct { @@ -1431,14 +1431,14 @@ func TestInitiateTransaction(t *testing.T) { if err != nil { t.Logf(err.Error()) } - account_authorized_flag, _ := fm.parser.GetFlag("flag_account_authorized") + account_authorized_flag, _ := fm.GetFlag("flag_account_authorized") mockAccountService := new(mocks.MockAccountService) h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } tests := []struct { @@ -1524,7 +1524,7 @@ func TestQuit(t *testing.T) { if err != nil { t.Logf(err.Error()) } - flag_account_authorized, _ := fm.parser.GetFlag("flag_account_authorized") + flag_account_authorized, _ := fm.GetFlag("flag_account_authorized") mockAccountService := new(mocks.MockAccountService) @@ -1534,7 +1534,7 @@ func TestQuit(t *testing.T) { h := &MenuHandlers{ accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } tests := []struct { name string @@ -1577,14 +1577,14 @@ func TestValidateAmount(t *testing.T) { ctx, store := InitializeTestStore(t) ctx = context.WithValue(ctx, "SessionId", sessionId) - flag_invalid_amount, _ := fm.parser.GetFlag("flag_invalid_amount") + flag_invalid_amount, _ := fm.GetFlag("flag_invalid_amount") mockAccountService := new(mocks.MockAccountService) h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } tests := []struct { name string @@ -1651,8 +1651,8 @@ func TestValidateRecipient(t *testing.T) { ctx, store := InitializeTestStore(t) ctx = context.WithValue(ctx, "SessionId", sessionId) - flag_invalid_recipient, _ := fm.parser.GetFlag("flag_invalid_recipient") - flag_invalid_recipient_with_invite, _ := fm.parser.GetFlag("flag_invalid_recipient_with_invite") + flag_invalid_recipient, _ := fm.GetFlag("flag_invalid_recipient") + flag_invalid_recipient_with_invite, _ := fm.GetFlag("flag_invalid_recipient_with_invite") // Define test cases tests := []struct { @@ -1704,7 +1704,7 @@ func TestValidateRecipient(t *testing.T) { mockAccountService := new(mocks.MockAccountService) // Create the MenuHandlers instance h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, userdataStore: store, accountService: mockAccountService, } @@ -1867,10 +1867,10 @@ func TestVerifyNewPin(t *testing.T) { fm, _ := NewFlagManager(flagsPath) - flag_valid_pin, _ := fm.parser.GetFlag("flag_valid_pin") + flag_valid_pin, _ := fm.GetFlag("flag_valid_pin") mockAccountService := new(mocks.MockAccountService) h := &MenuHandlers{ - flagManager: fm.parser, + flagManager: fm, accountService: mockAccountService, } ctx := context.WithValue(context.Background(), "SessionId", sessionId) @@ -1913,11 +1913,11 @@ func TestConfirmPin(t *testing.T) { ctx = context.WithValue(ctx, "SessionId", sessionId) fm, _ := NewFlagManager(flagsPath) - flag_pin_mismatch, _ := fm.parser.GetFlag("flag_pin_mismatch") + flag_pin_mismatch, _ := fm.GetFlag("flag_pin_mismatch") mockAccountService := new(mocks.MockAccountService) h := &MenuHandlers{ userdataStore: store, - flagManager: fm.parser, + flagManager: fm, accountService: mockAccountService, } @@ -2047,7 +2047,7 @@ func TestSetDefaultVoucher(t *testing.T) { h := &MenuHandlers{ userdataStore: store, accountService: mockAccountService, - flagManager: fm.parser, + flagManager: fm, } err := store.WriteEntry(ctx, sessionId, storedb.DATA_PUBLIC_KEY, []byte(publicKey)) @@ -2155,7 +2155,7 @@ func TestViewVoucher(t *testing.T) { h := &MenuHandlers{ userdataStore: store, - flagManager: fm.parser, + flagManager: fm, prefixDb: spdb, } @@ -2228,7 +2228,7 @@ func TestGetVoucherDetails(t *testing.T) { h := &MenuHandlers{ userdataStore: store, - flagManager: fm.parser, + flagManager: fm, accountService: mockAccountService, } err = store.WriteEntry(ctx, sessionId, storedb.DATA_ACTIVE_ADDRESS, []byte(tokA_AAddress)) diff --git a/handlers/local.go b/handlers/local.go index 5650cf0..a060f1a 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -4,7 +4,6 @@ import ( "context" "strings" - "git.defalsify.org/vise.git/asm" "git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/persist" @@ -19,17 +18,8 @@ type HandlerService interface { GetHandler() (*application.MenuHandlers, error) } -func getParser(fp string, debug bool) (*asm.FlagParser, error) { - flagParser := asm.NewFlagParser().WithDebug() - _, err := flagParser.Load(fp) - if err != nil { - return nil, err - } - return flagParser, nil -} - type LocalHandlerService struct { - Parser *asm.FlagParser + Parser *application.FlagManager DbRs *resource.DbResource Pe *persist.Persister UserdataStore *db.Db @@ -39,10 +29,13 @@ type LocalHandlerService struct { } func NewLocalHandlerService(ctx context.Context, fp string, debug bool, dbResource *resource.DbResource, cfg engine.Config, rs resource.Resource) (*LocalHandlerService, error) { - parser, err := getParser(fp, debug) + parser, err := application.NewFlagManager(fp) if err != nil { return nil, err } + if debug { + parser.SetDebug() + } adminstore, err := store.NewAdminStore(ctx, "admin_numbers") if err != nil { return nil, err diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go index 3bc817f..1ebfd11 100644 --- a/internal/cmd/cmd.go +++ b/internal/cmd/cmd.go @@ -4,9 +4,9 @@ import ( "context" "fmt" - "git.defalsify.org/vise.git/asm" "git.defalsify.org/vise.git/logging" "git.grassecon.net/grassrootseconomics/visedriver/storage" + "git.grassecon.net/grassrootseconomics/sarafu-vise/handlers/application" ) var ( @@ -16,13 +16,13 @@ var ( type Cmd struct { sessionId string conn storage.ConnData - flagParser *asm.FlagParser + flagParser *application.FlagManager cmd int enable bool exec func(ctx context.Context, ss storage.StorageService) error } -func NewCmd(conn storage.ConnData, sessionId string, flagParser *asm.FlagParser) *Cmd { +func NewCmd(conn storage.ConnData, sessionId string, flagParser *application.FlagManager) *Cmd { return &Cmd{ conn: conn, sessionId: sessionId, -- 2.45.2 From ecee5b4dee6720eff843afecf002415ca47eac97 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 17 Jan 2025 11:35:20 +0300 Subject: [PATCH 3/6] remove code that reset the admin flag based on the adminstore --- handlers/application/menuhandler.go | 9 --------- 1 file changed, 9 deletions(-) diff --git a/handlers/application/menuhandler.go b/handlers/application/menuhandler.go index d03d68b..45aa369 100644 --- a/handlers/application/menuhandler.go +++ b/handlers/application/menuhandler.go @@ -138,15 +138,6 @@ func (h *MenuHandlers) Init(ctx context.Context, sym string, input []byte) (reso ctx = context.WithValue(ctx, "SessionId", sessionId) } - flag_admin_privilege, _ := h.flagManager.GetFlag("flag_admin_privilege") - isAdmin, _ := h.adminstore.IsAdmin(sessionId) - - if isAdmin { - r.FlagSet = append(r.FlagSet, flag_admin_privilege) - } else { - r.FlagReset = append(r.FlagReset, flag_admin_privilege) - } - if h.st == nil || h.ca == nil { logg.ErrorCtxf(ctx, "perister fail in handler", "state", h.st, "cache", h.ca) return r, fmt.Errorf("cannot get state and memory for handler") -- 2.45.2 From 104db94826d7a8d5e0354511a37984ac7b3c801f Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 17 Jan 2025 11:44:33 +0300 Subject: [PATCH 4/6] remove unused adminstore --- handlers/application/menuhandler.go | 4 +-- handlers/local.go | 18 ++++------ store/adminstore.go | 51 ----------------------------- 3 files changed, 7 insertions(+), 66 deletions(-) delete mode 100644 store/adminstore.go diff --git a/handlers/application/menuhandler.go b/handlers/application/menuhandler.go index 45aa369..11b551c 100644 --- a/handlers/application/menuhandler.go +++ b/handlers/application/menuhandler.go @@ -70,7 +70,6 @@ type MenuHandlers struct { st *state.State ca cache.Memory userdataStore store.DataStore - adminstore *store.AdminStore flagManager *FlagManager accountService remote.AccountService prefixDb storedb.PrefixDb @@ -79,7 +78,7 @@ type MenuHandlers struct { } // NewHandlers creates a new instance of the Handlers struct with the provided dependencies. -func NewMenuHandlers(appFlags *FlagManager, userdataStore db.Db, adminstore *store.AdminStore, accountService remote.AccountService, replaceSeparatorFunc func(string) string) (*MenuHandlers, error) { +func NewMenuHandlers(appFlags *FlagManager, userdataStore db.Db, accountService remote.AccountService, replaceSeparatorFunc func(string) string) (*MenuHandlers, error) { if userdataStore == nil { return nil, fmt.Errorf("cannot create handler with nil userdata store") } @@ -94,7 +93,6 @@ func NewMenuHandlers(appFlags *FlagManager, userdataStore db.Db, adminstore *sto h := &MenuHandlers{ userdataStore: userDb, flagManager: appFlags, - adminstore: adminstore, accountService: accountService, prefixDb: prefixDb, profile: &profile.Profile{Max: 6}, diff --git a/handlers/local.go b/handlers/local.go index a060f1a..325fe89 100644 --- a/handlers/local.go +++ b/handlers/local.go @@ -11,7 +11,6 @@ import ( "git.grassecon.net/grassrootseconomics/sarafu-api/remote" "git.grassecon.net/grassrootseconomics/sarafu-vise/handlers/application" - "git.grassecon.net/grassrootseconomics/sarafu-vise/store" ) type HandlerService interface { @@ -23,7 +22,6 @@ type LocalHandlerService struct { DbRs *resource.DbResource Pe *persist.Persister UserdataStore *db.Db - AdminStore *store.AdminStore Cfg engine.Config Rs resource.Resource } @@ -36,16 +34,12 @@ func NewLocalHandlerService(ctx context.Context, fp string, debug bool, dbResour if debug { parser.SetDebug() } - adminstore, err := store.NewAdminStore(ctx, "admin_numbers") - if err != nil { - return nil, err - } + return &LocalHandlerService{ - Parser: parser, - DbRs: dbResource, - AdminStore: adminstore, - Cfg: cfg, - Rs: rs, + Parser: parser, + DbRs: dbResource, + Cfg: cfg, + Rs: rs, }, nil } @@ -62,7 +56,7 @@ func (ls *LocalHandlerService) GetHandler(accountService remote.AccountService) return strings.ReplaceAll(input, ":", ls.Cfg.MenuSeparator) } - appHandlers, err := application.NewMenuHandlers(ls.Parser, *ls.UserdataStore, ls.AdminStore, accountService, replaceSeparatorFunc) + appHandlers, err := application.NewMenuHandlers(ls.Parser, *ls.UserdataStore, accountService, replaceSeparatorFunc) if err != nil { return nil, err } diff --git a/store/adminstore.go b/store/adminstore.go deleted file mode 100644 index d20c5e1..0000000 --- a/store/adminstore.go +++ /dev/null @@ -1,51 +0,0 @@ -package store - -import ( - "context" - - "git.defalsify.org/vise.git/db" - fsdb "git.defalsify.org/vise.git/db/fs" - "git.defalsify.org/vise.git/logging" -) - -var ( - logg = logging.NewVanilla().WithDomain("adminstore") -) - -type AdminStore struct { - ctx context.Context - FsStore db.Db -} - -func NewAdminStore(ctx context.Context, fileName string) (*AdminStore, error) { - fsStore, err := getFsStore(ctx, fileName) - if err != nil { - return nil, err - } - return &AdminStore{ctx: ctx, FsStore: fsStore}, nil -} - -func getFsStore(ctx context.Context, connectStr string) (db.Db, error) { - fsStore := fsdb.NewFsDb() - err := fsStore.Connect(ctx, connectStr) - fsStore.SetPrefix(db.DATATYPE_USERDATA) - if err != nil { - return nil, err - } - return fsStore, nil -} - -// Checks if the given sessionId is listed as an admin. -func (as *AdminStore) IsAdmin(sessionId string) (bool, error) { - _, err := as.FsStore.Get(as.ctx, []byte(sessionId)) - if err != nil { - if db.IsNotFound(err) { - logg.Printf(logging.LVL_INFO, "Returning false because session id was not found") - return false, nil - } else { - return false, err - } - } - - return true, nil -} -- 2.45.2 From 4b8505680b10da78772b4f8b79fafb2354a5c31c Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 17 Jan 2025 11:45:27 +0300 Subject: [PATCH 5/6] added logging --- store/vouchers.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/store/vouchers.go b/store/vouchers.go index ca8a75f..0569a60 100644 --- a/store/vouchers.go +++ b/store/vouchers.go @@ -6,10 +6,15 @@ import ( "math/big" "strings" + "git.defalsify.org/vise.git/logging" storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" dataserviceapi "github.com/grassrootseconomics/ussd-data-service/pkg/api" ) +var ( + logg = logging.NewVanilla().WithDomain("vouchers").WithContextKey("SessionId") +) + // VoucherMetadata helps organize data fields type VoucherMetadata struct { Symbols string -- 2.45.2 From 4cc0de59a7c8bb7290da317066aa9c18def83b76 Mon Sep 17 00:00:00 2001 From: alfred-mk Date: Fri, 17 Jan 2025 11:45:55 +0300 Subject: [PATCH 6/6] updated tests --- handlers/application/menuhandler_test.go | 40 +++++++----------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/handlers/application/menuhandler_test.go b/handlers/application/menuhandler_test.go index f981d7c..4c0fa7f 100644 --- a/handlers/application/menuhandler_test.go +++ b/handlers/application/menuhandler_test.go @@ -14,11 +14,11 @@ import ( "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" - "git.grassecon.net/grassrootseconomics/sarafu-api/models" - "git.grassecon.net/grassrootseconomics/sarafu-api/testutil/testservice" - "git.grassecon.net/grassrootseconomics/sarafu-api/testutil/mocks" - "git.grassecon.net/grassrootseconomics/sarafu-vise/store" "git.grassecon.net/grassrootseconomics/common/pin" + "git.grassecon.net/grassrootseconomics/sarafu-api/models" + "git.grassecon.net/grassrootseconomics/sarafu-api/testutil/mocks" + "git.grassecon.net/grassrootseconomics/sarafu-api/testutil/testservice" + "git.grassecon.net/grassrootseconomics/sarafu-vise/store" storedb "git.grassecon.net/grassrootseconomics/sarafu-vise/store/db" "github.com/alecthomas/assert/v2" @@ -84,7 +84,7 @@ func TestNewMenuHandlers(t *testing.T) { // Test case for valid UserDataStore t.Run("Valid UserDataStore", func(t *testing.T) { - handlers, err := NewMenuHandlers(fm, store, nil, &accountService, mockReplaceSeparator) + handlers, err := NewMenuHandlers(fm, store, &accountService, mockReplaceSeparator) if err != nil { t.Fatalf("expected no error, got %v", err) } @@ -108,7 +108,7 @@ func TestNewMenuHandlers(t *testing.T) { // Test case for nil UserDataStore t.Run("Nil UserDataStore", func(t *testing.T) { - handlers, err := NewMenuHandlers(fm, nil, nil, &accountService, mockReplaceSeparator) + handlers, err := NewMenuHandlers(fm, nil, &accountService, mockReplaceSeparator) if err == nil { t.Fatal("expected an error, got none") } @@ -132,16 +132,9 @@ func TestInit(t *testing.T) { t.Fatal(err.Error()) } - adminstore, err := store.NewAdminStore(ctx, "admin_numbers") - if err != nil { - t.Fatal(err.Error()) - } - st := state.NewState(128) ca := cache.NewCache() - flag_admin_privilege, _ := fm.GetFlag("flag_admin_privilege") - tests := []struct { name string setup func() (*MenuHandlers, context.Context) @@ -162,15 +155,12 @@ func TestInit(t *testing.T) { pe := persist.NewPersister(testStore).WithSession(sessionId).WithContent(st, ca) h := &MenuHandlers{ flagManager: fm, - adminstore: adminstore, pe: pe, } return h, context.WithValue(ctx, "SessionId", sessionId) }, - input: []byte("1"), - expectedResult: resource.Result{ - FlagReset: []uint32{flag_admin_privilege}, - }, + input: []byte("1"), + expectedResult: resource.Result{}, }, { name: "Non-admin session initialization", @@ -178,15 +168,12 @@ func TestInit(t *testing.T) { pe := persist.NewPersister(testStore).WithSession("0712345678").WithContent(st, ca) h := &MenuHandlers{ flagManager: fm, - adminstore: adminstore, pe: pe, } return h, context.WithValue(context.Background(), "SessionId", "0712345678") }, - input: []byte("1"), - expectedResult: resource.Result{ - FlagReset: []uint32{flag_admin_privilege}, - }, + input: []byte("1"), + expectedResult: resource.Result{}, }, { name: "Move to top node on empty input", @@ -194,16 +181,13 @@ func TestInit(t *testing.T) { pe := persist.NewPersister(testStore).WithSession(sessionId).WithContent(st, ca) h := &MenuHandlers{ flagManager: fm, - adminstore: adminstore, pe: pe, } st.Code = []byte("some pending bytecode") return h, context.WithValue(ctx, "SessionId", sessionId) }, - input: []byte(""), - expectedResult: resource.Result{ - FlagReset: []uint32{flag_admin_privilege}, - }, + input: []byte(""), + expectedResult: resource.Result{}, }, } -- 2.45.2