From 75a21eeb9f0204421165121a6b76f993dfa31630 Mon Sep 17 00:00:00 2001 From: Jason Streifling Date: Thu, 22 Feb 2024 18:49:51 +0100 Subject: [PATCH] Added ability to add user --- cmd/data/db.go | 26 ++++++++++++++++++++++++++ cmd/data/helpers.go | 6 ++++++ go.mod | 1 + go.sum | 2 ++ 4 files changed, 35 insertions(+) diff --git a/cmd/data/db.go b/cmd/data/db.go index 8589250..d969aeb 100644 --- a/cmd/data/db.go +++ b/cmd/data/db.go @@ -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 +} diff --git a/cmd/data/helpers.go b/cmd/data/helpers.go index bc4b3f9..efbba7c 100644 --- a/cmd/data/helpers.go +++ b/cmd/data/helpers.go @@ -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 +} diff --git a/go.mod b/go.mod index de87f21..9e7649a 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/gorilla/feeds v1.1.2 github.com/microcosm-cc/bluemonday v1.0.26 github.com/yuin/goldmark v1.7.0 + golang.org/x/crypto v0.14.0 golang.org/x/term v0.17.0 ) diff --git a/go.sum b/go.sum index cef3c78..234adb6 100644 --- a/go.sum +++ b/go.sum @@ -16,6 +16,8 @@ github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZV github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/yuin/goldmark v1.7.0 h1:EfOIvIMZIzHdB/R/zVrikYLPPwJlfMcNczJFMs1m6sA= github.com/yuin/goldmark v1.7.0/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=