cabinet/auth/auth.go

70 lines
1.2 KiB
Go
Raw Normal View History

2019-11-11 00:26:36 +00:00
package auth
import (
"code.chrissexton.org/cws/cabinet/db"
"github.com/jmoiron/sqlx"
"golang.org/x/crypto/bcrypt"
)
type User struct {
*db.Database
ID int64
Name string
Hash []byte
}
func PrepareTable(tx *sqlx.Tx) error {
q := `create table if not exists users (
id integer primary key,
name text unique,
hash text
)`
_, err := tx.Exec(q)
return err
}
func New(db *db.Database, name, password string) (*User, error) {
q := `insert into users (null, ?, ?)`
res, err := db.Exec(q, name, password)
if err != nil {
return nil, err
}
id, err := res.LastInsertId()
if err != nil {
return nil, err
}
u := &User{
ID: id,
Name: name,
}
u.Set(password)
return u, nil
}
func Get(db *db.Database, name string) (*User, error) {
q := `select * from users where name = ?`
u := &User{}
if err := db.Get(u, q, name); err != nil {
return nil, err
}
return u, nil
}
func (u *User) Set(newPassword string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(newPassword), 0)
if err != nil {
return err
}
u.Hash = hash
return nil
}
func (u *User) Validate(password string) bool {
err := bcrypt.CompareHashAndPassword(u.Hash, []byte(password))
if err != nil {
return false
}
return true
}