This repository has been archived on 2024-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
feedpanel/db/db.go

51 lines
1.2 KiB
Go
Raw Normal View History

package paneldb
2018-09-26 15:59:50 +02:00
import (
"fmt"
"github.com/go-pg/pg"
"github.com/pkg/errors"
2018-09-27 23:11:07 +02:00
"golang.org/x/crypto/bcrypt"
2018-09-26 15:59:50 +02:00
)
type DB struct {
PgDB *pg.DB
Schema string
}
2018-09-26 16:53:06 +02:00
func (db *DB) Setup() error {
2018-09-26 15:59:50 +02:00
_, err := db.PgDB.Exec(`CREATE SCHEMA IF NOT EXISTS users`)
if err != nil {
return errors.Wrap(err, "Error creating schema")
}
2018-09-26 16:53:06 +02:00
fmt.Println("schema created")
2018-09-26 15:59:50 +02:00
_, 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,
password varchar(256) NOT NULL
)`)
if err != nil {
return errors.Wrap(err, "Error creating users table")
}
2018-09-26 16:53:06 +02:00
fmt.Println("table created")
2018-09-26 15:59:50 +02:00
return nil
}
2018-09-27 23:11:07 +02:00
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)")
2018-09-26 15:59:50 +02:00
if err != nil {
return errors.Wrap(err, "Error preparing insert statement")
2018-09-26 15:59:50 +02:00
}
2018-09-27 23:11:07 +02:00
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))
2018-09-26 15:59:50 +02:00
if err != nil {
return errors.Wrapf(err, "Error adding user `%s`", username)
2018-09-26 15:59:50 +02:00
}
return nil
}