Added ability to add user
This commit is contained in:
@ -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
|
||||
}
|
||||
|
@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user