package db
import (
"golang.org/x/crypto/bcrypt"
)
type UserStatus uint8
const (
Confirmed UserStatus = iota + 1
AwaitingConfirmation
)
type UserRole string
const RoleUser UserRole = "user"
const RoleAdmin UserRole = "admin"
type User struct {
Id int64
Role UserRole
Email string
PasswordHash string
OtpSecret string
IsOtpSetup bool
Status UserStatus
}
func HashPassword(password string) (string, error) {
b, err := bcrypt.GenerateFromPassword([]byte(password), 10)
return string(b), err
}
func ValidatePassword(password string, hash string) error {
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
}
func InsertUser(user *User) error {
return DB.Insert(user)
}
func ConfirmUserByEmail(email string) error {
_, err := DB.Model(&User{}).Set("status=?", Confirmed).Where("email=?", email).Returning("*").Update()
return err
}
func GetUserById(id int64) (*User, error) {
user := User{Id: id}
err := DB.Select(&user)
return &user, err
}
func GetUserByEmail(email string) (*User, error) {
var users []User
err := DB.Model(&users).Where("email = ?", email).Select()
if err != nil {
return nil, err
}
if len(users) == 0 {
return nil, nil
}
return &users[0], nil
}
func SetOtpSecret(user *User, secret string, temporary bool) error {
user.OtpSecret = secret
user.IsOtpSetup = !temporary
return DB.Update(user)
}
func SetPassword(user *User, password string) error {
var err error
user.PasswordHash, err = HashPassword(password)
if err != nil {
return err
}
return DB.Update(user)
}
func SetUserStatus(user *User, status UserStatus) error {
user.Status = status
return DB.Update(user)
}