/
user.go
97 lines (78 loc) · 2.14 KB
/
user.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package shares
import (
"encoding/json"
"errors"
"log"
"github.com/boltdb/bolt"
"golang.org/x/crypto/bcrypt"
)
// User represents a single user in the database
type User struct {
Name string
pwd []byte
UserProfile
// bolt is the boltdb associated with this user
bolt *bolt.DB
}
// ComparePassword compares pwd with the saved password
func (u User) ComparePassword(pwd string) bool {
// empty known password is always a rejection.
if len(u.pwd) == 0 || len(pwd) == 0 {
return false
}
err := bcrypt.CompareHashAndPassword(u.pwd, []byte(pwd))
return err == nil
}
// SetPassword sets a new password for user.
func (u *User) SetPassword(current, new string) bool {
// empty current password means we're setting our first password, this
// means we can skip the compare.
if len(u.pwd) != 0 && !u.ComparePassword(current) {
return false
}
bp, err := bcrypt.GenerateFromPassword([]byte(new), bcryptCost)
if err != nil {
log.Printf("critical: failed to generate bcrypt hash: %s", err)
return false
}
u.pwd = bp
return true
}
func (u User) Save() error {
if len(u.pwd) == 0 {
return errors.New("invalid password: empty")
}
if len(u.Name) == 0 {
return errors.New("invalid username: empty")
}
if u.bolt == nil {
return errors.New("invalid user instance: no database")
}
return u.bolt.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists(userBucket)
if err != nil {
// TODO: error clarification
return err
}
userdb, err := b.CreateBucketIfNotExists([]byte(u.Name))
if err != nil {
// TODO: error clarification
return err
}
// Store the users password
if err := userdb.Put(userPasswordKey, u.pwd); err != nil {
return errors.New("failed to store password: " + err.Error())
}
// Store the users profile
userProfile, err := json.Marshal(u.UserProfile)
if err != nil {
return errors.New("failed to marshal userprofile: " + err.Error())
}
if err := userdb.Put(userProfileBucket, userProfile); err != nil {
return errors.New("failed to store userprofile: " + err.Error())
}
return nil
})
}
// UserProfile contains non-critical information about a User
type UserProfile struct{}