From 068bf045a796569e1f568037a0deb84d4411ac89 Mon Sep 17 00:00:00 2001 From: Jason Streifling Date: Thu, 22 Feb 2024 20:12:09 +0100 Subject: [PATCH] Check user credentials before adding user --- cmd/data/db.go | 17 +++++++++++------ cmd/data/helpers.go | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/cmd/data/db.go b/cmd/data/db.go index b6106df..4ac8921 100644 --- a/cmd/data/db.go +++ b/cmd/data/db.go @@ -35,23 +35,28 @@ func OpenDB(dbName string) (*DB, error) { } func (db *DB) AddUser(user, pass, first, last string, writer, editor, admin bool) error { - hashedPass, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost) - if err != nil { - return fmt.Errorf("error creating password hash: %v", err) + userString, stringLen, ok := checkUserStrings(user, first, last) + if !ok { + return fmt.Errorf("error: %v is longer than %v characters", userString, stringLen) } if !permissionsOK(writer, editor, admin) { - return fmt.Errorf("error with mutually exclusive permissions: writer = %v, editor = %v, admin = %v", + return fmt.Errorf("error: permissions must be mutually exclusive: writer = %v, editor = %v, admin = %v", writer, editor, admin) } + hashedPass, err := bcrypt.GenerateFromPassword([]byte(pass), bcrypt.DefaultCost) + if err != nil { + return fmt.Errorf("error creating password hash: %v", err) + } + query := ` INSERT INTO users (username, password, first_name, last_name, writer, editor, admin) VALUES (?, ?, ?, ?, ?, ?) ` - _, err = db.Exec(query, user, hashedPass, first, last, writer, editor, admin) + _, err = db.Exec(query, user, string(hashedPass), first, last, writer, editor, admin) if err != nil { return fmt.Errorf("error inserting user into DB: %v", err) } @@ -87,7 +92,7 @@ func (db *DB) ChangePassword(id int64, oldPass, newPass string) error { SET password = ? WHERE id = ? ` - _, err = db.Exec(updateQuery, newHashedPass, id) + _, err = db.Exec(updateQuery, string(newHashedPass), id) if err != nil { return fmt.Errorf("error updating password in DB: %v", err) } diff --git a/cmd/data/helpers.go b/cmd/data/helpers.go index efbba7c..39e8572 100644 --- a/cmd/data/helpers.go +++ b/cmd/data/helpers.go @@ -51,6 +51,21 @@ func getCredentials() (string, string, error) { return user, pass, nil } +func checkUserStrings(user, first, last string) (string, int, bool) { + userLen := 15 + nameLen := 50 + + if len(user) > userLen { + return user, userLen, false + } else if len(first) > nameLen { + return first, nameLen, false + } else if len(last) > nameLen { + return last, nameLen, false + } else { + return "", 0, true + } +} + func permissionsOK(writer, editor, admin bool) bool { return writer && !editor && !admin || !writer && editor && !admin ||