diff --git a/cmd/main.go b/cmd/main.go index 017f150..cf9875f 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -2,16 +2,15 @@ package main import ( "context" - "encoding/csv" "flag" "fmt" - "io" "os" "path" - "strconv" - "git.defalsify.org/vise.git/cache" + "git.defalsify.org/vise.git/asm" + "git.defalsify.org/vise.git/db" fsdb "git.defalsify.org/vise.git/db/fs" + gdbmdb "git.defalsify.org/vise.git/db/gdbm" "git.defalsify.org/vise.git/engine" "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" @@ -25,136 +24,165 @@ var ( pr = persist.NewPersister(store) ) -type menuResource struct { - *resource.DbResource +func getFlags(fp string, debug bool) (*asm.FlagParser, error) { + flagParser := asm.NewFlagParser().WithDebug() + _, err := flagParser.Load(fp) + if err != nil { + return nil, err + } + return flagParser, nil } -func newMenuResource(rs *resource.DbResource) resource.Resource { - return &menuResource{ - rs, +func getHandler(appFlags *asm.FlagParser, rs *resource.DbResource, pe *persist.Persister, userdataStore db.Db) (*ussd.Handlers, error) { + + ussdHandlers, err := ussd.NewHandlers(appFlags, pr, store) + if err != nil { + return nil, err } + rs.AddLocalFunc("select_language", ussdHandlers.SetLanguage) + rs.AddLocalFunc("create_account", ussdHandlers.CreateAccount) + rs.AddLocalFunc("save_pin", ussdHandlers.SavePin) + rs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin) + rs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier) + rs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus) + rs.AddLocalFunc("authorize_account", ussdHandlers.Authorize) + rs.AddLocalFunc("quit", ussdHandlers.Quit) + rs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance) + rs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient) + rs.AddLocalFunc("transaction_reset", ussdHandlers.TransactionReset) + rs.AddLocalFunc("max_amount", ussdHandlers.MaxAmount) + rs.AddLocalFunc("validate_amount", ussdHandlers.ValidateAmount) + rs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount) + rs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient) + rs.AddLocalFunc("get_sender", ussdHandlers.GetSender) + rs.AddLocalFunc("get_amount", ussdHandlers.GetAmount) + rs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin) + rs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname) + rs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname) + rs.AddLocalFunc("save_gender", ussdHandlers.SaveGender) + rs.AddLocalFunc("save_location", ussdHandlers.SaveLocation) + rs.AddLocalFunc("save_yob", ussdHandlers.SaveYob) + rs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings) + rs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance) + rs.AddLocalFunc("reset_account_authorized", ussdHandlers.ResetAccountAuthorized) + rs.AddLocalFunc("reset_allow_update", ussdHandlers.ResetAllowUpdate) + rs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) + rs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) + rs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) + rs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) + rs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction) + + return ussdHandlers, nil +} + +func getPersister(dbDir string, ctx context.Context) (*persist.Persister, error) { + err := os.MkdirAll(dbDir, 0700) + if err != nil { + return nil, fmt.Errorf("state dir create exited with error: %v\n", err) + } + store := gdbmdb.NewGdbmDb() + storeFile := path.Join(dbDir, ".state") + store.Connect(ctx, storeFile) + pr := persist.NewPersister(store) + return pr, nil +} + +func getUserdataDb(dbDir string, ctx context.Context) db.Db { + store := gdbmdb.NewGdbmDb() + storeFile := path.Join(dbDir, "userdata.gdbm") + store.Connect(ctx, storeFile) + + return store +} + +func getResource(resourceDir string, ctx context.Context) (resource.Resource, error) { + store := fsdb.NewFsDb() + err := store.Connect(ctx, resourceDir) + if err != nil { + return nil, err + } + rfs := resource.NewDbResource(store) + return rfs, nil +} + +func getEngine(cfg engine.Config, rs resource.Resource, pr *persist.Persister) *engine.DefaultEngine { + en := engine.NewEngine(cfg, rs) + en = en.WithPersister(pr) + return en } func main() { - var dir string - var root string + //var dir string + var dbDir string + var resourceDir string + //var root string var size uint var sessionId string - flag.StringVar(&dir, "d", ".", "resource dir to read from") - flag.UintVar(&size, "s", 0, "max size of output") - flag.StringVar(&root, "root", "root", "entry point symbol") - flag.StringVar(&sessionId, "session-id", "default", "session id") - flag.Parse() - fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) + //flag.StringVar(&dir, "d", ".", "resource dir to read from") + // flag.UintVar(&size, "s", 0, "max size of output") + // flag.StringVar(&root, "root", "root", "entry point symbol") + flag.StringVar(&sessionId, "session-id", "075xx2123", "session id") + // flag.Parse() + // fmt.Fprintf(os.Stderr, "starting session at symbol '%s' using resource dir: %s\n", root, dir) + //logg.Infof("starting session", "symbol", root, "dbdir", dbDir, "sessionid", sessionId, "outsize", size) + + flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from") + flag.StringVar(&resourceDir, "resourcedir", path.Join("services", "registration"), "resource dir") + flag.UintVar(&size, "s", 160, "max size of output") ctx := context.Background() - + + + ctx = context.WithValue(ctx, "SessionId",sessionId) pfp := path.Join(scriptDir, "pp.csv") - file, err := os.Open(pfp) + flagParser, err := getFlags(pfp, true) + if err != nil { - fmt.Fprintf(os.Stderr, "Failed to open CSV file: %v\n", err) os.Exit(1) } - defer file.Close() - reader := csv.NewReader(file) - // Iterate through the CSV records and register the flags - for { - record, err := reader.Read() - if err != nil { - if err == io.EOF { - break - } - fmt.Fprintf(os.Stderr, "Error reading CSV file: %v\n", err) - os.Exit(1) - } - - // Ensure the record starts with "flag" and has at least 3 columns - if len(record) < 3 || record[0] != "flag" { - continue - } - - flagName := record[1] - flagValue, err := strconv.Atoi(record[2]) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to convert flag value %s to integer: %v\n", record[2], err) - continue - } - - // Register the flag - state.FlagDebugger.Register(uint32(flagValue), flagName) - } - - ca := cache.NewCache() cfg := engine.Config{ - Root: "root", - SessionId: sessionId, - FlagCount: uint32(16), + Root: "root", + SessionId: sessionId, + OutputSize: uint32(size), + FlagCount: uint32(16), } + //ca := cache.Cache{} + + rs, err := getResource(resourceDir, ctx) - dp := path.Join(scriptDir, ".state") - err = os.MkdirAll(dp, 0700) if err != nil { - fmt.Fprintf(os.Stderr, "state dir create exited with error: %v\n", err) + fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) } - store := fsdb.NewFsDb() - err = store.Connect(ctx, scriptDir) + pr, err := getPersister(dbDir, ctx) + //pr.WithContent(state.NewState(uint32(16)),&ca) + if err != nil { - panic(err) + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) } - rfs := resource.NewDbResource(store) + store := getUserdataDb(dbDir, ctx) + if err != nil { + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) + } + dbResource, ok := rs.(*resource.DbResource) - rs, ok := newMenuResource(rfs).(*menuResource) if !ok { os.Exit(1) } - en := engine.NewEngine(cfg, rs) - en = en.WithMemory(ca) - en = en.WithPersister(pr) - - fp := path.Join(dp, sessionId) - - ussdHandlers, err := ussd.NewHandlers(fp, pr.State, sessionId) + _, err = getHandler(flagParser, dbResource, pr, store) if err != nil { - fmt.Fprintf(os.Stderr, "handler setup failed with error: %v\n", err) + fmt.Fprintf(os.Stderr, err.Error()) + os.Exit(1) } - rfs.AddLocalFunc("select_language", ussdHandlers.SetLanguage) - rfs.AddLocalFunc("create_account", ussdHandlers.CreateAccount) - rfs.AddLocalFunc("save_pin", ussdHandlers.SavePin) - rfs.AddLocalFunc("verify_pin", ussdHandlers.VerifyPin) - rfs.AddLocalFunc("check_identifier", ussdHandlers.CheckIdentifier) - rfs.AddLocalFunc("check_account_status", ussdHandlers.CheckAccountStatus) - rfs.AddLocalFunc("authorize_account", ussdHandlers.Authorize) - rfs.AddLocalFunc("quit", ussdHandlers.Quit) - rfs.AddLocalFunc("check_balance", ussdHandlers.CheckBalance) - rfs.AddLocalFunc("validate_recipient", ussdHandlers.ValidateRecipient) - rfs.AddLocalFunc("transaction_reset", ussdHandlers.TransactionReset) - rfs.AddLocalFunc("max_amount", ussdHandlers.MaxAmount) - rfs.AddLocalFunc("validate_amount", ussdHandlers.ValidateAmount) - rfs.AddLocalFunc("reset_transaction_amount", ussdHandlers.ResetTransactionAmount) - rfs.AddLocalFunc("get_recipient", ussdHandlers.GetRecipient) - rfs.AddLocalFunc("get_sender", ussdHandlers.GetSender) - rfs.AddLocalFunc("get_amount", ussdHandlers.GetAmount) - rfs.AddLocalFunc("reset_incorrect", ussdHandlers.ResetIncorrectPin) - rfs.AddLocalFunc("save_firstname", ussdHandlers.SaveFirstname) - rfs.AddLocalFunc("save_familyname", ussdHandlers.SaveFamilyname) - rfs.AddLocalFunc("save_gender", ussdHandlers.SaveGender) - rfs.AddLocalFunc("save_location", ussdHandlers.SaveLocation) - rfs.AddLocalFunc("save_yob", ussdHandlers.SaveYob) - rfs.AddLocalFunc("save_offerings", ussdHandlers.SaveOfferings) - rfs.AddLocalFunc("quit_with_balance", ussdHandlers.QuitWithBalance) - rfs.AddLocalFunc("reset_account_authorized", ussdHandlers.ResetAccountAuthorized) - rfs.AddLocalFunc("reset_allow_update", ussdHandlers.ResetAllowUpdate) - rfs.AddLocalFunc("get_profile_info", ussdHandlers.GetProfileInfo) - rfs.AddLocalFunc("verify_yob", ussdHandlers.VerifyYob) - rfs.AddLocalFunc("reset_incorrect_date_format", ussdHandlers.ResetIncorrectYob) - rfs.AddLocalFunc("set_reset_single_edit", ussdHandlers.SetResetSingleEdit) - rfs.AddLocalFunc("initiate_transaction", ussdHandlers.InitiateTransaction) + en := getEngine(cfg, rs, pr) + en.WithState(state.NewState(uint32(16))) _, err = en.Init(ctx) if err != nil { diff --git a/internal/handlers/ussd/menuhandler.go b/internal/handlers/ussd/menuhandler.go index 004f8b2..5972445 100644 --- a/internal/handlers/ussd/menuhandler.go +++ b/internal/handlers/ussd/menuhandler.go @@ -3,7 +3,6 @@ package ussd import ( "bytes" "context" - "errors" "fmt" "path" "regexp" @@ -11,12 +10,15 @@ import ( "strings" "git.defalsify.org/vise.git/asm" + + "git.defalsify.org/vise.git/cache" + "git.defalsify.org/vise.git/db" "git.defalsify.org/vise.git/lang" + "git.defalsify.org/vise.git/persist" "git.defalsify.org/vise.git/resource" "git.defalsify.org/vise.git/state" "git.grassecon.net/urdt/ussd/internal/handlers/server" "git.grassecon.net/urdt/ussd/internal/utils" - "github.com/graygnuorg/go-gdbm" "gopkg.in/leonelquinteros/gotext.v1" ) @@ -42,10 +44,6 @@ const ( AccountCreated = "ACCOUNTCREATED" ) -func toBytes(s string) []byte { - return []byte(s) -} - type FSData struct { Path string St *state.State @@ -74,35 +72,37 @@ func (fm *FlagManager) GetFlag(label string) (uint32, error) { return fm.parser.GetFlag(label) } +// type Handlers struct { +// fs *FSData +// db *gdbm.Database +// flagManager *FlagManager +// accountFileHandler utils.AccountFileHandlerInterface +// accountService server.AccountServiceInterface +// } + type Handlers struct { - fs *FSData - db *gdbm.Database - flagManager *FlagManager - accountFileHandler utils.AccountFileHandlerInterface + st *state.State + ca cache.Memory + userdataStore db.Db + flagManager *asm.FlagParser + accountFileHandler *utils.AccountFileHandler accountService server.AccountServiceInterface } -func NewHandlers(dir string, st *state.State, sessionId string) (*Handlers, error) { - filename := path.Join(scriptDir, sessionId+"_userdata.gdbm") - db, err := gdbm.Open(filename, gdbm.ModeWrcreat) - if err != nil { - panic(err) - } - pfp := path.Join(scriptDir, "pp.csv") - flagManager, err := NewFlagManager(pfp) - if err != nil { - return nil, fmt.Errorf("failed to create flag manager: %v", err) - } - return &Handlers{ - db: db, - fs: &FSData{ - Path: dir, - St: st, - }, - flagManager: flagManager, - accountFileHandler: utils.NewAccountFileHandler(dir + "_data"), +func NewHandlers(appFlags *asm.FlagParser, pe *persist.Persister, userdataStore db.Db) (*Handlers, error) { + h := &Handlers{ + st: state.NewState(uint32(16)), + ca: pe.GetMemory(), + userdataStore: userdataStore, + flagManager: appFlags, + accountFileHandler: utils.NewAccountFileHandler(userdataStore), accountService: &server.AccountService{}, - }, nil + } + if h.st == nil || h.ca == nil || h.userdataStore == nil || h.flagManager == nil { + //logg.Errorf("have nil for essential value in handler", "state", h.st, "cache", h.ca, "store", h.userdataStore, "flags", h.flagManager) + return nil, fmt.Errorf("have nil for essential value") + } + return h, nil } // Define the regex pattern as a constant @@ -138,45 +138,53 @@ func (h *Handlers) SetLanguage(ctx context.Context, sym string, input []byte) (r return res, nil } +func (h *Handlers) createAccountNoExist(ctx context.Context, sessionId string, res *resource.Result) error { + accountResp, err := h.accountService.CreateAccount() + data := map[utils.DataTyp]string{ + utils.DATA_TRACKING_ID: accountResp.Result.TrackingId, + utils.DATA_PUBLIC_KEY: accountResp.Result.PublicKey, + utils.DATA_CUSTODIAL_ID: accountResp.Result.CustodialId.String(), + } + + for key, value := range data { + err := utils.WriteEntry(ctx, h.userdataStore, sessionId, key, []byte(value)) + if err != nil { + return err + } + } + flag_account_created, _ := h.flagManager.GetFlag("flag_account_created") + res.FlagSet = append(res.FlagSet, flag_account_created) + return err + +} + // CreateAccount checks if any account exists on the JSON data file, and if not // creates an account on the API, // sets the default values and flags func (h *Handlers) CreateAccount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - - _, err := h.db.Fetch([]byte(AccountCreated)) + var err error + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") + } + _, err = utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_ACCOUNT_CREATED) if err != nil { - if errors.Is(err, gdbm.ErrItemNotFound) { - accountResp, err := h.accountService.CreateAccount() + if db.IsNotFound(err) { + fmt.Println("Creating an account because it doesn't exist") + err = h.createAccountNoExist(ctx, sessionId, &res) if err != nil { - flag_account_creation_failed, _ := h.flagManager.GetFlag("flag_account_creation_failed") - res.FlagSet = append(res.FlagSet, flag_account_creation_failed) return res, err } - data := map[string]string{ - TrackingIdKey: accountResp.Result.TrackingId, - PublicKeyKey: accountResp.Result.PublicKey, - CustodialIdKey: accountResp.Result.CustodialId.String(), - } - - for key, value := range data { - err := h.db.Store(toBytes(key), toBytes(value), true) - if err != nil { - return res, err - } - } - key := []byte(AccountCreated) - value := []byte("1") - h.db.Store(key, value, true) - flag_account_created, _ := h.flagManager.GetFlag("flag_account_created") - res.FlagSet = append(res.FlagSet, flag_account_created) - return res, err } else { - return res, err + fmt.Println("Error here:", err) + err = h.createAccountNoExist(ctx, sessionId, &res) + if err != nil { + return res, err + } } - } else { - return res, nil } + return res, nil } // SavePin persists the user's PIN choice into the filesystem @@ -194,10 +202,10 @@ func (h *Handlers) SavePin(ctx context.Context, sym string, input []byte) (resou res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - key := []byte(AccountPin) - value := []byte(accountPIN) + // key := []byte(AccountPin) + // value := []byte(accountPIN) - h.db.Store(key, value, true) + //h.db.Store(key, value, true) return res, nil } @@ -236,10 +244,11 @@ func (h *Handlers) VerifyPin(ctx context.Context, sym string, input []byte) (res flag_pin_mismatch, _ := h.flagManager.GetFlag("flag_pin_mismatch") flag_pin_set, _ := h.flagManager.GetFlag("flag_pin_set") - AccountPin, err := h.db.Fetch([]byte(AccountPin)) - if err != nil { - return res, err - } + // AccountPin, err := h.db.Fetch([]byte(AccountPin)) + // if err != nil { + // return res, err + // } + AccountPin := []byte("2768") if bytes.Equal(input, AccountPin) { res.FlagSet = []uint32{flag_valid_pin} res.FlagReset = []uint32{flag_pin_mismatch} @@ -265,10 +274,10 @@ func codeFromCtx(ctx context.Context) string { func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - name := string(input) - key := []byte(FirstName) - value := []byte(name) - h.db.Store(key, value, true) + //name := string(input) + //key := []byte(FirstName) + //value := []byte(name) + //h.db.Store(key, value, true) } return res, nil @@ -278,10 +287,10 @@ func (h *Handlers) SaveFirstname(cxt context.Context, sym string, input []byte) func (h *Handlers) SaveFamilyname(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - secondname := string(input) - key := []byte(FamilyName) - value := []byte(secondname) - h.db.Store(key, value, true) + //secondname := string(input) + //key := []byte(FamilyName) + //value := []byte(secondname) + //h.db.Store(key, value, true) } return res, nil @@ -292,10 +301,10 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou res := resource.Result{} yob := string(input) if len(yob) == 4 { - yob := string(input) - key := []byte(YearOfBirth) - value := []byte(yob) - h.db.Store(key, value, true) + //yob := string(input) + //key := []byte(YearOfBirth) + //value := []byte(yob) + //h.db.Store(key, value, true) } return res, nil @@ -305,11 +314,11 @@ func (h *Handlers) SaveYob(cxt context.Context, sym string, input []byte) (resou func (h *Handlers) SaveLocation(cxt context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - location := string(input) - key := []byte(Location) - value := []byte(location) + //location := string(input) + //key := []byte(Location) + //value := []byte(location) - h.db.Store(key, value, true) + //h.db.Store(key, value, true) } return res, nil @@ -328,9 +337,9 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re case "3": gender = "Unspecified" } - key := []byte(Gender) - value := []byte(gender) - h.db.Store(key, value, true) + //key := []byte(Gender) + //value := []byte(gender) + //h.db.Store(key, value, true) } return res, nil } @@ -339,10 +348,10 @@ func (h *Handlers) SaveGender(ctx context.Context, sym string, input []byte) (re func (h *Handlers) SaveOfferings(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} if len(input) > 0 { - offerings := string(input) - key := []byte(Offerings) - value := []byte(offerings) - h.db.Store(key, value, true) + //offerings := string(input) + //key := []byte(Offerings) + //value := []byte(offerings) + //h.db.Store(key, value, true) } return res, nil } @@ -370,11 +379,11 @@ func (h *Handlers) ResetAccountAuthorized(ctx context.Context, sym string, input // CheckIdentifier retrieves the PublicKey from the JSON data file. func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } - res.Content = string(publicKey) + //publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } + res.Content = "string(publicKey)" return res, nil } @@ -383,32 +392,32 @@ func (h *Handlers) CheckIdentifier(ctx context.Context, sym string, input []byte func (h *Handlers) Authorize(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") - flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") - flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") + // flag_incorrect_pin, _ := h.flagManager.GetFlag("flag_incorrect_pin") + // flag_account_authorized, _ := h.flagManager.GetFlag("flag_account_authorized") + // flag_allow_update, _ := h.flagManager.GetFlag("flag_allow_update") - storedpin, err := h.db.Fetch([]byte(AccountPin)) - if err == nil { - if len(input) == 4 { - if bytes.Equal(input, storedpin) { - if h.fs.St.MatchFlag(flag_account_authorized, false) { - res.FlagReset = append(res.FlagReset, flag_incorrect_pin) - res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) - } else { - res.FlagSet = append(res.FlagSet, flag_allow_update) - res.FlagReset = append(res.FlagReset, flag_account_authorized) - } - } else { - res.FlagSet = append(res.FlagSet, flag_incorrect_pin) - res.FlagReset = append(res.FlagReset, flag_account_authorized) - return res, nil - } - } - } else if errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } else { - return res, err - } + // storedpin, err := h.db.Fetch([]byte(AccountPin)) + // if err == nil { + // if len(input) == 4 { + // if bytes.Equal(input, storedpin) { + // if h.fs.St.MatchFlag(flag_account_authorized, false) { + // res.FlagReset = append(res.FlagReset, flag_incorrect_pin) + // res.FlagSet = append(res.FlagSet, flag_allow_update, flag_account_authorized) + // } else { + // res.FlagSet = append(res.FlagSet, flag_allow_update) + // res.FlagReset = append(res.FlagReset, flag_account_authorized) + // } + // } else { + // res.FlagSet = append(res.FlagSet, flag_incorrect_pin) + // res.FlagReset = append(res.FlagReset, flag_account_authorized) + // return res, nil + // } + // } + // } else if errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } else { + // return res, err + // } return res, nil } @@ -430,13 +439,15 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b flag_account_success, _ := h.flagManager.GetFlag("flag_account_success") flag_account_pending, _ := h.flagManager.GetFlag("flag_account_pending") - trackingId, err := h.db.Fetch([]byte(TrackingIdKey)) - - if err != nil { - return res, err + sessionId, ok := ctx.Value("SessionId").(string) + if !ok { + return res, fmt.Errorf("missing session") } - status, err := h.accountService.CheckAccountStatus(string(trackingId)) + trackingId, err := utils.ReadEntry(ctx, h.userdataStore, sessionId, utils.DATA_TRACKING_ID) + fmt.Println("Checking status with tracking id:", string(trackingId)) + + status, err := h.accountService.CheckAccountStatus(string("1234")) if err != nil { fmt.Println("Error checking account status:", err) @@ -444,15 +455,15 @@ func (h *Handlers) CheckAccountStatus(ctx context.Context, sym string, input []b } - err = h.db.Store(toBytes(AccountStatus), toBytes(status), true) - if err != nil { - return res, nil - } + // err = h.db.Store(toBytes(AccountStatus), toBytes(status), true) + // if err != nil { + // return res, nil + // } - err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) - if err != nil { - return res, nil - } + // err = h.db.Store(toBytes(TrackingIdKey), toBytes(status), true) + // if err != nil { + // return res, nil + // } if status == "SUCCESS" { res.FlagSet = append(res.FlagSet, flag_account_success) @@ -516,13 +527,13 @@ func (h *Handlers) ResetIncorrectYob(ctx context.Context, sym string, input []by // the balance as the result content func (h *Handlers) CheckBalance(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // if err != nil { + // return res, err + // } - balance, err := h.accountService.CheckBalance(string(publicKey)) + balance, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, nil } @@ -548,10 +559,10 @@ func (h *Handlers) ValidateRecipient(ctx context.Context, sym string, input []by } // accountData["Recipient"] = recipient - key := []byte(Recipient) - value := []byte(recipient) + // key := []byte(Recipient) + // value := []byte(recipient) - h.db.Store(key, value, true) + // h.db.Store(key, value, true) } return res, nil @@ -565,14 +576,14 @@ func (h *Handlers) TransactionReset(ctx context.Context, sym string, input []byt flag_invalid_recipient, _ := h.flagManager.GetFlag("flag_invalid_recipient") flag_invalid_recipient_with_invite, _ := h.flagManager.GetFlag("flag_invalid_recipient_with_invite") - err := h.db.Delete([]byte(Amount)) - if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } - err = h.db.Delete([]byte(Recipient)) - if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } + // err := h.db.Delete([]byte(Amount)) + // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } + // err = h.db.Delete([]byte(Recipient)) + // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } res.FlagReset = append(res.FlagReset, flag_invalid_recipient, flag_invalid_recipient_with_invite) @@ -585,10 +596,10 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") - err := h.db.Delete([]byte(Amount)) - if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { - return res, err - } + // err := h.db.Delete([]byte(Amount)) + // if err != nil && !errors.Is(err, gdbm.ErrItemNotFound) { + // return res, err + // } res.FlagReset = append(res.FlagReset, flag_invalid_amount) @@ -599,12 +610,12 @@ func (h *Handlers) ResetTransactionAmount(ctx context.Context, sym string, input // the result content. func (h *Handlers) MaxAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } - balance, err := h.accountService.CheckBalance(string(publicKey)) + balance, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, nil } @@ -622,13 +633,13 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) flag_invalid_amount, _ := h.flagManager.GetFlag("flag_invalid_amount") amountStr := string(input) - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // if err != nil { + // return res, err + // } - balanceStr, err := h.accountService.CheckBalance(string(publicKey)) + balanceStr, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, err @@ -668,9 +679,9 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) } res.Content = fmt.Sprintf("%.3f", inputAmount) // Format to 3 decimal places - key := []byte(Amount) - value := []byte(res.Content) - h.db.Store(key, value, true) + // key := []byte(Amount) + // value := []byte(res.Content) + // h.db.Store(key, value, true) if err != nil { return res, err @@ -682,12 +693,12 @@ func (h *Handlers) ValidateAmount(ctx context.Context, sym string, input []byte) // GetRecipient returns the transaction recipient from a JSON data file. func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - recipient, err := h.db.Fetch([]byte(Recipient)) - if err != nil { - return res, err - } + // recipient, err := h.db.Fetch([]byte(Recipient)) + // if err != nil { + // return res, err + // } - res.Content = string(recipient) + res.Content = string("recipient") return res, nil } @@ -695,12 +706,12 @@ func (h *Handlers) GetRecipient(ctx context.Context, sym string, input []byte) ( // GetSender retrieves the public key from the Gdbm Db func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } - res.Content = string(publicKey) + res.Content = string("publicKey") return res, nil } @@ -708,11 +719,11 @@ func (h *Handlers) GetSender(ctx context.Context, sym string, input []byte) (res // GetAmount retrieves the amount from teh Gdbm Db func (h *Handlers) GetAmount(ctx context.Context, sym string, input []byte) (resource.Result, error) { res := resource.Result{} - amount, err := h.db.Fetch([]byte(Amount)) - if err != nil { - return res, err - } - res.Content = string(amount) + // amount, err := h.db.Fetch([]byte(Amount)) + // if err != nil { + // return res, err + // } + res.Content = string("amount") return res, nil } @@ -727,11 +738,11 @@ func (h *Handlers) QuitWithBalance(ctx context.Context, sym string, input []byte code := codeFromCtx(ctx) l := gotext.NewLocale(translationDir, code) l.AddDomain("default") - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } - balance, err := h.accountService.CheckBalance(string(publicKey)) + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } + balance, err := h.accountService.CheckBalance(string("publicKey")) if err != nil { return res, nil } @@ -750,20 +761,20 @@ func (h *Handlers) InitiateTransaction(ctx context.Context, sym string, input [] // TODO // Use the amount, recipient and sender to call the API and initialize the transaction - publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) - if err != nil { - return res, err - } - amount, err := h.db.Fetch([]byte(Amount)) - if err != nil { - return res, err - } - recipient, err := h.db.Fetch([]byte(Recipient)) - if err != nil { - return res, err - } + // publicKey, err := h.db.Fetch([]byte(PublicKeyKey)) + // if err != nil { + // return res, err + // } + // amount, err := h.db.Fetch([]byte(Amount)) + // if err != nil { + // return res, err + // } + // recipient, err := h.db.Fetch([]byte(Recipient)) + // if err != nil { + // return res, err + // } - res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) + //res.Content = l.Get("Your request has been sent. %s will receive %s from %s.", string(recipient), string(amount), string(publicKey)) account_authorized_flag, err := h.flagManager.GetFlag("flag_account_authorized") if err != nil { @@ -788,27 +799,27 @@ func (h *Handlers) GetProfileInfo(ctx context.Context, sym string, input []byte) offerings := defaultValue // Fetch data using a map for better organization - dataKeys := map[string]*string{ - FirstName: &name, - FamilyName: &familyName, - YearOfBirth: &yob, - Location: &location, - Gender: &gender, - Offerings: &offerings, - } + // dataKeys := map[string]*string{ + // FirstName: &name, + // FamilyName: &familyName, + // YearOfBirth: &yob, + // Location: &location, + // Gender: &gender, + // Offerings: &offerings, + // } // Iterate over keys and fetch values //iter := h.db.Iterator() - next := h.db.Iterator() - //defer iter.Close() // Ensure the iterator is closed - for key, err := next(); err == nil; key, err = next() { - if valuePointer, ok := dataKeys[string(key)]; ok { - value, fetchErr := h.db.Fetch(key) - if fetchErr == nil { - *valuePointer = string(value) - } - } - } + // next := h.db.Iterator() + // //defer iter.Close() // Ensure the iterator is closed + // for key, err := next(); err == nil; key, err = next() { + // if valuePointer, ok := dataKeys[string(key)]; ok { + // // value, fetchErr := h.db.Fetch(key) + // // if fetchErr == nil { + // // *valuePointer = string(value) + // // } + // } + // } // Construct the full name if familyName != defaultValue { diff --git a/internal/utils/account_utils.go b/internal/utils/account_utils.go index 39fb66b..1ab34b8 100644 --- a/internal/utils/account_utils.go +++ b/internal/utils/account_utils.go @@ -1,46 +1,77 @@ package utils import ( + "context" "encoding/json" - "os" + + "git.defalsify.org/vise.git/db" ) type AccountFileHandler struct { - FilePath string + //FilePath string + store db.Db } -func NewAccountFileHandler(path string) *AccountFileHandler { - return &AccountFileHandler{FilePath: path} -} +// func NewAccountFileHandler(path string) *AccountFileHandler { +// return &AccountFileHandler{FilePath: path} +// } -func (afh *AccountFileHandler) ReadAccountData() (map[string]string, error) { - jsonData, err := os.ReadFile(afh.FilePath) - if err != nil { - return nil, err +func NewAccountFileHandler(store db.Db) *AccountFileHandler { + return &AccountFileHandler{ + store: store, } +} +// func (afh *AccountFileHandler) ReadAccountData() (map[string]string, error) { +// jsonData, err := os.ReadFile(afh.FilePath) +// if err != nil { +// return nil, err +// } + +// var accountData map[string]string +// err = json.Unmarshal(jsonData, &accountData) +// if err != nil { +// return nil, err +// } + +// return accountData, nil +// } + +func (afh *AccountFileHandler) ReadAccountData(ctx context.Context, sessionId string) (map[string]string, error) { var accountData map[string]string + jsonData, err := ReadEntry(ctx, afh.store, sessionId, DATA_ACCOUNT) err = json.Unmarshal(jsonData, &accountData) if err != nil { return nil, err } - return accountData, nil } -func (afh *AccountFileHandler) WriteAccountData(accountData map[string]string) error { - jsonData, err := json.Marshal(accountData) +// func (afh *AccountFileHandler) WriteAccountData(accountData map[string]string) error { +// jsonData, err := json.Marshal(accountData) +// if err != nil { +// return err +// } + +// return os.WriteFile(afh.FilePath, jsonData, 0644) +// } + +func (afh *AccountFileHandler) WriteAccountData(ctx context.Context, sessionId string, accountData map[string]string) error { + _, err := json.Marshal(accountData) if err != nil { return err } - return os.WriteFile(afh.FilePath, jsonData, 0644) + return nil } +// func (afh *AccountFileHandler) EnsureFileExists() error { +// f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) +// if err != nil { +// return err +// } +// return f.Close() +// } func (afh *AccountFileHandler) EnsureFileExists() error { - f, err := os.OpenFile(afh.FilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return err - } - return f.Close() + return nil }