/
user.go
141 lines (115 loc) · 4.19 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package mongodb
import (
"fmt"
"time"
"github.com/ukane-philemon/bob/db"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"golang.org/x/crypto/bcrypt"
)
// UsernameExists checks if a username exists in the database. Implements
// db.DataStore.
func (m *MongoDB) UsernameExists(username string) (bool, error) {
res := m.usersCollection().FindOne(m.ctx, bson.M{userMapKey(usernameKey): username})
if res.Err() != nil && res.Err() != mongo.ErrNoDocuments {
return false, res.Err()
}
return res.Err() == nil /* false if we got mongo.ErrNoDocuments error */, nil
}
// CreateUser adds a new user to the database. The username must be unique and
// email must be unique. The password is hashed before being stored. Implements
// db.DataStore.
func (m *MongoDB) CreateUser(username, email string, password []byte) error {
if username == "" || email == "" || password == nil {
return fmt.Errorf("%w: username, email, and password are required", db.ErrorBadRequest)
}
if !db.IsValidEmail(email) {
return fmt.Errorf("%w: invalid email", db.ErrorBadRequest)
}
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
return fmt.Errorf("error hashing password: %w", err)
}
userInfo := &completeUserInfo{
UserInfo: &db.UserInfo{
Username: username,
Email: email,
Timestamp: time.Now().Unix(),
},
Password: hashedPassword,
}
if _, err := m.usersCollection().InsertOne(m.ctx, userInfo); err != nil {
// Check if this is a duplicate error.
if mongo.IsDuplicateKeyError(err) {
return fmt.Errorf("%w: username or email already exists", db.ErrorBadRequest)
}
return fmt.Errorf("error creating user: %w", err)
}
return nil
}
// RetrieveUserInfo fetches information about a user using the email. Implements
// db.DataStore.
func (m *MongoDB) RetrieveUserInfo(email string) (*db.UserInfo, error) {
if !db.IsValidEmail(email) {
return nil, fmt.Errorf("%w: a valid email is required", db.ErrorBadRequest)
}
res := m.usersCollection().FindOne(m.ctx, bson.M{userMapKey(emailKey): email})
if res.Err() != nil {
return nil, handleUserError(res.Err())
}
var userInfo *completeUserInfo
if err := res.Decode(&userInfo); err != nil {
return nil, fmt.Errorf("error decoding user info: %w", err)
}
// Set user's total links
nLinks, err := m.urlsCollection().CountDocuments(m.ctx, bson.M{urlMapKey(ownerIDKey): email})
if err != nil {
return nil, handleURLError(err)
}
userInfo.TotalLinks = int(nLinks)
return userInfo.UserInfo, nil
}
// LoginUser logs a user in and returns a nil error if the user exists and the
// password is correct. Implements db.DataStore.
func (m *MongoDB) LoginUser(email string, password []byte) (*db.UserInfo, error) {
if !db.IsValidEmail(email) {
return nil, fmt.Errorf("%w: a valid email is required", db.ErrorBadRequest)
}
if len(password) == 0 {
return nil, fmt.Errorf("%w: password is required", db.ErrorBadRequest)
}
res := m.usersCollection().FindOne(m.ctx, bson.M{userMapKey(emailKey): email})
if res.Err() != nil {
return nil, handleUserError(res.Err())
}
var dbUserInfo *completeUserInfo
if err := res.Decode(&dbUserInfo); err != nil {
return nil, fmt.Errorf("error decoding user info: %w", err)
}
if bcrypt.CompareHashAndPassword(dbUserInfo.Password, password) != nil {
return nil, fmt.Errorf("%w: incorrect password", db.ErrorBadRequest)
}
// Set user's total links
nLinks, err := m.urlsCollection().CountDocuments(m.ctx, bson.M{urlMapKey(ownerIDKey): email})
if err != nil {
return nil, handleURLError(err)
}
dbUserInfo.TotalLinks = int(nLinks)
return dbUserInfo.UserInfo, nil
}
// usersCollection returns the users collection.
func (m *MongoDB) usersCollection() *mongo.Collection {
return m.db.Collection(usersCollectionName)
}
// handleUserError handles errors that occur when retrieving a user.
func handleUserError(err error) error {
if err == mongo.ErrNoDocuments {
return fmt.Errorf("%w: user does not exist", db.ErrorBadRequest)
}
return fmt.Errorf("error retrieving user: %w", err)
}
// userMapKey returns a key for the user map.
func userMapKey(key string) string {
// userKey is the key for the user in the database. See: userInfo.UserInfo.
return mapKey("user", key)
}