-
Notifications
You must be signed in to change notification settings - Fork 61
/
User.js
334 lines (300 loc) · 9.08 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
const Util = require('./Util');
const usersTable = Util.getTableName('users');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
/**
* @module User
*/
module.exports = {
/** Create user */
async create(event) {
const body = JSON.parse(event.body);
if (!body.user) {
return Util.envelop('User must be specified.', 422);
}
const newUser = body.user;
if (!newUser.username) {
return Util.envelop('Username must be specified.', 422);
}
if (!newUser.email) {
return Util.envelop('Email must be specified.', 422);
}
if (!newUser.password) {
return Util.envelop('Password must be specified.', 422);
}
// Verify username is not taken
const userWithThisUsername = await getUserByUsername(newUser.username);
if (userWithThisUsername.Item) {
return Util.envelop(`Username already taken: [${newUser.username}]`, 422);
}
// Verify email is not taken
const userWithThisEmail = await getUserByEmail(newUser.email);
if (userWithThisEmail.Count !== 0) {
return Util.envelop(`Email already taken: [${newUser.email}]`, 422);
}
// Add new entry to usersTable
const encryptedPassword = bcrypt.hashSync(newUser.password, 5);
await Util.DocumentClient.put({
TableName: usersTable,
Item: {
username: newUser.username,
email: newUser.email,
password: encryptedPassword,
},
}).promise();
return Util.envelop({
user: {
email: newUser.email,
token: mintToken(newUser.username),
username: newUser.username,
bio: '',
image: '',
}
});
},
/** Login user */
async login(event) {
const body = JSON.parse(event.body);
if (!body.user) {
return Util.envelop('User must be specified.', 422);
}
const user = body.user;
if (!user.email) {
return Util.envelop('Email must be specified.', 422);
}
if (!user.password) {
return Util.envelop('Password must be specified.', 422);
}
// Get user with this email
const userWithThisEmail = await getUserByEmail(user.email);
if (userWithThisEmail.Count !== 1) {
return Util.envelop(`Email not found: [${user.email}]`, 422);
}
// Attempt to match password
if (!bcrypt.compareSync(user.password,
userWithThisEmail.Items[0].password)) {
return Util.envelop('Wrong password.', 422);
}
const authenticatedUser = {
email: user.email,
token: mintToken(userWithThisEmail.Items[0].username),
username: userWithThisEmail.Items[0].username,
bio: userWithThisEmail.Items[0].bio || '',
image: userWithThisEmail.Items[0].image || '',
};
return Util.envelop({ user: authenticatedUser });
},
/** Get user */
async get(event) {
const authenticatedUser = await authenticateAndGetUser(event);
if (!authenticatedUser) {
return Util.envelop('Token not present or invalid.', 422);
}
return Util.envelop({
user: {
email: authenticatedUser.email,
token: getTokenFromEvent(event),
username: authenticatedUser.username,
bio: authenticatedUser.bio || '',
image: authenticatedUser.image || '',
}
});
},
/** Update user */
async update(event) {
const authenticatedUser = await authenticateAndGetUser(event);
if (!authenticatedUser) {
return Util.envelop('Token not present or invalid.', 422);
}
const body = JSON.parse(event.body);
const user = body.user;
if (!user) {
return Util.envelop('User must be specified.', 422);
}
const updatedUser = {
username: authenticatedUser.username,
};
if (user.email) {
// Verify email is not taken
const userWithThisEmail = await getUserByEmail(user.email);
if (userWithThisEmail.Count !== 0) {
return Util.envelop(`Email already taken: [${user.email}]`, 422);
}
updatedUser.email = user.email;
}
if (user.password) {
updatedUser.password = bcrypt.hashSync(user.password, 5);
}
if (user.image) {
updatedUser.image = user.image;
}
if (user.bio) {
updatedUser.bio = user.bio;
}
await Util.DocumentClient.put({
TableName: usersTable,
Item: updatedUser,
}).promise();
// Decorate updatedUser and return it
if (updatedUser.password) {
delete updatedUser.password;
}
if (!updatedUser.email) {
updatedUser.email = authenticatedUser.email;
}
if (!updatedUser.image) {
updatedUser.image = authenticatedUser.image || '';
}
if (!updatedUser.bio) {
updatedUser.bio = authenticatedUser.bio || '';
}
updatedUser.token = getTokenFromEvent(event);
return Util.envelop({
user: updatedUser,
});
},
authenticateAndGetUser,
getUserByUsername,
async getProfile(event) {
const username = event.pathParameters.username;
const authenticatedUser =
await authenticateAndGetUser(event);
const profile = await getProfileByUsername(username,
authenticatedUser);
if (!profile) {
return Util.envelop(`User not found: [${username}]`, 422);
}
return Util.envelop({ profile });
},
getProfileByUsername,
async follow(event) {
const authenticatedUser = await authenticateAndGetUser(event);
if (!authenticatedUser) {
return Util.envelop('Token not present or invalid.', 422);
}
const username = event.pathParameters.username;
const user = (await getUserByUsername(username)).Item;
const shouldFollow = !(event.httpMethod === 'DELETE');
// Update "followers" field on followed user
if (shouldFollow) {
if (user.followers &&
!user.followers.values.includes(authenticatedUser.username)) {
user.followers.values.push(authenticatedUser.username);
} else {
user.followers = Util.DocumentClient.createSet(
[authenticatedUser.username]);
}
} else {
if (user.followers &&
user.followers.values.includes(authenticatedUser.username)) {
user.followers.values = user.followers.values.filter(
e => e != authenticatedUser.username
);
if (!user.followers.values.length) {
delete user.followers;
}
}
}
await Util.DocumentClient.put({
TableName: usersTable,
Item: user,
}).promise();
// Update "following" field on follower user
if (shouldFollow) {
if (authenticatedUser.following &&
!authenticatedUser.following.values.includes(username)) {
authenticatedUser.following.values.push(username);
} else {
authenticatedUser.following = Util.DocumentClient.createSet([username]);
}
} else {
if (authenticatedUser.following &&
authenticatedUser.following.values.includes(username)) {
authenticatedUser.following.values =
authenticatedUser.following.values.filter(
e => e != username
);
/* istanbul ignore next */
if (!authenticatedUser.following.values.length) {
delete authenticatedUser.following;
}
}
}
await Util.DocumentClient.put({
TableName: usersTable,
Item: authenticatedUser,
}).promise();
const profile = {
username,
bio: user.bio || '',
image: user.image || '',
following: shouldFollow,
};
return Util.envelop({ profile });
},
/** Create followed users */
async getFollowedUsers(aUsername) {
const user = (await Util.DocumentClient.get({
TableName: usersTable,
Key: {
username: aUsername,
},
}).promise()).Item;
return user.following ? user.following.values : [];
},
};
function mintToken(aUsername) {
return jwt.sign({ username: aUsername },
Util.tokenSecret, { expiresIn: '2 days' });
}
function getUserByEmail(aEmail) {
return Util.DocumentClient.query({
TableName: usersTable,
IndexName: 'email',
KeyConditionExpression: 'email = :email',
ExpressionAttributeValues: {
':email': aEmail,
},
Select: 'ALL_ATTRIBUTES',
}).promise();
}
function getUserByUsername(aUsername) {
return Util.DocumentClient.get({
TableName: usersTable,
Key: {
username: aUsername,
},
}).promise();
}
function getTokenFromEvent(event) {
return event.headers.Authorization.replace('Token ', '');
}
async function getProfileByUsername(aUsername, aAuthenticatedUser) {
const user = (await getUserByUsername(aUsername)).Item;
if (!user) {
return null;
}
const profile = {
username: user.username,
bio: user.bio || '',
image: user.image || '',
following: false,
};
// If user is authenticated, set following bit
if (user.followers && aAuthenticatedUser) {
profile.following = user.followers.values
.includes(aAuthenticatedUser.username);
}
return profile;
}
async function authenticateAndGetUser(event) {
try {
const token = getTokenFromEvent(event);
const decoded = jwt.verify(token, Util.tokenSecret);
const username = decoded.username;
const authenticatedUser = await getUserByUsername(username);
return authenticatedUser.Item;
} catch (err) {
return null;
}
}