This repository has been archived by the owner on Sep 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 41
/
User.js
215 lines (187 loc) · 6.42 KB
/
User.js
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
const { ds, namespace } = require('./Datastore.js');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
/* istanbul ignore next */
const tokenSecret = process.env.SECRET ? process.env.SECRET : '3ee058420bc2';
module.exports = {
async create(aUserData) {
// Verify username is not taken
const userKey = ds.key({ namespace, path: ['User', aUserData.username], });
const result = await ds.get(userKey);
if (result[0]) {
throw new Error(`Username already taken: [${aUserData.username}]`);
}
await verifyEmailIsNotTaken(aUserData.email);
// Add user
const encryptedPassword = await bcrypt.hash(aUserData.password, 5);
const userRecord = {
username: aUserData.username,
email: aUserData.email,
password: encryptedPassword,
bio: '',
image: '',
followers: [],
following: [],
};
await ds.upsert({ key: userKey, data: userRecord });
delete userRecord.password;
userRecord.token = this.mintToken(aUserData.username);
userRecord.username = aUserData.username;
return userRecord;
},
async update(aCurrentUser, aUserMutation) {
const userKey = ds.key({ namespace, path: ['User', aCurrentUser.username] });
const user = (await ds.get(userKey))[0];
if (!user) {
throw new Error(`User not found: [${aCurrentUser.username}]`);
}
// Make requested mutations
if (aUserMutation.email) {
await verifyEmailIsNotTaken(aUserMutation.email);
user.email = aUserMutation.email;
}
if (aUserMutation.password) {
user.password = await bcrypt.hash(aUserMutation.password, 5);
}
if (aUserMutation.image) {
user.image = aUserMutation.image;
}
if (aUserMutation.bio) {
user.bio = aUserMutation.bio;
}
await ds.update(user);
const updatedUser = (await ds.get(userKey))[0];
return {
email: updatedUser.email,
token: aCurrentUser.token,
username: updatedUser.username,
bio: updatedUser.bio,
image: updatedUser.image
};
},
async login(aUserData) {
// Get user with this email
const queryResult = await ds.runQuery(
ds.createQuery(namespace, 'User').filter('email', '=', aUserData.email));
const foundUser = queryResult[0][0];
if (!foundUser) {
throw new Error(`Email not found: [${aUserData.email}]`);
}
foundUser.username = foundUser[ds.KEY].name;
const passwordCheckResult = await bcrypt.compare(aUserData.password, foundUser.password);
if (!passwordCheckResult) {
throw new Error('Incorrect password');
}
return {
email: foundUser.email,
token: this.mintToken(foundUser.username),
username: foundUser.username,
bio: foundUser.bio,
image: foundUser.image
};
},
async getProfile(aUsername, aCurrentUser) {
if (!aUsername) {
throw new Error('User name must be specified');
}
const user = (await ds.get(ds.key({ namespace, path: ['User', aUsername] })))[0];
if (!user) {
throw new Error(`User not found: [${aUsername}]`);
}
const profile = {
username: aUsername,
bio: user.bio,
image: user.image,
following: false,
};
if (aCurrentUser && aCurrentUser.username) {
profile.following = user.followers.includes(aCurrentUser.username);
}
return profile;
},
async followUser(aFollowerUsername, aFollowedUsername) {
return await this.mutateFollowing(aFollowerUsername, aFollowedUsername, true);
},
async unfollowUser(aFollowerUsername, aFollowedUsername) {
return await this.mutateFollowing(aFollowerUsername, aFollowedUsername, false);
},
async mutateFollowing(aFollowerUsername, aFollowedUsername, aMutation) {
const updates = [];
// Add/remove "following" array of follower
const followerUserKey = ds.key({ namespace, path: ['User', aFollowerUsername] });
const followerUser = (await ds.get(followerUserKey))[0];
if (!followerUser) {
throw new Error(`User not found: [${aFollowerUsername}]`);
}
if (aMutation) {
if (!followerUser.following.includes(aFollowedUsername)) {
followerUser.following.push(aFollowedUsername);
}
} else {
followerUser.following = followerUser.following.filter(e => e != aFollowedUsername);
}
updates.push({ key: followerUserKey, data: followerUser, });
// Add/remove "followers" array of followed
const followedUserKey = ds.key({ namespace, path: ['User', aFollowedUsername] });
const followedUser = (await ds.get(followedUserKey))[0];
if (!followedUser) {
throw new Error(`User not found: [${aFollowedUsername}]`);
}
if (aMutation) {
if (!followedUser.followers.includes(aFollowerUsername)) {
followedUser.followers.push(aFollowerUsername);
}
} else {
followedUser.followers = followedUser.followers.filter(e => e != aFollowerUsername);
}
updates.push({ key: followedUserKey, data: followedUser });
await ds.update(updates);
// Return profile of followed user
return {
username: aFollowedUsername,
bio: followedUser.bio,
image: followedUser.image,
following: aMutation,
};
},
// ===== Token managenement
async authenticateToken(aToken) {
const decoded = jwt.verify(aToken, tokenSecret);
const username = decoded.username;
const result = await ds.get(ds.key({ namespace, path: ['User', decoded.username], }));
const foundUser = result[0];
if (!foundUser) {
throw new Error('Invalid token');
}
return {
username,
token: aToken,
email: foundUser.email,
bio: foundUser.bio,
image: foundUser.image,
};
},
mintToken(aUsername) {
return jwt.sign({ username: aUsername }, tokenSecret, { expiresIn: '2 days' });
},
testutils: {
async __deleteAllUsers() {
/* istanbul ignore next */
if (!namespace.startsWith('test')) {
console.warn(`__deleteAllUsers: namespace does not start with "test" but is [${namespace}], skipping.`);
return;
}
const userKeys = (await ds.createQuery(namespace, 'User').select('__key__').run())[0];
userKeys.forEach(async (userKey) => {
await ds.delete(userKey[ds.KEY]);
});
},
},
};
async function verifyEmailIsNotTaken(aEmail) {
const usersWithThisEmail = await ds.runQuery(
ds.createQuery(namespace, 'User').filter('email', '=', aEmail));
if (usersWithThisEmail[0].length) {
throw new Error(`Email already taken: [${aEmail}]`);
}
}