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.

378 lines
12 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. /* */
  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. //POST - Insert a new User in the DB
  15. exports.signup = function(req, res) {
  16. var user = new userModel({
  17. username: req.body.username,
  18. password: crypto.createHash('sha256').update(req.body.password).digest('base64'),
  19. description: req.body.description,
  20. avatar: req.body.avatar,
  21. email: req.body.email,
  22. phone: req.body.phone,
  23. telegram: req.body.telegram
  24. });
  25. if (user.username == undefined) {
  26. return res.status(500).jsonp("empty inputs");
  27. } else if (user.password == undefined) {
  28. return res.status(500).jsonp("empty inputs");
  29. } else if (user.email == undefined) {
  30. return res.status(500).jsonp("empty inputs");
  31. }
  32. user.save(function(err, user) {
  33. if (err) return res.send(500, err.message);
  34. exports.login(req, res);
  35. });
  36. };
  37. //POST - auth user
  38. exports.login = function(req, res) {
  39. // find the user
  40. userModel.findOne({
  41. username: req.body.username
  42. })
  43. .select('+password')
  44. .exec(function(err, user) {
  45. if (err) throw err;
  46. if (!user) {
  47. res.json({
  48. success: false,
  49. message: 'Authentication failed. User not found.'
  50. });
  51. } else if (user) {
  52. req.body.password = crypto.createHash('sha256').update(req.body.password).digest('base64');
  53. // check if password matches
  54. if (user.password != req.body.password) {
  55. res.json({
  56. success: false,
  57. message: 'Authentication failed. Wrong password.'
  58. });
  59. } else {
  60. // if user is found and password is right
  61. // create a token
  62. var token = jwt.sign({foo: 'bar'}, app.get('superSecret'), {
  63. //expiresInMinutes: 1440 // expires in 24 hours
  64. //expiresIn: '60m'
  65. });
  66. user.token = token;
  67. user.save(function(err, user) {
  68. if (err) return res.send(500, err.message);
  69. //res.status(200).jsonp(travel);
  70. console.log(user);
  71. // return the information including token as JSON
  72. user.password = "";
  73. res.json({
  74. success: true,
  75. message: 'Enjoy your token!',
  76. token: token,
  77. user: user
  78. });
  79. });
  80. }
  81. }
  82. });
  83. };
  84. //GET - Return all Users in the DB
  85. exports.getAllUsers = function(req, res) {
  86. userModel.find()
  87. .limit(Number(req.query.pageSize))
  88. .skip(Number(req.query.pageSize) * Number(req.query.page))
  89. .exec(function (err, users) {
  90. if (err) return res.send(500, err.message);
  91. res.status(200).jsonp(users);
  92. });
  93. };
  94. exports.getUserById = function (req, res) {
  95. userModel.findOne({_id: req.params.userid})
  96. .lean()
  97. .populate('travels', 'title from to date type')
  98. .exec(function (err, user) {
  99. if (err) return res.send(500, err.message);
  100. if (!user) {
  101. res.json({success: false, message: 'User not found.'});
  102. } else if (user) {
  103. res.status(200).jsonp(user);
  104. }
  105. });
  106. };
  107. exports.getUserByToken = function (req, res) {
  108. userModel.findOne({'token': req.headers['x-access-token']})
  109. .lean()
  110. .populate('travels', 'title from to date')
  111. .exec(function (err, user) {
  112. if (err) return res.send(500, err.message);
  113. if (!user) {
  114. res.json({success: false, message: 'User not found.'});
  115. } else if (user) {
  116. res.status(200).jsonp(user);
  117. }
  118. });
  119. };
  120. exports.getTravelsByUserId = function (req, res) {
  121. travelModel.find(
  122. {
  123. user: req.params.userid
  124. }
  125. )
  126. .lean()
  127. .exec(function (err, travels) {
  128. if (err) return res.send(500, err.message);
  129. travelModel.find(
  130. {
  131. joins: req.params.userid
  132. }
  133. )
  134. .lean()
  135. .exec(function (err, joins) {
  136. if (err) return res.send(500, err.message);
  137. res.json({
  138. travels: travels,
  139. joins: joins
  140. });
  141. });
  142. });
  143. };
  144. exports.getUserLikes = function (req, res) {
  145. userModel.findOne({_id: req.params.userid})
  146. .lean()
  147. .populate('likes', 'username avatar description')
  148. .exec(function (err, user) {
  149. if (err) return res.send(500, err.message);
  150. if (!user) {
  151. res.json({success: false, message: 'User not found.'});
  152. } else if (user) {
  153. res.status(200).jsonp(user.likes);
  154. }
  155. });
  156. };
  157. exports.getNotifications = function (req, res) {
  158. userModel.findOne({'token': req.headers['x-access-token']})
  159. .lean()
  160. .populate('notifications')
  161. .exec(function (err, user) {
  162. if (err) return res.send(500, err.message);
  163. if (!user) {
  164. res.json({success: false, message: 'User not found.'});
  165. } else if (user) {
  166. res.status(200).jsonp(user.notifications);
  167. }
  168. });
  169. };
  170. exports.updateUser = function (req, res) {
  171. userModel.update({'token': req.headers['x-access-token']}, req.body,
  172. function (err) {
  173. if (err) return console.log(err);
  174. exports.getUserByToken(req, res);
  175. });
  176. };
  177. //DELETE - Delete a user with specified ID
  178. exports.deleteUser = function(req, res) {
  179. userModel.findOne({'token': req.headers['x-access-token']})
  180. .exec(function(err, user) {
  181. user.remove(function(err) {
  182. if (err) return res.send(500, err.message);
  183. res.status(200).jsonp("deleted");
  184. })
  185. });
  186. };
  187. exports.likeUser = function(req, res) {
  188. userModel.findOne({'token': req.headers['x-access-token']})
  189. .exec(function (err, userL) {
  190. if (err) return res.send(500, err.message);
  191. if (!userL) {
  192. res.json({success: false, message: 'no user with that token, login again'});
  193. } else if (userL) {
  194. userModel.findOne({
  195. _id: req.params.userid,
  196. likes: {'$ne': userL._id}
  197. })
  198. .exec(function (err, user) {
  199. if (err) return res.send(500, err.message);
  200. if (!user) {
  201. res.json({success: false, message: 'Like not posible, user not exist, or like was already done'});
  202. } else if (user) {
  203. //res.status(200).jsonp(user);
  204. var notification = new notificationModel({
  205. concept: "like",
  206. message: "user "+userL.username+" adds a like to you",
  207. date: new Date(),
  208. icon: 'like.png',
  209. link: "users/" + user._id
  210. });
  211. notification.save(function(err, notification) {
  212. if (err) return res.send(500, err.message);
  213. user.likes.push(userL._id);
  214. user.notifications.push(notification._id);
  215. user.save(function(err, user) {
  216. if (err) return res.send(500, err.message);
  217. exports.getUserById(req, res);
  218. });
  219. });
  220. }//end of else if user
  221. });
  222. }//end of else if userL
  223. });
  224. };
  225. exports.unlikeUser = function(req, res) {
  226. userModel.findOne({'token': req.headers['x-access-token']})
  227. .exec(function (err, userL) {
  228. if (err) return res.send(500, err.message);
  229. if (!userL) {
  230. res.json({success: false, message: 'no user with that token, login again'});
  231. } else if (userL) {
  232. userModel.findOne({
  233. _id: req.params.userid,
  234. likes: userL._id
  235. })
  236. .exec(function (err, user) {
  237. if (err) return res.send(500, err.message);
  238. if (!user) {
  239. res.json({success: false, message: 'Unlike not posible'});
  240. } else if (user) {
  241. //res.status(200).jsonp(user);
  242. var notification = new notificationModel({
  243. concept: "like",
  244. message: "user "+userL.username+" removes like on you",
  245. date: new Date(),
  246. icon: 'like.png',
  247. link: "users/" + user._id
  248. });
  249. notification.save(function(err, notification) {
  250. if (err) return res.send(500, err.message);
  251. var indexOf= user.likes.indexOf(userL._id);
  252. user.likes.splice(indexOf, 1);
  253. user.notifications.push(notification._id);
  254. user.save(function(err, user) {
  255. if (err) return res.send(500, err.message);
  256. exports.getUserById(req, res);
  257. });
  258. });
  259. }//end of else if user
  260. });
  261. }//end of else if userL
  262. });
  263. };
  264. /* fav */
  265. exports.addFav = function(req, res) {
  266. var tokenuser;
  267. userModel.find({
  268. token: req.headers['x-access-token']
  269. }, function(err, users) {
  270. tokenuser = users[0];
  271. });
  272. userModel.findById(req.params.userId, function(err, user) {
  273. // first search if user have already said like
  274. var favRepeated = false;
  275. for (var i = 0; i < user.favs.length; i++) {
  276. if (user.favs[i].username == tokenuser.username) {
  277. favRepeated = true;
  278. }
  279. }
  280. console.log("favRepeated: " + favRepeated);
  281. if (favRepeated == false) {
  282. //fav
  283. var fav = {
  284. userId: tokenuser._id,
  285. username: tokenuser.username,
  286. avatar: tokenuser.avatar
  287. };
  288. user.favs.push(fav);
  289. //notification
  290. var notification = {
  291. concept: "like",
  292. otherusername: tokenuser.username,
  293. description: "user " + tokenuser.username + " favs you",
  294. date: new Date(),
  295. link: ""
  296. };
  297. user.notifications.push(notification);
  298. user.save(function(err, user) {
  299. if (err) return res.send(500, err.message);
  300. //once saved, send the users json to client
  301. userModel.find(function(err, users) {
  302. if (err) res.send(500, err.message);
  303. res.status(200).jsonp(users);
  304. });
  305. });
  306. } else {
  307. userModel.find(function(err, users) {
  308. if (err) res.send(500, err.message);
  309. res.status(200).jsonp(users);
  310. });
  311. }
  312. });
  313. };
  314. exports.doUnfav = function(req, res) {
  315. var tokenuser;
  316. userModel.find({
  317. token: req.headers['x-access-token']
  318. }, function(err, users) {
  319. tokenuser = users[0];
  320. });
  321. userModel.findById(req.params.userId, function(err, user) {
  322. for (var i = 0; i < user.favs.length; i++) {
  323. if (user.favs[i].username == tokenuser.username) {
  324. user.favs.splice(i, 1);
  325. }
  326. }
  327. user.save(function(err, travel) {
  328. if (err) return res.send(500, err.message);
  329. //res.status(200).jsonp(travel);
  330. userModel.find(function(err, users) {
  331. if (err) res.send(500, err.message);
  332. res.status(200).jsonp(users);
  333. });
  334. });
  335. });
  336. };