aboutsummaryrefslogtreecommitdiff
path: root/db/user.go
blob: aed0ac173c92652338c213629abbe5d276fff663 (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
package db

import (
	"golang.org/x/crypto/bcrypt"
)

type UserStatus uint8

const (
	Confirmed UserStatus = iota + 1
	AwaitingConfirmation
)

type User struct {
	Id           int64
	Email        string `sql:",unique,notnull"`
	PasswordHash string `sql:",notnull"`
	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)
}