From 96fe38726c388bc5fd254f8ccf852eb141e4eb71 Mon Sep 17 00:00:00 2001 From: Jason Streifling Date: Thu, 22 Feb 2024 19:27:41 +0100 Subject: [PATCH] Added ability to update Passwords --- cmd/data/db.go | 38 +++++++++++++++++++++++++++++++++++++- main.go | 1 + 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/cmd/data/db.go b/cmd/data/db.go index d969aeb..b6106df 100644 --- a/cmd/data/db.go +++ b/cmd/data/db.go @@ -41,7 +41,7 @@ func (db *DB) AddUser(user, pass, first, last string, writer, editor, admin bool } if !permissionsOK(writer, editor, admin) { - return fmt.Errorf("error with mutually exclusive user permissions: writer = %v, editor = %v, admin = %v", + return fmt.Errorf("error with mutually exclusive permissions: writer = %v, editor = %v, admin = %v", writer, editor, admin) } @@ -58,3 +58,39 @@ func (db *DB) AddUser(user, pass, first, last string, writer, editor, admin bool return nil } + +func (db *DB) ChangePassword(id int64, oldPass, newPass string) error { + var oldHashedPass string + + selectQuery := ` + SELECT password FROM + users + WHERE + id = ? + ` + row := db.QueryRow(selectQuery, id) + if err := row.Scan(&oldHashedPass); err != nil { + return fmt.Errorf("error reading password from DB: %v", err) + } + + if err := bcrypt.CompareHashAndPassword([]byte(oldHashedPass), []byte(oldPass)); err != nil { + return fmt.Errorf("error checking password: %v", err) + } + + newHashedPass, err := bcrypt.GenerateFromPassword([]byte(newPass), bcrypt.DefaultCost) + if err != nil { + return fmt.Errorf("error creating password hash: %v", err) + } + + updateQuery := ` + UPDATE users + SET password = ? + WHERE id = ? + ` + _, err = db.Exec(updateQuery, newHashedPass, id) + if err != nil { + return fmt.Errorf("error updating password in DB: %v", err) + } + + return nil +} diff --git a/main.go b/main.go index ccc938f..23d9187 100644 --- a/main.go +++ b/main.go @@ -15,6 +15,7 @@ func main() { if err != nil { log.Fatalln(err) } + defer db.Close() f, err := feed.OpenFeed("tmp/rss.gob") if err != nil {