aboutsummaryrefslogtreecommitdiff
path: root/db/user.go
blob: 24ce491e80ab9e4e3b7ee9135912aa4da1d9c853 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
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)
}