Check user credentials before adding user

This commit is contained in:
Jason Streifling 2024-02-22 20:12:09 +01:00
parent 8d47146a7c
commit 7d6f96a185
2 changed files with 26 additions and 6 deletions

View File

@ -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)
}

View File

@ -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 ||