diff options
author | jloup <jean-loup.jamet@trainline.com> | 2018-02-14 14:19:09 +0100 |
---|---|---|
committer | jloup <jean-loup.jamet@trainline.com> | 2018-02-14 14:19:09 +0100 |
commit | 7a9e5112eaaea58d55f181d3e5296e4ff839921c (patch) | |
tree | 968ed193f42a1fad759cc89ad2f8ad5b0091291e /db/user.go | |
download | Front-7a9e5112eaaea58d55f181d3e5296e4ff839921c.tar.gz Front-7a9e5112eaaea58d55f181d3e5296e4ff839921c.tar.zst Front-7a9e5112eaaea58d55f181d3e5296e4ff839921c.zip |
initial commit
Diffstat (limited to 'db/user.go')
-rw-r--r-- | db/user.go | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/db/user.go b/db/user.go new file mode 100644 index 0000000..aed0ac1 --- /dev/null +++ b/db/user.go | |||
@@ -0,0 +1,72 @@ | |||
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 | } | ||