]>
Commit | Line | Data |
---|---|---|
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 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 | ||
23 | func HashPassword(password string) (string, error) { | |
24 | b, err := bcrypt.GenerateFromPassword([]byte(password), 10) | |
25 | ||
26 | return string(b), err | |
27 | } | |
28 | ||
29 | func ValidatePassword(password string, hash string) error { | |
30 | return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) | |
31 | } | |
32 | ||
33 | func InsertUser(user *User) error { | |
34 | return DB.Insert(user) | |
35 | } | |
36 | ||
37 | func ConfirmUserByEmail(email string) error { | |
38 | _, err := DB.Model(&User{}).Set("status=?", Confirmed).Where("email=?", email).Returning("*").Update() | |
39 | ||
40 | return err | |
41 | } | |
42 | ||
43 | func GetUserById(id int64) (*User, error) { | |
44 | user := User{Id: id} | |
45 | ||
46 | err := DB.Select(&user) | |
47 | ||
48 | return &user, err | |
49 | } | |
50 | ||
51 | func 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 | ||
67 | func SetOtpSecret(user *User, secret string, temporary bool) error { | |
68 | user.OtpSecret = secret | |
69 | user.IsOtpSetup = !temporary | |
70 | ||
71 | return DB.Update(user) | |
72 | } |