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.

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