Added ability to add user

This commit is contained in:
2024-02-22 18:49:51 +01:00
parent 6020b24e44
commit 75a21eeb9f
4 changed files with 35 additions and 0 deletions

View File

@ -5,6 +5,7 @@ import (
"fmt"
"github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
type DB struct {
@ -32,3 +33,28 @@ func OpenDB(dbName string) (*DB, error) {
return &db, nil
}
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)
}
if !permissionsOK(writer, editor, admin) {
return fmt.Errorf("error with mutually exclusive user permissions: writer = %v, editor = %v, admin = %v",
writer, editor, admin)
}
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)
if err != nil {
return fmt.Errorf("error inserting user into DB: %v", err)
}
return nil
}

View File

@ -50,3 +50,9 @@ func getCredentials() (string, string, error) {
return user, pass, nil
}
func permissionsOK(writer, editor, admin bool) bool {
return writer && !editor && !admin ||
!writer && editor && !admin ||
!writer && !editor && admin
}