You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

607 lines
20 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. //File: controllers/userController.js
  2. var mongoose = require('mongoose');
  3. var userModel = mongoose.model('userModel');
  4. var notificationModel = mongoose.model('notificationModel');
  5. var travelModel = mongoose.model('travelModel');
  6. var config = require('../config');
  7. var pageSize = config.pageSize;
  8. /* */
  9. var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
  10. var express = require("express");
  11. var app = express();
  12. var config = require('../config'); // get our config file
  13. app.set('superSecret', config.secret); // secret variable
  14. var crypto = require('crypto');
  15. /* */
  16. var request = require('request');
  17. function getRand(min, max) {
  18. min = Math.ceil(min);
  19. max = Math.floor(max);
  20. return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
  21. }
  22. function getAvatar(n) {
  23. switch (n) {
  24. case 1:
  25. avatar = "img/avatars/racoon.png";
  26. break;
  27. case 2:
  28. avatar = "img/avatars/duck.png";
  29. break;
  30. case 3:
  31. avatar = "img/avatars/clown-fish.png";
  32. break;
  33. case 4:
  34. avatar = "img/avatars/tiger.png";
  35. break;
  36. case 5:
  37. avatar = "img/avatars/sloth.png";
  38. break;
  39. case 6:
  40. avatar = "img/avatars/penguin.png";
  41. break;
  42. case 7:
  43. avatar = "img/avatars/owl.png";
  44. break;
  45. case 8:
  46. avatar = "img/avatars/chameleon.png";
  47. break;
  48. case 9:
  49. avatar = "img/avatars/siberian-husky.png";
  50. break;
  51. case 10:
  52. avatar = "img/avatars/toucan.png";
  53. break;
  54. default:
  55. avatar = "img/avatars/racoon.png";
  56. }
  57. return avatar;
  58. }
  59. //POST - Insert a new User in the DB
  60. exports.signup = function(req, res) {
  61. //get random avatar
  62. var r = getRand(1, 10);
  63. randAvatar = getAvatar(r);
  64. var user = new userModel({
  65. username: req.body.username,
  66. password: crypto.createHash('sha256').update(req.body.password).digest('base64'),
  67. description: req.body.description,
  68. avatar: randAvatar,
  69. email: req.body.email,
  70. phone: req.body.phone,
  71. telegram: req.body.telegram
  72. });
  73. if (user.username == undefined) {
  74. return res.status(500).jsonp("empty inputs");
  75. } else if (user.password == undefined) {
  76. return res.status(500).jsonp("empty inputs");
  77. } else if (user.email == undefined) {
  78. return res.status(500).jsonp("empty inputs");
  79. }
  80. user.save(function(err, user) {
  81. if (err) return res.send(500, err.message);
  82. exports.login(req, res);
  83. });
  84. };
  85. //POST - auth user
  86. exports.login = function(req, res) {
  87. // find the user
  88. userModel.findOne({
  89. username: req.body.username
  90. })
  91. .select('+password')
  92. .exec(function(err, user) {
  93. if (err) throw err;
  94. if (!user) {
  95. res.json({
  96. success: false,
  97. message: 'Authentication failed. User not found.'
  98. });
  99. } else if (user) {
  100. req.body.password = crypto.createHash('sha256').update(req.body.password).digest('base64');
  101. // check if password matches
  102. if (user.password != req.body.password) {
  103. res.json({
  104. success: false,
  105. message: 'Authentication failed. Wrong password.'
  106. });
  107. } else {
  108. // if user is found and password is right
  109. // create a token
  110. var token = jwt.sign({
  111. foo: 'bar'
  112. }, app.get('superSecret'), {
  113. //expiresInMinutes: 1440 // expires in 24 hours
  114. //expiresIn: '60m'
  115. });
  116. user.token = token;
  117. user.save(function(err, user) {
  118. if (err) return res.send(500, err.message);
  119. //res.status(200).jsonp(travel);
  120. console.log(user);
  121. // return the information including token as JSON
  122. user.password = "";
  123. res.json({
  124. success: true,
  125. message: 'Enjoy your token!',
  126. token: token,
  127. user: user
  128. });
  129. });
  130. }
  131. }
  132. });
  133. };
  134. //GET - Return all Users in the DB
  135. exports.getAllUsers = function(req, res) {
  136. userModel.find()
  137. .limit(pageSize)
  138. .skip(pageSize * Number(req.query.page))
  139. .exec(function(err, users) {
  140. if (err) return res.send(500, err.message);
  141. res.status(200).jsonp(users);
  142. });
  143. };
  144. exports.getUserById = function(req, res) {
  145. userModel.findOne({
  146. _id: req.params.userid
  147. })
  148. .lean()
  149. .populate('validatedBy', 'username')
  150. .populate('travels', 'title from to date type')
  151. .exec(function(err, user) {
  152. if (err) return res.send(500, err.message);
  153. if (!user) {
  154. res.json({
  155. success: false,
  156. message: 'User not found.'
  157. });
  158. } else if (user) {
  159. res.status(200).jsonp(user);
  160. }
  161. });
  162. };
  163. exports.getUserByToken = function(req, res) {
  164. userModel.findOne({
  165. 'token': req.headers['x-access-token']
  166. })
  167. .lean()
  168. .populate('travels', 'title from to date')
  169. .exec(function(err, user) {
  170. if (err) return res.send(500, err.message);
  171. if (!user) {
  172. res.json({
  173. success: false,
  174. message: 'User not found.'
  175. });
  176. } else if (user) {
  177. res.status(200).jsonp(user);
  178. }
  179. });
  180. };
  181. exports.getTravelsByUserId = function(req, res) {
  182. travelModel.find({
  183. user: req.params.userid
  184. })
  185. .lean()
  186. .exec(function(err, travels) {
  187. if (err) return res.send(500, err.message);
  188. travelModel.find({
  189. joins: req.params.userid
  190. })
  191. .lean()
  192. .exec(function(err, joins) {
  193. if (err) return res.send(500, err.message);
  194. res.json({
  195. travels: travels,
  196. joins: joins
  197. });
  198. });
  199. });
  200. };
  201. exports.getUserLikes = function(req, res) {
  202. userModel.findOne({
  203. _id: req.params.userid
  204. })
  205. .lean()
  206. .populate('likes', 'username avatar description')
  207. .exec(function(err, user) {
  208. if (err) return res.send(500, err.message);
  209. if (!user) {
  210. res.json({
  211. success: false,
  212. message: 'User not found.'
  213. });
  214. } else if (user) {
  215. res.status(200).jsonp(user.likes);
  216. }
  217. });
  218. };
  219. exports.getNumNotificationsByToken = function(req, res) {
  220. userModel.findOne({
  221. 'token': req.headers['x-access-token']
  222. })
  223. .lean()
  224. .exec(function(err, user) {
  225. if (err) return res.send(500, err.message);
  226. if (!user) {
  227. res.json({
  228. success: false,
  229. message: 'User not found.'
  230. });
  231. } else if (user) {
  232. res.status(200).jsonp(user.notifications);
  233. }
  234. });
  235. };
  236. exports.getNotifications = function(req, res) {
  237. userModel.findOne({
  238. 'token': req.headers['x-access-token']
  239. })
  240. .lean()
  241. .populate('notifications')
  242. .exec(function(err, user) {
  243. if (err) return res.send(500, err.message);
  244. if (!user) {
  245. res.json({
  246. success: false,
  247. message: 'User not found.'
  248. });
  249. } else if (user) {
  250. notificationModel.find({
  251. 'user': user._id,
  252. 'state': 'pendent'
  253. })
  254. .lean()
  255. .exec(function(err, notifications) {
  256. if (err) return res.send(500, err.message);
  257. if (!notifications) {
  258. res.json({
  259. success: false,
  260. message: 'No pendent notifications.'
  261. });
  262. } else if (notifications) {
  263. //here, maybe in the future is better delete the viewed notifications
  264. notificationModel.update({
  265. state: "pendent"
  266. }, {
  267. state: "viewed"
  268. }, {
  269. multi: true
  270. },
  271. function(err) {
  272. if (err) {
  273. console.log(err);
  274. }
  275. }
  276. );
  277. res.status(200).jsonp(notifications);
  278. }
  279. });
  280. //now, clean notifications count from user
  281. userModel.update({
  282. 'token': req.headers['x-access-token']
  283. }, {
  284. notifications: []
  285. },
  286. function(err) {
  287. if (err) {
  288. console.log(err);
  289. }
  290. }
  291. );
  292. }
  293. });
  294. };
  295. function getRandomInt(min, max) {
  296. min = Math.ceil(min);
  297. max = Math.floor(max);
  298. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  299. }
  300. function postImage(req, res, filename, fileImg) {
  301. url = "http://127.0.0.1:3050/image";
  302. var importFile = function(fileImg) {
  303. var decodedFile = new Buffer(fileImg, 'base64');
  304. var r = request.post(url, function(err, httpResponse, body) {
  305. if (err) {
  306. console.log(err);
  307. }
  308. //console.log(body);
  309. updateUserWithNewImages(req, res, body);
  310. });
  311. var form = r.form();
  312. form.append('file', decodedFile, {
  313. filename: filename + '.png'
  314. });
  315. }
  316. importFile(fileImg);
  317. }
  318. function updateUserWithNewImages(req, res, imgUrl) {
  319. //adding random number to the url, to force ionic reload the image
  320. req.body.avatar = imgUrl + "?" + getRandomInt(1, 9999);
  321. userModel.update({
  322. 'token': req.headers['x-access-token']
  323. }, req.body,
  324. function(err) {
  325. if (err) return console.log(err);
  326. exports.getUserByToken(req, res);
  327. });
  328. }
  329. exports.updateUser = function(req, res) {
  330. if (req.body.newAvatar) {
  331. urlImg = postImage(req, res, "avatar_" + req.body.username, req.body.newAvatar);
  332. }
  333. /*if (req.body.newFaircoin) {
  334. urlImg = postImage(req, res, "fairdir_"+req.body.username,req.body.newFaircoin);
  335. }*/
  336. if (!req.body.newAvatar) {
  337. updateUserWithNewImages(req, res, req.body.avatar);
  338. }
  339. /*userModel.update({
  340. 'token': req.headers['x-access-token']
  341. }, req.body,
  342. function(err) {
  343. if (err) return console.log(err);
  344. exports.getUserByToken(req, res);
  345. });*/
  346. };
  347. //DELETE - Delete a user with specified ID
  348. exports.deleteUser = function(req, res) {
  349. userModel.findOne({
  350. 'token': req.headers['x-access-token']
  351. })
  352. .exec(function(err, user) {
  353. user.remove(function(err) {
  354. if (err) return res.send(500, err.message);
  355. res.status(200).jsonp("deleted");
  356. })
  357. });
  358. };
  359. exports.likeUser = function(req, res) {
  360. userModel.findOne({
  361. 'token': req.headers['x-access-token']
  362. })
  363. .exec(function(err, userL) {
  364. if (err) return res.send(500, err.message);
  365. if (!userL) {
  366. res.json({
  367. success: false,
  368. message: 'no user with that token, login again'
  369. });
  370. } else if (userL) {
  371. userModel.findOne({
  372. _id: req.params.userid,
  373. likes: {
  374. '$ne': userL._id
  375. }
  376. })
  377. .exec(function(err, user) {
  378. if (err) return res.send(500, err.message);
  379. if (!user) {
  380. res.json({
  381. success: false,
  382. message: 'Like not posible, user not exist, or like was already done'
  383. });
  384. } else if (user) {
  385. //res.status(200).jsonp(user);
  386. var notification = new notificationModel({
  387. concept: "like",
  388. message: "user " + userL.username + " adds a like to you",
  389. date: new Date(),
  390. icon: 'ion-heart',
  391. link: "users/" + user._id,
  392. user: user._id
  393. });
  394. notification.save(function(err, notification) {
  395. if (err) return res.send(500, err.message);
  396. user.likes.push(userL._id);
  397. user.notifications.push(notification._id);
  398. user.save(function(err, user) {
  399. if (err) return res.send(500, err.message);
  400. exports.getUserById(req, res);
  401. });
  402. });
  403. } //end of else if user
  404. });
  405. } //end of else if userL
  406. });
  407. };
  408. exports.unlikeUser = function(req, res) {
  409. userModel.findOne({
  410. 'token': req.headers['x-access-token']
  411. })
  412. .exec(function(err, userL) {
  413. if (err) return res.send(500, err.message);
  414. if (!userL) {
  415. res.json({
  416. success: false,
  417. message: 'no user with that token, login again'
  418. });
  419. } else if (userL) {
  420. userModel.findOne({
  421. _id: req.params.userid,
  422. likes: userL._id
  423. })
  424. .exec(function(err, user) {
  425. if (err) return res.send(500, err.message);
  426. if (!user) {
  427. res.json({
  428. success: false,
  429. message: 'Unlike not posible'
  430. });
  431. } else if (user) {
  432. //res.status(200).jsonp(user);
  433. var notification = new notificationModel({
  434. concept: "like",
  435. message: "user " + userL.username + " removes like on you",
  436. date: new Date(),
  437. icon: 'ion-heart-broken',
  438. link: "users/" + user._id,
  439. user: user._id
  440. });
  441. notification.save(function(err, notification) {
  442. if (err) return res.send(500, err.message);
  443. var indexOf = user.likes.indexOf(userL._id);
  444. user.likes.splice(indexOf, 1);
  445. user.notifications.push(notification._id);
  446. user.save(function(err, user) {
  447. if (err) return res.send(500, err.message);
  448. exports.getUserById(req, res);
  449. });
  450. });
  451. } //end of else if user
  452. });
  453. } //end of else if userL
  454. });
  455. };
  456. /* fav */
  457. exports.addFav = function(req, res) {
  458. var tokenuser;
  459. userModel.find({
  460. token: req.headers['x-access-token']
  461. }, function(err, users) {
  462. tokenuser = users[0];
  463. });
  464. userModel.findById(req.params.userId, function(err, user) {
  465. // first search if user have already said like
  466. var favRepeated = false;
  467. for (var i = 0; i < user.favs.length; i++) {
  468. if (user.favs[i].username == tokenuser.username) {
  469. favRepeated = true;
  470. }
  471. }
  472. console.log("favRepeated: " + favRepeated);
  473. if (favRepeated == false) {
  474. //fav
  475. var fav = {
  476. userId: tokenuser._id,
  477. username: tokenuser.username,
  478. avatar: tokenuser.avatar
  479. };
  480. user.favs.push(fav);
  481. //notification
  482. var notification = {
  483. concept: "like",
  484. otherusername: tokenuser.username,
  485. description: "user " + tokenuser.username + " favs you",
  486. date: new Date(),
  487. link: "",
  488. user: user._id
  489. };
  490. user.notifications.push(notification);
  491. user.save(function(err, user) {
  492. if (err) return res.send(500, err.message);
  493. //once saved, send the users json to client
  494. userModel.find(function(err, users) {
  495. if (err) res.send(500, err.message);
  496. res.status(200).jsonp(users);
  497. });
  498. });
  499. } else {
  500. userModel.find(function(err, users) {
  501. if (err) res.send(500, err.message);
  502. res.status(200).jsonp(users);
  503. });
  504. }
  505. });
  506. };
  507. exports.doUnfav = function(req, res) {
  508. var tokenuser;
  509. userModel.find({
  510. token: req.headers['x-access-token']
  511. }, function(err, users) {
  512. tokenuser = users[0];
  513. });
  514. userModel.findById(req.params.userId, function(err, user) {
  515. for (var i = 0; i < user.favs.length; i++) {
  516. if (user.favs[i].username == tokenuser.username) {
  517. user.favs.splice(i, 1);
  518. }
  519. }
  520. user.save(function(err, travel) {
  521. if (err) return res.send(500, err.message);
  522. //res.status(200).jsonp(travel);
  523. userModel.find(function(err, users) {
  524. if (err) res.send(500, err.message);
  525. res.status(200).jsonp(users);
  526. });
  527. });
  528. });
  529. };
  530. exports.changePassword = function(req, res) {
  531. console.log(req.body);
  532. userModel.findOne({
  533. 'token': req.headers['x-access-token'],
  534. 'password': crypto.createHash('sha256').update(req.body.old).digest('base64')
  535. })
  536. .exec(function(err, user) {
  537. if (err) return res.send(500, err.message);
  538. if (!user) {
  539. res.json({
  540. success: false,
  541. message: 'User not found.'
  542. });
  543. } else if (user) {
  544. if (req.body.new1 != req.body.new2) {
  545. res.json({
  546. success: false,
  547. message: 'New passwords not match'
  548. });
  549. }else{
  550. user.password = crypto.createHash('sha256').update(req.body.new1).digest('base64');
  551. user.save(function(err, user) {
  552. if (err) return res.send(500, err.message);
  553. exports.getUserByToken(req, res);
  554. });
  555. }
  556. }
  557. });
  558. };