2024-02-18 16:37:13 +01:00
|
|
|
package data
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/go-sql-driver/mysql"
|
2024-02-22 18:49:51 +01:00
|
|
|
"golang.org/x/crypto/bcrypt"
|
2024-02-18 16:37:13 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type DB struct {
|
|
|
|
*sql.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func OpenDB(dbName string) (*DB, error) {
|
|
|
|
var err error
|
|
|
|
db := DB{DB: &sql.DB{}}
|
|
|
|
|
|
|
|
cfg := mysql.NewConfig()
|
|
|
|
cfg.DBName = dbName
|
|
|
|
cfg.User, cfg.Passwd, err = getCredentials()
|
|
|
|
if err != nil {
|
2024-02-22 15:23:29 +01:00
|
|
|
return nil, fmt.Errorf("error reading user credentials for DB: %v", err)
|
2024-02-18 16:37:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
db.DB, err = sql.Open("mysql", cfg.FormatDSN())
|
|
|
|
if err != nil {
|
2024-02-22 15:23:29 +01:00
|
|
|
return nil, fmt.Errorf("error opening DB: %v", err)
|
2024-02-18 16:37:13 +01:00
|
|
|
}
|
|
|
|
if err = db.Ping(); err != nil {
|
2024-02-22 15:23:29 +01:00
|
|
|
return nil, fmt.Errorf("error pinging DB: %v", err)
|
2024-02-18 16:37:13 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return &db, nil
|
|
|
|
}
|
2024-02-22 18:49:51 +01:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|