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
20 KiB

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