Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var async = require('async'),
- nodemailer = require('nodemailer'),
- _ = require('lodash'),
- model = app.model,
- hash = app.security.hash,
- validate = app.validation.validate;
- /**
- * the mobile api should validate a token session from the mobile app
- * @param router
- * @returns {*}
- */
- module.exports = router => {
- router.get('/ping', (req, res, next) => {
- model.MobileAppVersion.findOne({}, {_id: 0}).exec().then(
- mobileAppVersion => res.send(mobileAppVersion),
- err => next(Error.create('An error occurred trying to get the mobile app version.', {}, err))
- );
- });
- function authenticate(req, res, next) {
- var header = req.get('Authorization');
- if (!header) {
- return res.sendStatus(401);
- }
- var token = header.split(/\s+/).pop();
- if (!token) {
- return res.sendStatus(401);
- }
- var auth = new Buffer(token, 'base64').toString().split(/:/);
- if (!auth.length) {
- return res.sendStatus(401);
- }
- model.User.findOne({
- _id: auth[0],
- password: auth[1],
- disabled: {$ne: true},
- mobile: true
- }).exec().then(
- user => {
- if (!user) {
- return res.sendStatus(401);
- }
- req.user = user;
- next();
- },
- err => next(Error.create('An error occurred trying to authenticate the mobile user.', {_id: auth[0]}, err))
- );
- }
- router.post('/sign-in', (req, res, next) => {
- var missingFields = validate.required(req.body, ['username', 'password']);
- if (missingFields.length) {
- return res.status(400).send(missingFields);
- }
- console.log(req.body.username, hash(req.body.password));
- model.User.findOne({
- _id: req.body.username,
- password: hash(req.body.password),
- disabled: {$ne: true},
- mobile: true
- }, {password: 1}).exec().then(
- user => {
- if (!user) {
- return res.sendStatus(403);
- }
- res.send(user);
- },
- err => next(Error.create('An error occurred trying to authenticate the mobile user.', {_id: req.body.username}, err))
- );
- });
- router.post('/sync', authenticate, (req, res, next) => {
- if (!req.user.demo) {
- next();
- }
- }, (req, res, next) => {
- req.syncLog = new model.SyncLog({
- user: req.user._id,
- received: 0
- });
- // receive new data
- var surveys = req.body.surveys;
- if (!surveys || !surveys.length) {
- return next();
- }
- _.forEach(surveys, survey => {
- delete survey._id;
- survey.pollster = req.user._id;
- });
- req.syncLog.received = surveys.length;
- model.Survey.collection.insert(surveys).then(
- () => next(),
- err => next(Error.create('An error occurred trying to save the surveys.', {idUser: req.user._id}, err))
- );
- }, (req, res, next)=> {
- var counters = _.map(req.body.surveysCounters || [], (counter, date) => ({
- user: req.user._id,
- date: new Date(date),
- surveysCompleted: counter.surveysCompleted,
- noAnswers: counter.noAnswers,
- partialResponse: counter.partialResponse
- }));
- if (!counters.length) {
- return next();
- }
- model.SurveyCounter.collection.insert(counters).then(
- () => next(),
- err => next(Error.create('An error occurred trying to save the survey counters.', {idUser: req.user._id}, err))
- );
- }, (req, res, next)=> {
- Promise.all(
- // Save all people counters of the user.
- _.map(req.body.peopleCounters || [],
- (counter, date) => model.PeopleCounter.update(
- {user: req.user._id, date: new Date(date)},
- {
- $inc: {
- residents: counter.residents,
- inTransit: counter.inTransit,
- noResidents: counter.noResidents,
- nonresidentsNotLeaveTheCountry: counter.nonresidentsNotLeaveTheCountry,
- residentNotReturningToTheCountry: counter.residentNotReturningToTheCountry
- }
- },
- {upsert: true})
- )
- ).then(
- () => next(),
- err => next(Error.create('An error occurred trying to save the people counters.', {idUser: req.user._id}, err))
- );
- }, (req, res, next) => {
- req.syncLog.save().then(
- () => {
- res.end();
- notifyWatchers(req.user);
- },
- err => next(Error.create('An error occurred trying to save the SyncLog.', {
- idUser: req.user._id,
- syncLog: req.syncLog
- }, err))
- );
- });
- function notifyWatchers(user) {
- return user.populate('watchers').exec().then(
- user => {
- if (!user.watchers || !user.watchers.length) {
- return;
- }
- return new Promise((resolve, reject) => {
- nodemailer.createTransport(app.config.email).sendMail({
- from: 'ETI <eti-contacto@indec.mecon.gov.ar>',
- bcc: _.pluck(user.watchers, 'email'),
- subject: '[ETI] Aviso de Sincronización',
- 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>`
- }, err => {
- if (err) {
- return reject(err);
- }
- resolve();
- });
- });
- },
- err => {
- console.log(err);
- return err;
- });
- }
- router.post('/messages', authenticate, (req, res, next) => {
- var query = {};
- if (req.body.last) {
- query.createdAt = {$gt: new Date(req.body.last)};
- }
- model.Message.find(query).sort({createdAt: -1}).limit(30).sort({createdAt: 1}).exec().then(
- messages => res.send(messages),
- err => next(Error.create('An error occurred trying to fetch the messages.', {}, err))
- );
- });
- router.post('/messages/new', authenticate, (req, res, next) => {
- var message = model.Message({
- sender: req.user._id,
- senderName: `${req.user.name} ${req.user.surname}`,
- text: req.body.text
- });
- message.save().then(
- () => res.sendStatus(200),
- err => next(Error.create('An error occurred trying to save the mobile message.', {}, err))
- );
- });
- return router;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement