-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmodel_users.go
82 lines (69 loc) · 1.95 KB
/
model_users.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import "golang.org/x/crypto/bcrypt"
// These are all model functions that have to do with users
// Unlike gamejam functions, we manipulate the DB directly
// We want to make sure that we always use the most up-to-date user
// information.
// Returns true if there are any users in the database
func (m *model) hasUser() bool {
return len(m.getAllUsers()) > 0
}
func (m *model) getAllUsers() []string {
if err := m.openDB(); err != nil {
return []string{}
}
defer m.closeDB()
usrs, err := m.bolt.GetBucketList([]string{"users"})
if err != nil {
return []string{}
}
return usrs
}
// Is the given email one that is in our DB?
func (m *model) isValidUserEmail(email string) bool {
if err := m.openDB(); err != nil {
return false
}
defer m.closeDB()
usrPath := []string{"users", email}
_, err := m.bolt.GetValue(usrPath, "password")
return err == nil
}
// Is the email and pw given valid?
func (m *model) checkCredentials(email, pw string) error {
var err error
if err = m.openDB(); err != nil {
return err
}
defer m.closeDB()
var uPw string
usrPath := []string{"users", email}
if uPw, err = m.bolt.GetValue(usrPath, "password"); err != nil {
return err
}
return bcrypt.CompareHashAndPassword([]byte(uPw), []byte(pw))
}
// updateUserPassword
// Takes an email address and a password
// Creates the user if it doesn't exist, encrypts the password
// and updates it in the db
func (m *model) updateUserPassword(email, password string) error {
cryptPw, cryptError := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if cryptError != nil {
return cryptError
}
if err := m.openDB(); err != nil {
return err
}
defer m.closeDB()
usrPath := []string{"users", email}
return m.bolt.SetValue(usrPath, "password", string(cryptPw))
}
func (m *model) deleteUser(email string) error {
var err error
if err = m.openDB(); err != nil {
return err
}
defer m.closeDB()
return m.bolt.DeleteBucket([]string{"users"}, email)
}