]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/Cryptoportfolio/Front.git/blame - db/user.go
User roles.
[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
cf5bb85c 14type UserRole string
15
16const RoleUser UserRole = "user"
17const RoleAdmin UserRole = "admin"
18
7a9e5112 19type User struct {
20 Id int64
cf5bb85c 21 Role UserRole
22 Email string
23 PasswordHash string
7a9e5112 24 OtpSecret string
25 IsOtpSetup bool
26 Status UserStatus
27}
28
29func HashPassword(password string) (string, error) {
30 b, err := bcrypt.GenerateFromPassword([]byte(password), 10)
31
32 return string(b), err
33}
34
35func ValidatePassword(password string, hash string) error {
36 return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
37}
38
39func InsertUser(user *User) error {
40 return DB.Insert(user)
41}
42
43func ConfirmUserByEmail(email string) error {
44 _, err := DB.Model(&User{}).Set("status=?", Confirmed).Where("email=?", email).Returning("*").Update()
45
46 return err
47}
48
49func GetUserById(id int64) (*User, error) {
50 user := User{Id: id}
51
52 err := DB.Select(&user)
53
54 return &user, err
55}
56
57func 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
73func SetOtpSecret(user *User, secret string, temporary bool) error {
74 user.OtpSecret = secret
75 user.IsOtpSetup = !temporary
76
77 return DB.Update(user)
78}
85545aba 79
80func 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}
2da5b12c 89
90func SetUserStatus(user *User, status UserStatus) error {
91 user.Status = status
92
93 return DB.Update(user)
94}