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.

573 lines
19 KiB

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