From a5ad050d3e285333a0c525300ca4901aebcfee80 Mon Sep 17 00:00:00 2001 From: Denis Gukov Date: Wed, 1 Jan 2025 22:44:55 +0500 Subject: [PATCH] feat(auth): api for adding totp --- db/Store.go | 8 +++++++- db/bolt/user.go | 28 ++++++++++++++++++++++++++++ db/sql/user.go | 4 ++-- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/db/Store.go b/db/Store.go index 528b6f81..dba61f29 100644 --- a/db/Store.go +++ b/db/Store.go @@ -276,7 +276,7 @@ type Store interface { UpdateUser(user UserWithPwd) error SetUserPassword(userID int, password string) error AddUserTotpVerification(userID int, secret string) (UserTotp, error) - DeleteTotpVerification(userID int) error + DeleteTotpVerification(userID int, totpID int) error GetUser(userID int) (User, error) GetUserByLoginOrEmail(login string, email string) (User, error) @@ -534,6 +534,12 @@ var TemplateVaultProps = ObjectProps{ ReferringColumnSuffix: "template_id", } +var UserTotpProps = ObjectProps{ + TableName: "user__totp", + Type: reflect.TypeOf(UserTotp{}), + PrimaryColumnName: "id", +} + func (p ObjectProps) GetReferringFieldsFrom(t reflect.Type) (fields []string, err error) { n := t.NumField() for i := 0; i < n; i++ { diff --git a/db/bolt/user.go b/db/bolt/user.go index de130eb2..39d0ca7a 100644 --- a/db/bolt/user.go +++ b/db/bolt/user.go @@ -216,3 +216,31 @@ func (d *BoltDb) GetAllAdmins() (users []db.User, err error) { }, &users) return } + +func (d *BoltDb) AddUserTotpVerification(userID int, secret string) (totp db.UserTotp, err error) { + + current := make([]db.UserTotp, 0) + err = d.getObjects(userID, db.UserTotpProps, db.RetrieveQueryParams{}, nil, current) + + if len(current) > 0 { + err = fmt.Errorf("already exists") + return + } + + totp.UserID = userID + totp.Secret = secret + totp.Created = db.GetParsedTime(time.Now().UTC()) + + newTotp, err := d.createObject(userID, db.UserTotpProps, totp) + + if err != nil { + return + } + + totp = newTotp.(db.UserTotp) + return +} + +func (d *BoltDb) DeleteTotpVerification(userID int, totpID int) error { + return d.deleteObject(userID, db.UserTotpProps, intObjectID(totpID), nil) +} diff --git a/db/sql/user.go b/db/sql/user.go index 560076ce..d82c453c 100644 --- a/db/sql/user.go +++ b/db/sql/user.go @@ -287,7 +287,7 @@ func (d *SqlDb) AddUserTotpVerification(userID int, secret string) (totp db.User return } -func (d *SqlDb) DeleteTotpVerification(userID int) error { - _, err := d.exec("delete from user__totp where user_id=?", userID) +func (d *SqlDb) DeleteTotpVerification(userID int, totpID int) error { + _, err := d.exec("delete from user__totp where user_id=? and id = ?", userID, totpID) return err }