From b1cfd16627330f3f8af90b0b7a9e6bc8c682ef32 Mon Sep 17 00:00:00 2001 From: Evan Reichard Date: Sun, 28 Jan 2024 11:38:44 -0500 Subject: [PATCH] feat(restore): rotate auth hash on restore --- api/app-routes.go | 5 +++++ api/auth.go | 53 +++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/api/app-routes.go b/api/app-routes.go index 8cbf97b..e60b480 100644 --- a/api/app-routes.go +++ b/api/app-routes.go @@ -1457,6 +1457,11 @@ func (api *API) processRestoreFile(rAdminAction requestAdminAction, c *gin.Conte if err := api.db.Reload(); err != nil { log.Panicf("Unable to reload DB: %v", err) } + + // Rotate Auth Hashes + if err := api.rotateAllAuthHashes(); err != nil { + log.Panicf("Unable to rotate auth hashes: %v", err) + } } func (api *API) restoreData(zipReader *zip.Reader) error { diff --git a/api/auth.go b/api/auth.go index 93c5113..ddeb502 100644 --- a/api/auth.go +++ b/api/auth.go @@ -340,13 +340,62 @@ func (api *API) rotateUserAuthHash(username string) error { } // Update User - _, err = api.db.Queries.UpdateUser(api.db.Ctx, database.UpdateUserParams{ + if _, err = api.db.Queries.UpdateUser(api.db.Ctx, database.UpdateUserParams{ UserID: username, AuthHash: fmt.Sprintf("%x", rawAuthHash), - }) + }); err != nil { + log.Error("UpdateUser DB Error: ", err) + return err + } // Update Cache api.userAuthCache[username] = fmt.Sprintf("%x", rawAuthHash) return nil } + +func (api *API) rotateAllAuthHashes() error { + // Do Transaction + tx, err := api.db.DB.Begin() + if err != nil { + log.Error("Transaction Begin DB Error: ", err) + return err + } + + // Defer & Start Transaction + defer tx.Rollback() + qtx := api.db.Queries.WithTx(tx) + + users, err := qtx.GetUsers(api.db.Ctx) + if err != nil { + return err + } + + // Update users + for _, user := range users { + // Generate Auth Hash + rawAuthHash, err := utils.GenerateToken(64) + if err != nil { + return err + } + + // Update User + if _, err = qtx.UpdateUser(api.db.Ctx, database.UpdateUserParams{ + UserID: user.ID, + AuthHash: fmt.Sprintf("%x", rawAuthHash), + }); err != nil { + return err + } + + // Update Cache + api.userAuthCache[user.ID] = fmt.Sprintf("%x", rawAuthHash) + } + + // Commit Transaction + if err := tx.Commit(); err != nil { + log.Error("Transaction Commit DB Error: ", err) + return err + } + + return nil +}