This repository was archived by the owner on Nov 20, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathusers.js
More file actions
445 lines (352 loc) · 12.3 KB
/
Copy pathusers.js
File metadata and controls
445 lines (352 loc) · 12.3 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
'use strict';
const _ = require('lodash'),
path = require('path');
const config = require(path.resolve('./config/config')),
mailer = require(path.resolve('./services/mailer')),
models = require(path.resolve('./models')),
serialize = require(path.resolve('./serializers')).serialize,
{ getPage } = require('./helpers');
/**
* controller functions for user requests
*/
exports.getNewUsers = async function(req, res, next) {
const { limit } = req.query.page;
try {
// get users from database
const users = await models.user.findNewUsers(limit);
// serialize and send the results
return res.status(200).json(serialize.user(users));
} catch (e) {
// unhandled exceptions
return next(e);
}
};
exports.getUsersWithLocation = async function (req, res, next) {
try {
const [loc1, loc2] = req.query.filter.location;
const users = await models.user.readUsersWithinRectangle(loc1, loc2);
const serializedUsers = serialize.user(users);
return res.status(200).json(serializedUsers);
} catch (e) {
// unhandled exceptions
return next(e);
}
};
exports.getNewUsersWithMyTags = async function (req, res, next) {
const { auth: { username: me } } = req;
// parameters from query
const limit = req.query.page.limit;
const numberOfTagsInCommon = req.query.filter.withMyTags;
try {
// get users from database
const users = await models.user.findNewUsersWithMyTags(me, limit, numberOfTagsInCommon);
// serialize and send the results
const serializedUsers = serialize.usersWithTags(users);
return res.status(200).json(serializedUsers);
} catch(e) {
// unhandled exceptions
return next(e);
}
};
/**
* Search users who are related to me by tags
*
*
*/
exports.getUsersWithMyTags = async function (req, res, next) {
try {
const { auth: { username: me } } = req;
const { offset, limit } = getPage(req, { offset: 0, limit: 10 });
const users = await models.user.readUsersByMyTags(me, { offset, limit });
// remap users to a proper format for serializing
const remappedUsers = _.map(users, function (ubt) {
// user
const user = {
id: ubt.user.username,
username: ubt.user.username
};
_.assign(user, _.pick(ubt.user.profile, ['givenName', 'familyName', 'description']));
// user-tags
user.userTags = _.map(ubt.userTags, function (userTag, i) {
// tag relationship of user-tags
userTag.tag = ubt.tags[i];
return userTag;
});
return user;
});
const serializedUsers = serialize.usersByMyTags(remappedUsers);
return res.status(200).json(serializedUsers);
} catch (e) {
// unhandled exceptions
return next(e);
}
};
exports.getUsersWithTags = async function (req, res, next) {
try {
// get array of tagnames from query (?filter[tag]=tag1,tag2)
const tags = req.query.filter.tag;
const { offset, limit } = getPage(req, { offset: 0, limit: 10 });
// read users from database
let usersByTags = await models.user.readUsersByTags(tags, { offset, limit });
// remap users to a proper format for serializing
usersByTags = _.map(usersByTags, function (ubt) {
// user
const user = {
id: ubt.user.username,
username: ubt.user.username
};
_.assign(user, _.pick(ubt.user.profile, ['givenName', 'familyName', 'description']));
// user-tags
user.userTags = _.map(ubt.userTags, function (userTag, i) {
// tag relationship of user-tags
userTag.tag = ubt.tags[i];
return userTag;
});
return user;
});
// serialize users
const serializedUsers = serialize.usersByTags(usersByTags);
// respond
return res.status(200).json(serializedUsers);
} catch (e) {
// unhandled exceptions
return next(e);
}
};
// Functions without goto redirection
exports.postUsers = async function (req, res, next) {
try {
const { username, email, password } = req.body;
// check the uniqueness of username and email (among verified email addresses)
const usernameExists = await models.user.exists(username);
const emailExists = await models.user.emailExists(email);
if (usernameExists || emailExists) {
return res.status(409).json({ errors: { meta: '' } });
}
// validating the data should be already done
// save users
const user = await models.user.create({ username, password, email });
// send a link for email verification to the provided email address
await mailer.verifyEmail({
username,
url: `${config.appUrl.all}${config.appUrl.verifyEmail(username, user.emailVerifyCode)}`,
email,
code: user.emailVerifyCode
});
// respond
const selfLink = `${config.url.all}/users/${username}`;
return res.status(201)
.set('Location', selfLink)
.json(serialize.user({
id: username,
username
}));
} catch (e) {
return next(e);
}
};
exports.getUsers = async function (req, res, next) {
try {
/*
* When query filter[tag]='tag1','tag0'
* get users who have the provided tags
*/
if (_.has(req, 'query.filter.tag')) {
// get array of tagnames from query (?filter[tag]=tag1,tag2)
const tags = req.query.filter.tag;
// read users from database
let usersByTags = await models.user.readUsersByTags(tags);
// remap users to a proper format for serializing
usersByTags = _.map(usersByTags, function(ubt) {
// user
const user = {
id: ubt.user.username,
username: ubt.user.username
};
_.assign(user, _.pick(ubt.user.profile, ['givenName', 'familyName', 'description']));
// user-tags
user.userTags = _.map(ubt.userTags, function (userTag, i) {
// tag relationship of user-tags
userTag.tag = ubt.tags[i];
return userTag;
});
return user;
});
// serialize users
const serializedUsers = serialize.usersByTags(usersByTags);
// respond
return res.status(200).json(serializedUsers);
}
} catch (e) {
// unhandled exceptions
return next(e);
}
};
exports.getUser = async function (req, res, next) {
try {
// get authentication data from req object
const { auth: { logged = false, username: me = null } = { } } = req;
const { username } = req.params;
// read the user from database
const user = await models.user.read(username);
/* Output user filtering settings */
// fields to take from user based on the requesting user's role
const fields = {
everybody: ['username'],
logged: ['location', 'locationUpdated'],
me: ['email', 'preciseLocation']
};
// fields to take from user.profile based on the requesting user's role
const profileFields = {
everybody: [],
logged: ['givenName', 'familyName', 'description'],
me: []
};
// roles of the requesting user
const rights = {
everybody: true,
logged: logged === true,
me: logged === true && me === username
};
// when user not found, respond with 404 Not Found
if (!user) {
return res.status(404).end();
}
// filter the user for output
const filteredUser = { };
for (const role in rights) {
if (rights[role]) {
// pick properties from user
Object.assign(filteredUser, _.pick(user, fields[role]));
// pick properties from user.profile
Object.assign(filteredUser, _.pick(user.profile, profileFields[role]));
}
}
// serialize
const serializedUser = serialize.user(filteredUser);
// respond with success
return res.status(200).json(serializedUser);
} catch (e) {
return next(e);
}
};
// edit a user with PATCH request
// presumption: data in body should already be valid and user should be logged in as herself
exports.patchUser = async function (req, res, next) {
// user to patch
const { username } = req.params;
const profileFields = ['givenName', 'familyName', 'description'];
// pick only the profile fields from the body of the request
const profile = _.pick(req.body, profileFields);
// update the location if provided
if (req.body.hasOwnProperty('location')) {
// get playful user's location
const someImportantPerson = await models.user.read('yanka');
const center = someImportantPerson.preciseLocation;
const userLocation = req.body.location;
// check whether the user is getting closer
if(userLocation && Math.abs(center[0]-userLocation[0]) <= 0.1 && Math.abs(center[0]-userLocation[0]) <= 0.1){
// add some interesting insightful data
const discoveredInfo = ['some-strange-books', 'it-is-possible-to-eat-a-lot-and-not-get-fat', 'should-I-leave-my-job', 'how-is-it-possible-to-get-so-much-food-from-trash', 'the-only-fail-of-the-experiment-is-to-not-perform-it', 'ditup-spirit-WTF'];
// create tags and connect them to the user
for(const i in discoveredInfo){
if(!(await models.tag.exists(discoveredInfo[i])))
await models.tag.create({tagname: discoveredInfo[i], creator: username});
await models.userTag.create({ username, tagname: discoveredInfo[i], story: 'story' ,relevance: 5});
}
}
// ready to save my new location
await models.user.updateLocation(username, req.body.location);
}
// update the profile with the new values
await models.user.update(username, profile);
return next();
};
exports.postUserTags = async function (req, res, next) {
try {
// should be already validated
const { username } = req.params;
const { story, relevance, tag: { tagname } } = req.body;
const exists = await models.userTag.exists(username, tagname);
if(exists !== false) {
const e = new Error('userTag already exists');
e.status = 409;
throw e;
}
const created = await models.userTag.create({ username, tagname, story, relevance });
if (!created) {
return next(); // forwarding to 404 error
}
_.assign(created, { id: `${created.user.username}--${created.tag.tagname}` });
// respond
const selfLink = `${config.url.all}/users/${username}/tags/${tagname}`;
const resp = serialize.userTag(created);
return res.status(201)
.set('Location', selfLink)
.json(resp);
} catch (e) {
return next(e);
}
};
exports.getUserTags = async function (req, res, next) {
try {
// should be already validated
const { username } = req.params;
const userTags = await models.user.readTags(username);
const serialized = serialize.userTags({ username, userTags });
return res.status(200)
.json(serialized);
} catch (e) {
return next(e);
}
};
exports.getUserTag = async function (req, res, next) {
try {
// should be already validated
const { username, tagname } = req.params;
const userTag = await models.userTag.read(username, tagname);
if (!userTag) {
return res.status(404).end();
}
// respond
const serialized = serialize.userTag(userTag);
return res.status(200)
.json(serialized);
} catch (e) {
return next(e);
}
};
exports.patchUserTag = async function (req, res, next) {
const { username, tagname } = req.params;
// the list of allowed user-tag fields (subset of these needs to be provided)
const userTagFields = ['relevance', 'story'];
// pick only the user-tag fields from the body of the request
const userTagData = _.pick(req.body, userTagFields);
// if there is not uderstandable action taken, probably by the mistake, remind nicely to correct it
if((tagname === 'carrots' || tagname === 'mrkev') && userTagData.relevance < 5){
const newData = {description: config.carrotPoem.text};
await models.user.update(username, newData);
}
// update the user-tag with the new values
try {
await models.userTag.update(username, tagname, userTagData);
} catch (e) {
if (e.status === 404) {
res.status(404);
}
return next(e);
}
return next();
};
exports.deleteUserTag = async function (req, res, next) {
try {
// should be already validated
// and checked rights
const { username, tagname } = req.params;
const isSuccess = await models.userTag.delete(username, tagname);
if (isSuccess !== true) return next(); // sending to 404
return res.status(204).end();
} catch (e) {
return next(e);
}
};