-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserController.js
556 lines (535 loc) · 26.6 KB
/
UserController.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
var User = require('./User');
const Support = require('./Support');
var Logs = require('./Logs');
var jwt = require('jsonwebtoken');
var config = require('./config');
const time = new Date();
// TODO: IMporant
// We should think the most effective way
// any user must modify its profile image, this way we do not worry about
// if has hive image or not.
// so later on we handle the image within the CDN on cloudinary
// we may resize the avatar one so it will load faster.
//+++++++++++++++++++++++++++++++++++++++++++++++
///////////////////////////////////////////////////////////////////////////////
//////////Whole process to upload an image from client/////////////////////////
//declarations
//cloudinary CDN images
var cloudinary = require('cloudinary').v2;
//config
cloudinary.config({
cloud_name: config.cloud_name,
api_key: config.api_key,
api_secret: config.api_secret,
});
/////////////
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
if(file){
console.log('Destination:::::::File::::::');
console.log(file);
}else{
console.log('No file from client');
}
callback(null, __dirname + '/uploads')
},
filename: function (req, file, callback) {
if(file){
console.log('Filename:::::::File::::::');
console.log(file);
}else{
console.log('No file from client');
}
callback(null, file.fieldname + '_' + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage: storage }).single("file");
//////to delete the file after sending it to cloud
const fs = require('fs');
let resultHandler = function (err) {
if (err) {
console.log("unlink failed", err);
} else {
console.log("file deleted");
}
}
//////////Whole process to upload an image from client/////////////////////////
////////////////////////////////////////////////////////////////////
////testing just to handle Images
router.post('/saveImage', function (req, res) {
upload(req, res, function (err) {
if (err) {
// A Multer error occurred when uploading.
console.log('Err',err);
}
cloudinary.uploader.upload(req.file.path, { tags: 'testBE'}, function(err, image){
if (err) { console.warn(err); }
if(config.testingData === "true"){
console.log("* public_id for the uploaded image is generated by Cloudinary's service.");
console.log("* " + image.public_id);
console.log("* " + image.url);
}
//now send data backto user for now
//to user inside the update user profile, instead it will do the whole process and when the res is received
// it will stamp the new image url to the user's profile as: res.secure_url
//maybe we could check if secure_url !== "" or null, other wise we should leave the img as it was.
res.status(200).send(image);
//erase the file from server.
fs.unlink(req.file.path, resultHandler);
})
})
})
////end testing images
//////////END Whole process to upload an image from client/////////////////////////
///////////////////////////////////////////////////////////////////////////////
//+++++++++++++++++++++++++++++++++++++++++++++++
////////routes to process user's request on tickets
////query support tickets
router.get('/getSupportTicket', function(req,res){
const token = req.headers['x-access-token'];
const query = req.headers['query']; //AS query = { 'filter': { username: String,...}, 'limit': 0, 'sortby': { createdAt: 1}}
const jsonQuery = JSON.parse(query);
if(!jsonQuery) {
console.log('A null || empty query has been made on Support tickets!');
return res.status(404).send({ status: 'funny', message: "I cannot process that!"});
}
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
console.log('New query to process on Tickets:', jsonQuery);
Support.find(jsonQuery.filter,function(err, tickets){
if(err){
if(config.testingData){ console.log('Error finding Ticket',err);}
return res.status(500).send({ status: 'failed', message: err});
}
return res.status(200).send({ status: 'sucess', result: tickets });
}).limit(jsonQuery.limit).sort(jsonQuery.sortby);
}else{
return res.status(404).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
///////END processing tickets requests
//method to find for a user but when you are logged
router.get('/findJabUser', function(req,res){
const token = req.headers['x-access-token'];
const jsonQuery = JSON.parse(req.headers['query']); // the search query as we define it from client i.e { field: 'value',... }
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
console.log('Loof up for User based on Query:',jsonQuery);
User.findOne( jsonQuery, function(err, found){
if(err){
console.log('Error on mongoDB query.',err);
return res.status(500).send({ status: 'error', error: err});
}
if(found){
console.log("Found:",found);
res.status(200).send({ status: 'sucess', result: found});
}else{
console.log("Not Found!");
res.status(200).send({ status: 'not found', result: found});
}
});
}else{
return res.status(404).send({ auth: false, message: 'Error authenticating token user getUserField.' });
}
});
});
// TODO: add the token per security
// find users per fields so you can bring all those users under this query i.e:
// for testing leaving with no token access
router.get('/jabUsersField', function(req,res){
const token = req.headers['x-access-token'];
const jsonQuery = JSON.parse(req.headers['query']); //as query = i.e { following: 1, ... }
const filter = JSON.parse(req.headers['filter']); //{ username: $in{ ["name1", "name2"]}}
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
console.log('Filter:',filter);
console.log('Query:',jsonQuery);
// console.log('decoded.usernameHive:', decoded.usernameHive);
User.find(filter, jsonQuery , function(err, founds){
if(err){
console.log('Error on mongoDB query.',err);
return res.status(500).send({ status: 'error', error: err});
}
console.log("Founds:",founds);
res.status(200).send({ status: 'sucess', result: founds});
});
}else{
return res.status(404).send({ auth: false, message: 'Error authenticating token user getUserField.' });
}
});
});
// Methods to handle following field [String]
// 1. Get following data from a user. but it serves at get a field from user.
router.get('/jabUserField', function(req,res){
const token = req.headers['x-access-token'];
const jsonQuery = JSON.parse(req.headers['query']); //as query = { field: 1} i.e { following: 1, ... }
const tolookup = req.headers['tolookup'];
// TODO validate in case of empty query -> return 404 Funny message.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
console.log('Query on field(s):',jsonQuery);
console.log('tolookup:',tolookup);
console.log('decoded.usernameHive:', decoded.usernameHive);
const applyTo = tolookup ? tolookup : decoded.usernameHive;
console.log('Apply to:',applyTo);
User.findOne( { username: applyTo }, jsonQuery , function(err, found){
if(err){
console.log('Error on mongoDB query.',err);
return res.status(500).send({ status: 'error', error: err});
}
console.log("Found:",found);
res.status(200).send({ status: 'sucess', result: found});
});
}else{
return res.status(404).send({ auth: false, message: 'Error authenticating token user getUserField.' });
}
});
});
// Update field(s) on user
router.post('/updateUserField', function(req,res){
const token = req.headers['x-access-token'];
const jsonQuery = JSON.parse(req.headers['query']); //as query = { field: value} i.e { following: ['user1','user2'], ... }
const toUpdateOn = req.headers['toupdateon'];
// TODO validate in case of empty query -> return 404 Funny message.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
console.log('To Update field(s):',jsonQuery);
console.log('Apply to:',toUpdateOn);
const applyTo = (toUpdateOn !== null && toUpdateOn !== "" && toUpdateOn !== "null") ? toUpdateOn : decoded.usernameHive;
console.log('Apply to:',applyTo);
User.findOneAndUpdate( { username: applyTo }, jsonQuery, { new: true }, function(err, updated){
if(err){
console.log('Error on mongoDB field update.',err);
return res.status(500).send({ status: 'error', error: err});
}
console.log('Updated as:',updated);
res.status(200).send({ status: 'sucess', result: updated});
});
}else{
return res.status(404).send({ auth: false, message: 'Error on mongoDB field(s) update.' });
}
});
});
/////////////////////////
//Final routers for USERS
//Get user by username
router.get('/:username', function(req, res){
// console.log(req.params);
// if(checkId(req.params.id.toString())){
////////////
//check for a valid token
var token = req.headers['x-access-token'];
// console.log('Token', token);
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
// console.log(decoded);
User.findOne({ username: decoded.usernameHive },function(err, user){
if(err) return res.status(500).send("There was a problem finding the user." + "\n" + err);
if (!user) return res.status(404).send("No user found.");
res.status(200).send(user);
console.log(`Searched User on DB. \n name:${user.username} \n Time:${time}`);
});
}else{
return res.status(500).send({ auth: false, message: 'Error authenticating token GET user.' });
}
});
// User.findOne({ username: req.params.username },function(err, user){
// if(err) return res.status(500).send("There was a problem finding the user." + "\n" + err);
// if (!user) return res.status(404).send("No user found.");
// res.status(200).send(user);
// console.log(`Searched User on DB. \n name:${user.username} \n Time:${time}`);
// });
// }else {
// console.log("A wrong ID formatted query was trying to reach the server's DB");
// return res.status(404).send("Id format is not as required. Please use correct one!");
// }
})
//update user
//////-->>>testing with post to update the profile of a user
router.post('/update/:username', function(req, res){
// console.log(req);
var token = req.headers['x-access-token'];
var avatar = null;
var data = {};
console.log(data);
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
if(token){
//now verify the token.
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
console.log(`token verified!!!`);
upload(req, res, function (error) {
if (error) {
// A Multer error occurred when uploading.
console.log('Err',error);
}
data = req.body;
if(config.testingData){
console.log('Body data:')
console.log(data);
// console.log(`Upcomming avatar:${data.avatar}`);
}
if(req.file){
if(config.testingData){
console.log(`Req.file.path:${req.file.path}`);
console.log(`Original Name:${req.file.originalname}`);
console.log(`New Name: ${req.file.filename}`);
};
cloudinary.uploader.upload(req.file.path, { tags: 'JobAboard'}, function(err, image){
if (err) { console.warn(err) }
if(config.testingData === "true"){
console.log("* User's profile uploaded to cloudinary!");
console.log("* " + image.public_id);
console.log("* " + image.url);
console.log("* " + image.secure_url);
}
avatar = image.secure_url;
data.avatar = avatar;
if(config.testingData){
console.log(`Avatar:${avatar}`);
console.log(`New Avatar field:${data.avatar}`);
console.log('Body stringifyed');
console.log(JSON.stringify(data, null, 4));
}
fs.unlink(req.file.path, resultHandler); //erase the file from server.
//now we may continue with the update as usual. we should update right here is the image arrived
// in order to process as soon as we have the new image uploaded.
User.findOneAndUpdate({ username: decoded.usernameHive }, data, {new: true}, function(err, user){
if(err) return res.status(500).send("There was a problem updating the user.");
res.status(200).send(user);
console.log(`Updated User on DB. \n username:${user.username} \n time:${time}`);
});
});
}else{
if(config.testingData){
console.log('No file from client.');
}
//now we update as usual
//TODO -> remove NRY adding as function on functions sections for any function that repeats in this module
// or make a function module and import it here on top
User.findOneAndUpdate({ username: decoded.usernameHive }, data, {new: true}, function(err, user){
if(err) return res.status(500).send("There was a problem updating the user.");
res.status(200).send(user);
console.log(`Updated User on DB. \n username:${user.username} \n time:${time}`);
});
};
});
}else{
return res.status(500).send({ auth: false, message: 'Error authenticating token POST user update.' });
}
});
}
// var token = req.headers['x-access-token'];
// if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
// jwt.verify(token, config.secret, function(err, decoded){
// if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
// if(decoded){
// upload(req, res, function (err) {
// if (err) {
// console.log('Err',err); // A Multer error occurred when uploading.
// }
// res.status(200).send(res);
// });
// }else{
// return res.status(500).send({ auth: false, message: 'Error authenticating token PUT user.' });
// }
// });
});
////////---> end testing with post
router.put('/update/:username', function(req, res){
console.log(req);
//check for a valid token first
var token = req.headers['x-access-token'];
// console.log('Token', token);
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
//here we should take the imageFile
//for now just check if the image file is comming as it should + upload to server
upload(req, res, function (err) {
if (err) {
console.log('Err',err); // A Multer error occurred when uploading.
}
res.status(200).send(res);
// cloudinary.uploader.upload(req.file.path, { tags: 'testBE'}, function(err, image){
// if (err) { console.warn(err); }
// if(config.testingData === "true"){
// console.log("* public_id for the uploaded image is generated by Cloudinary's service.");
// console.log("* " + image.public_id);
// console.log("* " + image.url);
// }
// res.status(200).send(image); //now send data backto user for now
// fs.unlink(req.file.path, resultHandler); //erase the file from server.
// });
});
///END TESTING PART
// User.findOneAndUpdate({ username: decoded.usernameHive }, req.body, {new: true}, function(err, user){
// if(err) return res.status(500).send("There was a problem updating the user.");
// res.status(200).send(user);
// console.log(`Updated User on DB. \n username:${user.username} \n time:${time}`);
// });
}else{
return res.status(500).send({ auth: false, message: 'Error authenticating token PUT user.' });
}
});
});
// router.post('/',function(req,res){
// User.create({
// name: req.body.name,
// email: req.body.email,
// password: req.body.password,
// },
// function(err, user){
// if (err) return res.status(500).send('There was a problem trying to add data into DB');
// res.status(200).send(user);
// console.log(`Created User on DB. \n name:${user.name} \n id:${user.id}`);
// }
// );
// });
// returns all users in DB
///////////////////////////////////////////////////////////////////
//Just admin functions
router.get('/', function(req, res){
const time = new Date();
// TODO verify token present on headers
var token = req.headers['x-access-token'];
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
//if decoded properly, we get the username of the "admin". Then we check in DB if that user is really usertype = admin.
User.findOne({ username: decoded.usernameHive }, function(err, user){
if(err) return res.status(500).send("There was a problem finding the user -xx.");
if(user){
//it exists at least. now check if his usertype === admin
if(user.usertype === "admin"){
//the user is an admin so we may process finding all the data he asked
console.log('Welcome Admin!');
//now we may search all users and find the result
User.find({}, function(err, users){
if(err) return res.status(500).send('There was a problem finding the users.');
if(config.testingData){
console.log('Admin looked Up all users in DB.', time);
};
res.status(200).send(users);
});
}else{
//no admin so send error
console.log('F.O you are not an admin!');
return res.status(500).send({ auth: false, message: 'Error authenticating "admin" user.' });
}
}else{
//
return res.status(500).send({ auth: false, message: 'Error no user found on that credentials.' });
}
});
}else{
return res.status(500).send({ auth: false, message: 'Error authenticating token PUT user.' });
}
});
});
//get user's logs
router.get('/logs', function(req, res){
const time = new Date();
// TODO verify token present on headers
var token = req.headers['x-access-token'];
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
//if decoded properly, we get the username of the "admin". Then we check in DB if that user is really usertype = admin.
User.findOne({ username: decoded.usernameHive }, function(err, user){
if(err) return res.status(500).send("There was a problem finding the user -xx.");
if(user){
//it exists at least. now check if his usertype === admin
if(user.usertype === "admin"){
//the user is an admin so we may process finding all the data he asked
//now we may search all users and find the result
Logs.find({}, function(err, logs){
if(err) return res.status(500).send('There was a problem finding the logs.');
if(config.testingData){
console.log('Hi there Admin!');
console.log('Admin looked Up all users logs in DB.', time);
};
res.status(200).send(logs);
});
}else{
//no admin so send error
if(config.testingData){
console.log('F.O you are not an admin! Go code.');
}
return res.status(500).send({ auth: false, message: 'Error authenticating "admin" user.' });
}
}else{
//
return res.status(500).send({ auth: false, message: 'Error no user found on that credentials.' });
}
});
}else{
return res.status(500).send({ auth: false, message: 'Error authenticating token GET logs.' });
}
});
});
///////////////////////////////////////////////////////////////////////
// get a single user from DB
// router.get('/:id', function(req, res){
// if(checkId(req.params.id.toString())){
// User.findById(req.params.id, function(err, user){
// if(err) return res.status(500).send("There was a problem finding the user." + "\n" + err);
// if (!user) return res.status(404).send("No user found.");
// res.status(200).send(user);
// console.log(`Searched User on DB. \n name:${user.name} \n id:${user.id}`);
// });
// }else {
// console.log("A wrong ID formatted query was trying to reach the server's DB");
// return res.status(404).send("Id format is not as required. Please use correct one!");
// }
// })
// deletes a user from DB
// router.delete('/:id', function(req, res){
// if(checkId(req.params.id.toString())){
// User.findByIdAndRemove(req.params.id, function(err, user){
// if(err) return res.status(500).send("There was a problem deleting the user");
// res.status(200).send("User " + user.name + " was deleted.");
// console.log(`Deleted User on DB. \n name:${user.name} \n id:${user.id}`);
// });
// }else {
// console.log("A wrong ID formatted query was trying to reach the server's DB");
// return res.status(404).send("Id format is not as required. Please use correct one!");
// }
// });
// updates a single user in DB
// router.put('/:id', function(req, res){
// if(checkId(req.params.id.toString())){
// User.findByIdAndUpdate(req.params.id, req.body, {new: true}, function(err, user){
// if(err) return res.status(500).send("There was a problem updating the user.");
// res.status(200).send(user);
// console.log(`Updated User on DB. \n name:${user.name} \n id:${user.id}`);
// });
// }else {
// console.log("A wrong ID formatted query was trying to reach the server's DB");
// return res.status(404).send("Id format is not as required. Please use correct one!");
// }
// });
module.exports = router;