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.

586 lines
19 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('travels', 'title from to date type')
  150. .exec(function(err, user) {
  151. if (err) return res.send(500, err.message);
  152. if (!user) {
  153. res.json({
  154. success: false,
  155. message: 'User not found.'
  156. });
  157. } else if (user) {
  158. res.status(200).jsonp(user);
  159. }
  160. });
  161. };
  162. exports.getUserByToken = function(req, res) {
  163. userModel.findOne({
  164. 'token': req.headers['x-access-token']
  165. })
  166. .lean()
  167. .populate('travels', 'title from to date')
  168. .exec(function(err, user) {
  169. if (err) return res.send(500, err.message);
  170. if (!user) {
  171. res.json({
  172. success: false,
  173. message: 'User not found.'
  174. });
  175. } else if (user) {
  176. res.status(200).jsonp(user);
  177. }
  178. });
  179. };
  180. exports.getTravelsByUserId = function(req, res) {
  181. travelModel.find({
  182. user: req.params.userid
  183. })
  184. .lean()
  185. .exec(function(err, travels) {
  186. if (err) return res.send(500, err.message);
  187. travelModel.find({
  188. joins: req.params.userid
  189. })
  190. .lean()
  191. .exec(function(err, joins) {
  192. if (err) return res.send(500, err.message);
  193. res.json({
  194. travels: travels,
  195. joins: joins
  196. });
  197. });
  198. });
  199. };
  200. exports.getUserLikes = function(req, res) {
  201. userModel.findOne({
  202. _id: req.params.userid
  203. })
  204. .lean()
  205. .populate('likes', 'username avatar description')
  206. .exec(function(err, user) {
  207. if (err) return res.send(500, err.message);
  208. if (!user) {
  209. res.json({
  210. success: false,
  211. message: 'User not found.'
  212. });
  213. } else if (user) {
  214. res.status(200).jsonp(user.likes);
  215. }
  216. });
  217. };
  218. exports.getNumNotificationsByToken = function(req, res) {
  219. userModel.findOne({
  220. 'token': req.headers['x-access-token']
  221. })
  222. .lean()
  223. .exec(function(err, user) {
  224. if (err) return res.send(500, err.message);
  225. if (!user) {
  226. res.json({
  227. success: false,
  228. message: 'User not found.'
  229. });
  230. } else if (user) {
  231. res.status(200).jsonp(user.notifications);
  232. }
  233. });
  234. };
  235. exports.getNotifications = function(req, res) {
  236. userModel.findOne({
  237. 'token': req.headers['x-access-token']
  238. })
  239. .lean()
  240. .populate('notifications')
  241. .exec(function(err, user) {
  242. if (err) return res.send(500, err.message);
  243. if (!user) {
  244. res.json({
  245. success: false,
  246. message: 'User not found.'
  247. });
  248. } else if (user) {
  249. notificationModel.find({
  250. 'user': user._id,
  251. 'state': 'pendent'
  252. })
  253. .lean()
  254. .exec(function(err, notifications) {
  255. if (err) return res.send(500, err.message);
  256. if (!notifications) {
  257. res.json({
  258. success: false,
  259. message: 'No pendent notifications.'
  260. });
  261. } else if (notifications) {
  262. //here, maybe in the future is better delete the viewed notifications
  263. notificationModel.update({
  264. state: "pendent"
  265. }, {
  266. state: "viewed"
  267. }, {
  268. multi: true
  269. },
  270. function(err) {
  271. if (err) {
  272. console.log(err);
  273. }
  274. }
  275. );
  276. res.status(200).jsonp(notifications);
  277. }
  278. });
  279. //now, clean notifications count from user
  280. userModel.update({
  281. 'token': req.headers['x-access-token']
  282. }, {
  283. notifications: []
  284. },
  285. function(err) {
  286. if (err) {
  287. console.log(err);
  288. }
  289. }
  290. );
  291. }
  292. });
  293. };
  294. function getRandomInt(min, max) {
  295. min = Math.ceil(min);
  296. max = Math.floor(max);
  297. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  298. }
  299. function postImage(req, res, filename, fileImg) {
  300. url = "http://127.0.0.1:3050/image";
  301. var importFile = function(fileImg) {
  302. var decodedFile = new Buffer(fileImg, 'base64');
  303. var r = request.post(url, function(err, httpResponse, body) {
  304. if (err) {
  305. console.log(err);
  306. }
  307. //console.log(body);
  308. updateUserWithNewImages(req, res, body);
  309. });
  310. var form = r.form();
  311. form.append('file', decodedFile, {
  312. filename: filename + '.png'
  313. });
  314. }
  315. importFile(fileImg);
  316. }
  317. function updateUserWithNewImages(req, res, imgUrl) {
  318. //adding random number to the url, to force ionic reload the image
  319. req.body.avatar = imgUrl + "?" + getRandomInt(1, 9999);
  320. userModel.update({
  321. 'token': req.headers['x-access-token']
  322. }, req.body,
  323. function(err) {
  324. if (err) return console.log(err);
  325. exports.getUserByToken(req, res);
  326. });
  327. }
  328. exports.updateUser = function(req, res) {
  329. if (req.body.newAvatar) {
  330. urlImg = postImage(req, res, "avatar_" + req.body.username, req.body.newAvatar);
  331. }
  332. /*if (req.body.newFaircoin) {
  333. urlImg = postImage(req, res, "fairdir_"+req.body.username,req.body.newFaircoin);
  334. }*/
  335. if (!req.body.newAvatar) {
  336. updateUserWithNewImages(req, res, req.body.avatar);
  337. }
  338. /*userModel.update({
  339. 'token': req.headers['x-access-token']
  340. }, req.body,
  341. function(err) {
  342. if (err) return console.log(err);
  343. exports.getUserByToken(req, res);
  344. });*/
  345. };
  346. //DELETE - Delete a user with specified ID
  347. exports.deleteUser = function(req, res) {
  348. userModel.findOne({
  349. 'token': req.headers['x-access-token']
  350. })
  351. .exec(function(err, user) {
  352. user.remove(function(err) {
  353. if (err) return res.send(500, err.message);
  354. res.status(200).jsonp("deleted");
  355. })
  356. });
  357. };
  358. exports.likeUser = function(req, res) {
  359. userModel.findOne({
  360. 'token': req.headers['x-access-token']
  361. })
  362. .exec(function(err, userL) {
  363. if (err) return res.send(500, err.message);
  364. if (!userL) {
  365. res.json({
  366. success: false,
  367. message: 'no user with that token, login again'
  368. });
  369. } else if (userL) {
  370. userModel.findOne({
  371. _id: req.params.userid,
  372. likes: {
  373. '$ne': userL._id
  374. }
  375. })
  376. .exec(function(err, user) {
  377. if (err) return res.send(500, err.message);
  378. if (!user) {
  379. res.json({
  380. success: false,
  381. message: 'Like not posible, user not exist, or like was already done'
  382. });
  383. } else if (user) {
  384. //res.status(200).jsonp(user);
  385. var notification = new notificationModel({
  386. concept: "like",
  387. message: "user " + userL.username + " adds a like to you",
  388. date: new Date(),
  389. icon: 'ion-heart',
  390. link: "users/" + user._id,
  391. user: user._id
  392. });
  393. notification.save(function(err, notification) {
  394. if (err) return res.send(500, err.message);
  395. user.likes.push(userL._id);
  396. user.notifications.push(notification._id);
  397. user.save(function(err, user) {
  398. if (err) return res.send(500, err.message);
  399. exports.getUserById(req, res);
  400. });
  401. });
  402. } //end of else if user
  403. });
  404. } //end of else if userL
  405. });
  406. };
  407. exports.unlikeUser = function(req, res) {
  408. userModel.findOne({
  409. 'token': req.headers['x-access-token']
  410. })
  411. .exec(function(err, userL) {
  412. if (err) return res.send(500, err.message);
  413. if (!userL) {
  414. res.json({
  415. success: false,
  416. message: 'no user with that token, login again'
  417. });
  418. } else if (userL) {
  419. userModel.findOne({
  420. _id: req.params.userid,
  421. likes: userL._id
  422. })
  423. .exec(function(err, user) {
  424. if (err) return res.send(500, err.message);
  425. if (!user) {
  426. res.json({
  427. success: false,
  428. message: 'Unlike not posible'
  429. });
  430. } else if (user) {
  431. //res.status(200).jsonp(user);
  432. var notification = new notificationModel({
  433. concept: "like",
  434. message: "user " + userL.username + " removes like on you",
  435. date: new Date(),
  436. icon: 'ion-heart-broken',
  437. link: "users/" + user._id,
  438. user: user._id
  439. });
  440. notification.save(function(err, notification) {
  441. if (err) return res.send(500, err.message);
  442. var indexOf = user.likes.indexOf(userL._id);
  443. user.likes.splice(indexOf, 1);
  444. user.notifications.push(notification._id);
  445. user.save(function(err, user) {
  446. if (err) return res.send(500, err.message);
  447. exports.getUserById(req, res);
  448. });
  449. });
  450. } //end of else if user
  451. });
  452. } //end of else if userL
  453. });
  454. };
  455. /* fav */
  456. exports.addFav = function(req, res) {
  457. var tokenuser;
  458. userModel.find({
  459. token: req.headers['x-access-token']
  460. }, function(err, users) {
  461. tokenuser = users[0];
  462. });
  463. userModel.findById(req.params.userId, function(err, user) {
  464. // first search if user have already said like
  465. var favRepeated = false;
  466. for (var i = 0; i < user.favs.length; i++) {
  467. if (user.favs[i].username == tokenuser.username) {
  468. favRepeated = true;
  469. }
  470. }
  471. console.log("favRepeated: " + favRepeated);
  472. if (favRepeated == false) {
  473. //fav
  474. var fav = {
  475. userId: tokenuser._id,
  476. username: tokenuser.username,
  477. avatar: tokenuser.avatar
  478. };
  479. user.favs.push(fav);
  480. //notification
  481. var notification = {
  482. concept: "like",
  483. otherusername: tokenuser.username,
  484. description: "user " + tokenuser.username + " favs you",
  485. date: new Date(),
  486. link: "",
  487. user: user._id
  488. };
  489. user.notifications.push(notification);
  490. user.save(function(err, user) {
  491. if (err) return res.send(500, err.message);
  492. //once saved, send the users json to client
  493. userModel.find(function(err, users) {
  494. if (err) res.send(500, err.message);
  495. res.status(200).jsonp(users);
  496. });
  497. });
  498. } else {
  499. userModel.find(function(err, users) {
  500. if (err) res.send(500, err.message);
  501. res.status(200).jsonp(users);
  502. });
  503. }
  504. });
  505. };
  506. exports.doUnfav = function(req, res) {
  507. var tokenuser;
  508. userModel.find({
  509. token: req.headers['x-access-token']
  510. }, function(err, users) {
  511. tokenuser = users[0];
  512. });
  513. userModel.findById(req.params.userId, function(err, user) {
  514. for (var i = 0; i < user.favs.length; i++) {
  515. if (user.favs[i].username == tokenuser.username) {
  516. user.favs.splice(i, 1);
  517. }
  518. }
  519. user.save(function(err, travel) {
  520. if (err) return res.send(500, err.message);
  521. //res.status(200).jsonp(travel);
  522. userModel.find(function(err, users) {
  523. if (err) res.send(500, err.message);
  524. res.status(200).jsonp(users);
  525. });
  526. });
  527. });
  528. };
  529. exports.changePassword = function(req, res) {
  530. //if(req.body.)
  531. userModel.update({
  532. 'token': req.headers['x-access-token']
  533. }, req.body,
  534. function(err) {
  535. if (err) return console.log(err);
  536. exports.getUserByToken(req, res);
  537. });
  538. };