aboutsummaryrefslogblamecommitdiff
path: root/db/user.go
blob: 24ce491e80ab9e4e3b7ee9135912aa4da1d9c853 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13












                                       




                                  

                          


                             






















































                                                                                                              









                                                       





                                                         
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)
}