From 61265f790e3c32accb3ce844422bb6b23db7fe8a Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Sat, 16 Mar 2024 11:32:54 +0530 Subject: validator: init --- db/account.go | 33 ++++++++++++++++++++++++++------- db/main.go | 5 ++++- 2 files changed, 30 insertions(+), 8 deletions(-) (limited to 'db') diff --git a/db/account.go b/db/account.go index c7f76bf..507060e 100644 --- a/db/account.go +++ b/db/account.go @@ -1,18 +1,22 @@ package db -import "errors" +import ( + "errors" + "fmt" + "log" +) type Account struct { - UserName string - PassHash string `json:",omitempty"` + UserName string `validate:"required,alphanum,max=64"` + PassHash string `json:",omitempty" validate:"required,min=10,max=128"` Info *Login } type Login struct { id uint - Level uint - FirstName, LastName string + Level uint `validate:"gte=0,lte=100"` + FirstName, LastName string `validate:"required,alphanumunicode"` Bearer *Bearer } @@ -29,10 +33,18 @@ func (ac *Account) CreateAccount(safe *SafeDB) error { VALUES (NULL, ?, ?, ?, ?, ?); ` + err := safe.validate.Struct(ac) + if err == nil { + err = safe.validate.Struct(ac.Login) + } + if err != nil { + return err + } + safe.mu.Lock() defer safe.mu.Unlock() - _, err := safe.db.Exec( + _, err = safe.db.Exec( sqlStatement, ac.UserName, ToBlake3(ac.PassHash), @@ -52,6 +64,13 @@ func (ac *Account) Login(safe *SafeDB) error { WHERE Accounts.UserName = ? ` + err := safe.validate.Struct(ac) + fmt.Println(ac.PassHash, ac.UserName) + if err != nil { + log.Println(err) + return err + } + ac.Info = &Login{} ac.Info.Bearer = &Bearer{} safe.mu.Lock() @@ -59,7 +78,7 @@ func (ac *Account) Login(safe *SafeDB) error { safe.mu.Unlock() var PassHash string - err := row.Scan( + err = row.Scan( &ac.Info.id, &PassHash, &ac.Info.FirstName, diff --git a/db/main.go b/db/main.go index 801cb65..fcfbf11 100644 --- a/db/main.go +++ b/db/main.go @@ -6,11 +6,13 @@ import ( "path/filepath" "sync" + "github.com/go-playground/validator/v10" _ "github.com/mattn/go-sqlite3" ) type SafeDB struct { - mu sync.Mutex + mu sync.Mutex + validate *validator.Validate path string db *sql.DB @@ -70,5 +72,6 @@ func NewSafeDB() (*SafeDB, error) { return nil, err } + safe.validate = validator.New(validator.WithRequiredStructEnabled()) return safe, nil } -- cgit v1.2.3