Advertisement
Guest User

Untitled

a guest
Jan 27th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.05 KB | None | 0 0
  1. var async = require('async'),
  2. nodemailer = require('nodemailer'),
  3. _ = require('lodash'),
  4. model = app.model,
  5. hash = app.security.hash,
  6. validate = app.validation.validate;
  7.  
  8. /**
  9. * the mobile api should validate a token session from the mobile app
  10. * @param router
  11. * @returns {*}
  12. */
  13. module.exports = router => {
  14. router.get('/ping', (req, res, next) => {
  15. model.MobileAppVersion.findOne({}, {_id: 0}).exec().then(
  16. mobileAppVersion => res.send(mobileAppVersion),
  17. err => next(Error.create('An error occurred trying to get the mobile app version.', {}, err))
  18. );
  19. });
  20.  
  21. function authenticate(req, res, next) {
  22. var header = req.get('Authorization');
  23. if (!header) {
  24. return res.sendStatus(401);
  25. }
  26. var token = header.split(/\s+/).pop();
  27. if (!token) {
  28. return res.sendStatus(401);
  29. }
  30. var auth = new Buffer(token, 'base64').toString().split(/:/);
  31. if (!auth.length) {
  32. return res.sendStatus(401);
  33. }
  34. model.User.findOne({
  35. _id: auth[0],
  36. password: auth[1],
  37. disabled: {$ne: true},
  38. mobile: true
  39. }).exec().then(
  40. user => {
  41. if (!user) {
  42. return res.sendStatus(401);
  43. }
  44. req.user = user;
  45. next();
  46. },
  47. err => next(Error.create('An error occurred trying to authenticate the mobile user.', {_id: auth[0]}, err))
  48. );
  49. }
  50.  
  51. router.post('/sign-in', (req, res, next) => {
  52. var missingFields = validate.required(req.body, ['username', 'password']);
  53. if (missingFields.length) {
  54. return res.status(400).send(missingFields);
  55. }
  56. console.log(req.body.username, hash(req.body.password));
  57. model.User.findOne({
  58. _id: req.body.username,
  59. password: hash(req.body.password),
  60. disabled: {$ne: true},
  61. mobile: true
  62. }, {password: 1}).exec().then(
  63. user => {
  64. if (!user) {
  65. return res.sendStatus(403);
  66. }
  67. res.send(user);
  68. },
  69. err => next(Error.create('An error occurred trying to authenticate the mobile user.', {_id: req.body.username}, err))
  70. );
  71.  
  72. });
  73.  
  74. router.post('/sync', authenticate, (req, res, next) => {
  75. if (!req.user.demo) {
  76. next();
  77. }
  78. }, (req, res, next) => {
  79. req.syncLog = new model.SyncLog({
  80. user: req.user._id,
  81. received: 0
  82. });
  83. // receive new data
  84. var surveys = req.body.surveys;
  85. if (!surveys || !surveys.length) {
  86. return next();
  87. }
  88. _.forEach(surveys, survey => {
  89. delete survey._id;
  90. survey.pollster = req.user._id;
  91. });
  92. req.syncLog.received = surveys.length;
  93. model.Survey.collection.insert(surveys).then(
  94. () => next(),
  95. err => next(Error.create('An error occurred trying to save the surveys.', {idUser: req.user._id}, err))
  96. );
  97. }, (req, res, next)=> {
  98. var counters = _.map(req.body.surveysCounters || [], (counter, date) => ({
  99. user: req.user._id,
  100. date: new Date(date),
  101. surveysCompleted: counter.surveysCompleted,
  102. noAnswers: counter.noAnswers,
  103. partialResponse: counter.partialResponse
  104. }));
  105. if (!counters.length) {
  106. return next();
  107. }
  108. model.SurveyCounter.collection.insert(counters).then(
  109. () => next(),
  110. err => next(Error.create('An error occurred trying to save the survey counters.', {idUser: req.user._id}, err))
  111. );
  112. }, (req, res, next)=> {
  113. Promise.all(
  114. // Save all people counters of the user.
  115. _.map(req.body.peopleCounters || [],
  116. (counter, date) => model.PeopleCounter.update(
  117. {user: req.user._id, date: new Date(date)},
  118. {
  119. $inc: {
  120. residents: counter.residents,
  121. inTransit: counter.inTransit,
  122. noResidents: counter.noResidents,
  123. nonresidentsNotLeaveTheCountry: counter.nonresidentsNotLeaveTheCountry,
  124. residentNotReturningToTheCountry: counter.residentNotReturningToTheCountry
  125. }
  126. },
  127. {upsert: true})
  128. )
  129. ).then(
  130. () => next(),
  131. err => next(Error.create('An error occurred trying to save the people counters.', {idUser: req.user._id}, err))
  132. );
  133. }, (req, res, next) => {
  134. req.syncLog.save().then(
  135. () => {
  136. res.end();
  137. notifyWatchers(req.user);
  138. },
  139. err => next(Error.create('An error occurred trying to save the SyncLog.', {
  140. idUser: req.user._id,
  141. syncLog: req.syncLog
  142. }, err))
  143. );
  144. });
  145.  
  146. function notifyWatchers(user) {
  147. return user.populate('watchers').exec().then(
  148. user => {
  149. if (!user.watchers || !user.watchers.length) {
  150. return;
  151. }
  152. return new Promise((resolve, reject) => {
  153. nodemailer.createTransport(app.config.email).sendMail({
  154. from: 'ETI <eti-contacto@indec.mecon.gov.ar>',
  155. bcc: _.pluck(user.watchers, 'email'),
  156. subject: '[ETI] Aviso de Sincronización',
  157. html: `Hola,<br/><br/>Le informamos que <strong>${user.name} ${user.surname} (${user._id})</strong> ha sincronizado con el sistema.<br/><br/><small>Por favor no responda este mail, esta es una casilla automática.</small>`
  158. }, err => {
  159. if (err) {
  160. return reject(err);
  161. }
  162. resolve();
  163. });
  164. });
  165. },
  166. err => {
  167. console.log(err);
  168. return err;
  169. });
  170. }
  171.  
  172. router.post('/messages', authenticate, (req, res, next) => {
  173. var query = {};
  174. if (req.body.last) {
  175. query.createdAt = {$gt: new Date(req.body.last)};
  176. }
  177. model.Message.find(query).sort({createdAt: -1}).limit(30).sort({createdAt: 1}).exec().then(
  178. messages => res.send(messages),
  179. err => next(Error.create('An error occurred trying to fetch the messages.', {}, err))
  180. );
  181. });
  182.  
  183. router.post('/messages/new', authenticate, (req, res, next) => {
  184. var message = model.Message({
  185. sender: req.user._id,
  186. senderName: `${req.user.name} ${req.user.surname}`,
  187. text: req.body.text
  188. });
  189. message.save().then(
  190. () => res.sendStatus(200),
  191. err => next(Error.create('An error occurred trying to save the mobile message.', {}, err))
  192. );
  193. });
  194.  
  195. return router;
  196. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement