]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blame - db/user.go
initial commit
[perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git] / db / user.go
CommitLineData
7a9e5112 1package db
2
3import (
4 "golang.org/x/crypto/bcrypt"
5)
6
7type UserStatus uint8
8
9const (
10 Confirmed UserStatus = iota + 1
11 AwaitingConfirmation
12)
13
14type User struct {
15 Id int64
16 Email string `sql:",unique,notnull"`
17 PasswordHash string `sql:",notnull"`
18 OtpSecret string
19 IsOtpSetup bool
20 Status UserStatus
21}
22
23func HashPassword(password string) (string, error) {
24 b, err := bcrypt.GenerateFromPassword([]byte(password), 10)
25
26 return string(b), err
27}
28
29func ValidatePassword(password string, hash string) error {
30 return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
31}
32
33func InsertUser(user *User) error {
34 return DB.Insert(user)
35}
36
37func ConfirmUserByEmail(email string) error {
38 _, err := DB.Model(&User{}).Set("status=?", Confirmed).Where("email=?", email).Returning("*").Update()
39
40 return err
41}
42
43func GetUserById(id int64) (*User, error) {
44 user := User{Id: id}
45
46 err := DB.Select(&user)
47
48 return &user, err
49}
50
51func GetUserByEmail(email string) (*User, error) {
52 var users []User
53
54 err := DB.Model(&users).Where("email = ?", email).Select()
55
56 if err != nil {
57 return nil, err
58 }
59
60 if len(users) == 0 {
61 return nil, nil
62 }
63
64 return &users[0], nil
65}
66
67func SetOtpSecret(user *User, secret string, temporary bool) error {
68 user.OtpSecret = secret
69 user.IsOtpSetup = !temporary
70
71 return DB.Update(user)
72}