package paneldb import ( "fmt" "github.com/go-pg/pg" "github.com/pkg/errors" "golang.org/x/crypto/bcrypt" ) type User struct { ID string `sql:"uid"` UserName string `sql:"username"` Email string `sql:"email"` DateCreated string `sql:"date_created"` PasswordHash string `sql:"password"` } type DB struct { PgDB *pg.DB Schema string } func (db *DB) Setup() error { _, err := db.PgDB.Exec(`CREATE SCHEMA IF NOT EXISTS users`) if err != nil { return errors.Wrap(err, "Error creating schema") } fmt.Println("schema created") _, err = db.PgDB.Exec(`CREATE TABLE IF NOT EXISTS users.users ( uid UUID PRIMARY KEY DEFAULT uuid_generate_v4(), username varchar(64) UNIQUE NOT NULL, email varchar(100) UNIQUE NOT NULL, date_created TIMESTAMPTZ NOT NULL DEFAULT NOW(), password varchar(256) NOT NULL )`) if err != nil { return errors.Wrap(err, "Error creating users table") } fmt.Println("table created") return nil } func (db *DB) UserAdd(username, email, pwd string) error { stmt, err := db.PgDB.Prepare("INSERT INTO users.users (username, email, password) VALUES ($1, $2, $3)") if err != nil { return errors.Wrap(err, "Error preparing insert statement") } pwhash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost) if err != nil { return errors.Wrap(err, "Error deriving password (with bcrypt)") } _, err = stmt.Exec(username, email, string(pwhash)) if err != nil { return errors.Wrapf(err, "Error adding user `%s`", username) } return nil } func (db *DB) GetUsers() ([]User, error) { var users []User _, err := db.PgDB.Query(&users, "SELECT * FROM users.users") if err != nil { return users, errors.Wrap(err, "User enumeration failed") } return users, err }