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