<commit_before>var fs = require('fs')
var _ = require('lodash')
var path = require('path')
var async = require('async')
var express = require('express')
var mongoose = require('mongoose')
var parser = require('body-parser')
var timestamp = require('timestamp')
var jsonschema = require('jsonschema')
var spawn = require('child_process').spawn
var debug = require('debug')('spikefinder')
var config = require('./config')
var evaluate = require('./evaluate')

var Result = require('./models/result')
var Submission = require('./models/submission')

mongoose.connect(config.db.uri)
mongoose.Promise = global.Promise

var start = function (opts) {
  opts = opts || {}
  var port = opts.port || 8080
  var app = express()
  app.use(express.static(path.join(__dirname, '../client')))
  app.use(parser.urlencoded({ extended: false }))
  app.use(parser.json({limit: '50mb'}))

  app.get('/api/results/', function (req, res) {
    Result.find({}, function (err, data) {
      return res.json(data)
    })
  })

  app.get('/api/submissions/', function (req, res) {
    Submission.find({}, function (err, data) {
      return res.json(data)
    })
  })

  app.post('/api/submit/', function (req, res) {
    var answers = req.body

    console.log('')
    debug('processing submission from ' + req.body.name)

    function checkFormat (next) {
      debug('checking format')
      if (!answers.contents || (answers.contents.length != 15))
        return next({stage: 'checking answers', error: 'invalid result format'})
      return next(null)
    }

    function computeResults (next) {
      debug('computing results')
      async.map(answers.contents, function (item, next) {
        evaluate(item.dataset, item.values, function (err, scores) {
          if (err) return next({stage: 'computing results', error: err})
          var reformatted = []
          _.forEach(scores, function (value, label) {
            reformatted.push({label: label, value: value})
          })
          var result = {
            dataset: item.dataset,
            scores: reformatted
          }
          return next(null, result)
        })
      }, function (err, results) {
        if (err) return next(err)
        return next(null, results)
      })
    }

    function sendResults (results, next) {
      debug('sending answers')
      var payload = {
        name: answers.name,
        contact: answers.contact,
        algorithm: answers.algorithm,
        repository: answers.repository,
        timestamp: timestamp(),
        contents: results
      }
      var result = new Result(payload)
      result.save(function (err, data) {
        if (err) return next({stage: 'sending results', error: err})
        return next(null)
      })
    }

    async.waterfall([
      checkFormat, computeResults, sendResults
    ], function (err) {
      if (err) {
        debug('failed and sending error message')
        if (err.stage === 'checking answers') return res.status(500).end(err.error)
        else if (err.stage === 'computing results') return res.status(500).end('failure evaulating, check your file!')
        else if (err.stage === 'sending results') return res.status(500).end('error posting')
        else return res.status(500).end('error parsing results')
      } else {
        debug('wrote result to db for ' + req.body.name)
        return res.status(200).end('submission succeeeded')
      }
    })
  })

  app.listen(port, function () {
    debug('serving on port ' + port)
  })
}

if (require.main === module) {
  start()
} else {
  module.exports = start
}
<commit_msg>increase size limit<commit_after>var fs = require('fs')
var _ = require('lodash')
var path = require('path')
var async = require('async')
var express = require('express')
var mongoose = require('mongoose')
var parser = require('body-parser')
var timestamp = require('timestamp')
var jsonschema = require('jsonschema')
var spawn = require('child_process').spawn
var debug = require('debug')('spikefinder')
var config = require('./config')
var evaluate = require('./evaluate')

var Result = require('./models/result')
var Submission = require('./models/submission')

mongoose.connect(config.db.uri)
mongoose.Promise = global.Promise

var start = function (opts) {
  opts = opts || {}
  var port = opts.port || 8080
  var app = express()
  app.use(express.static(path.join(__dirname, '../client')))
  app.use(parser.urlencoded({ extended: false }))
  app.use(parser.json({limit: '100mb'}))

  app.get('/api/results/', function (req, res) {
    Result.find({}, function (err, data) {
      return res.json(data)
    })
  })

  app.get('/api/submissions/', function (req, res) {
    Submission.find({}, function (err, data) {
      return res.json(data)
    })
  })

  app.post('/api/submit/', function (req, res) {
    var answers = req.body

    console.log('')
    debug('processing submission from ' + req.body.name)

    function checkFormat (next) {
      debug('checking format')
      if (!answers.contents || (answers.contents.length != 15))
        return next({stage: 'checking answers', error: 'invalid result format'})
      return next(null)
    }

    function computeResults (next) {
      debug('computing results')
      async.map(answers.contents, function (item, next) {
        evaluate(item.dataset, item.values, function (err, scores) {
          if (err) return next({stage: 'computing results', error: err})
          var reformatted = []
          _.forEach(scores, function (value, label) {
            reformatted.push({label: label, value: value})
          })
          var result = {
            dataset: item.dataset,
            scores: reformatted
          }
          return next(null, result)
        })
      }, function (err, results) {
        if (err) return next(err)
        return next(null, results)
      })
    }

    function sendResults (results, next) {
      debug('sending answers')
      var payload = {
        name: answers.name,
        contact: answers.contact,
        algorithm: answers.algorithm,
        repository: answers.repository,
        timestamp: timestamp(),
        contents: results
      }
      var result = new Result(payload)
      result.save(function (err, data) {
        if (err) return next({stage: 'sending results', error: err})
        return next(null)
      })
    }

    async.waterfall([
      checkFormat, computeResults, sendResults
    ], function (err) {
      if (err) {
        debug('failed and sending error message')
        if (err.stage === 'checking answers') return res.status(500).end(err.error)
        else if (err.stage === 'computing results') return res.status(500).end('failure evaulating, check your file!')
        else if (err.stage === 'sending results') return res.status(500).end('error posting')
        else return res.status(500).end('error parsing results')
      } else {
        debug('wrote result to db for ' + req.body.name)
        return res.status(200).end('submission succeeeded')
      }
    })
  })

  app.listen(port, function () {
    debug('serving on port ' + port)
  })
}

if (require.main === module) {
  start()
} else {
  module.exports = start
}
<|endoftext|>


<commit_before>var express = require('express'),
    http = require('http'),
    path = require('path'),
    config = require('./config'),
    log = require('./lib/log')(module),
    HttpError = require('./error').HttpError;

var app = express();

// all environments
app.set('port', process.env.PORT || config.get('port'));
var ENV = app.get('env');

if ('production' === ENV) {
  app.use(express.compress());
  app.use(express.static(path.join(__dirname, '../dist'), { maxAge: 86400000 }));
  app.use(express.logger('default'));
  app.set('views', path.join(__dirname, '../dist'));
} else {
  app.use(express.static(path.join(__dirname, '../client')));
  app.use(express.logger('dev'));
  app.set('views', path.join(__dirname, '../client'));
}

app.use(express.bodyParser());
app.use(express.cookieParser(config.get('cookieSecret')));
app.use(express.methodOverride());

var mongoose = require('./lib/mongoose');

if ('production' !== ENV) {
  mongoose.set('debug', true);
}

app.use(require('./middleware/sendHttpError'));
app.use(require('./middleware/checkDB'));

var mongoStore = require('./lib/mongoStore');
var store = mongoStore.createMongoStore(express, mongoose);

app.use(express.session({
  secret: config.get('session:secret'),
  key: config.get('session:key'),
  cookie: config.get('session:cookie'),
  store: store
}));

app.use(require('./middleware/loadUser'));
app.use(app.router);

require('./routes')(app);

app.use(appErrorHandler());

function appErrorHandler() {
  return function (err, req, res, next) {
    if (typeof err === 'number') {
      err = new HttpError(err);
    }
    if (err instanceof HttpError && res) {
      res.sendHttpError(err);
    } else {
      if (res) {
        log.error(err.message, err);
        err = new HttpError(500);
        res.sendHttpError(err);
      } else {
        log.error(err.stack);
      }
    }
  };
}

process.on('uncaughtException', function (err) {
  log.error('Uncaught Exception: ' + err.message);
  log.error(err.stack);
});

http.createServer(app).listen(app.get('port'), function () {
  log.info('Express server listening on port ' + app.get('port'));
});<commit_msg>Logger after static and views<commit_after>var express = require('express'),
    http = require('http'),
    path = require('path'),
    config = require('./config'),
    log = require('./lib/log')(module),
    HttpError = require('./error').HttpError;

var app = express();

// all environments
app.set('port', process.env.PORT || config.get('port'));
var ENV = app.get('env');

if ('production' === ENV) {
  app.use(express.compress());
  app.use(express.static(path.join(__dirname, '../dist'), { maxAge: 86400000 }));
  app.set('views', path.join(__dirname, '../dist'));
  app.use(express.logger('default'));
} else {
  app.use(express.static(path.join(__dirname, '../client')));
  app.set('views', path.join(__dirname, '../client'));
  app.use(express.logger('dev'));
}

app.use(express.bodyParser());
app.use(express.cookieParser(config.get('cookieSecret')));
app.use(express.methodOverride());

var mongoose = require('./lib/mongoose');

if ('production' !== ENV) {
  mongoose.set('debug', true);
}

app.use(require('./middleware/sendHttpError'));
app.use(require('./middleware/checkDB'));

var mongoStore = require('./lib/mongoStore');
var store = mongoStore.createMongoStore(express, mongoose);

app.use(express.session({
  secret: config.get('session:secret'),
  key: config.get('session:key'),
  cookie: config.get('session:cookie'),
  store: store
}));

app.use(require('./middleware/loadUser'));
app.use(app.router);

require('./routes')(app);

app.use(appErrorHandler());

function appErrorHandler() {
  return function (err, req, res, next) {
    if (typeof err === 'number') {
      err = new HttpError(err);
    }
    if (err instanceof HttpError && res) {
      res.sendHttpError(err);
    } else {
      if (res) {
        log.error(err.message, err);
        err = new HttpError(500);
        res.sendHttpError(err);
      } else {
        log.error(err.stack);
      }
    }
  };
}

process.on('uncaughtException', function (err) {
  log.error('Uncaught Exception: ' + err.message);
  log.error(err.stack);
});

http.createServer(app).listen(app.get('port'), function () {
  log.info('Express server listening on port ' + app.get('port'));
});<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>app.js file updated<commit_after>var express = require('express');
var routes = require('./routes');
var garage = require('./routes/garage');
var http = require('http');
var path = require('path');
var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

// home
app.get('/', routes.index);

// get all activities
app.get('/garage', garage.readAll);

// get activity by id
app.get('/garage/:garageID', garage.read);

// create activity
app.put('/garage', garage.create);

// update activity by id
app.post('/garage/:garageID', garage.update);

// delete activity by id
app.delete('/garage/:garageID', garage.delete);

http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>const logger = require('../log.js');
const expressWinston = require('express-winston');
const addRequestId = require('express-request-id')();
const moment = require('moment');

const bodyParser = require('body-parser');
const cookieSession = require('cookie-session');
const cookieParser = require('cookie-parser');
const express = require('express');
const path = require('path');
const flash = require('connect-flash');

const helmet = require('helmet');
const csurf = require('csurf');
const compression = require('compression');
const ensureHttps = require('./utils/ensureHttps');

const sassMiddleware = require('node-sass-middleware');

const config = require('../server/config');
const healthcheck = require('../server/healthcheck');

const passport = require('passport');
const auth = require('./authentication/auth');

const defaultRouter = require('../server/routes/default');
const signInRouter = require('./routes/signIn');

const adminRouter = require('../server/routes/admin/admin');
const apiRouter = require('../server/routes/api');
const caseListRouter = require('../server/routes/caseList');
const contactRouter = require('../server/routes/contact');
const pdfRouter = require('../server/routes/pdf');
const searchRouter = require('../server/routes/search');
const sendRouter = require('../server/routes/send');
const sentRouter = require('../server/routes/sent');
const taskListRouter = require('./routes/taskList');
const utilsRouter = require('../server/routes/utils');
const userRouter = require('../server/routes/user');

const standardRouter = require('./routes/routeWorkers/standardRouter');
const addressRouter = require('./routes/address');
const approvalRouter = require('./routes/approval');
const bassReferralRouter = require('./routes/bassReferral');
const conditionsRouter = require('./routes/conditions');
const curfewRouter = require('./routes/curfew');
const eligibilityRouter = require('./routes/eligibility');
const finalChecksRouter = require('./routes/finalChecks');
const reviewRouter = require('./routes/review');
const reportingRouter = require('./routes/reporting');
const riskRouter = require('./routes/risk');
const victimRouter = require('./routes/victim');
const varyRouter = require('./routes/vary');

const version = moment.now().toString();
const production = process.env.NODE_ENV === 'production';

module.exports = function createApp({
                                        signInService,
                                        licenceService,
                                        prisonerService,
                                        conditionsService,
                                        caseListService,
                                        pdfService,
                                        searchService,
                                        userAdminService,
                                        reportingService,
                                        notificationService,
                                        userService,
                                        audit
                                    }) {
    const app = express();

    auth.init(signInService, userService, audit, config.authStrategy);

    app.set('json spaces', 2);

    // Configure Express for running behind proxies
    // https://expressjs.com/en/guide/behind-proxies.html
    app.set('trust proxy', true);

    // View Engine Configuration
    app.set('views', path.join(__dirname, '../server/views'));
    app.set('view engine', 'pug');

    // Server Configuration
    app.set('port', process.env.PORT || 3000);

    // HACK: Azure doesn't support X-Forwarded-Proto so we add it manually
    // http://stackoverflow.com/a/18455265/173062
    app.use(function(req, res, next) {
        if (req.headers['x-arr-ssl'] && !req.headers['x-forwarded-proto']) {
            req.headers['x-forwarded-proto'] = 'https';
        }
        return next();
    });

    // Secure code best practice - see:
    // 1. https://expressjs.com/en/advanced/best-practice-security.html,
    // 2. https://www.npmjs.com/package/helmet
    app.use(helmet());

    app.use(addRequestId);

    app.use(cookieSession({
        name: 'session',
        keys: [config.sessionSecret],
        maxAge: 60 * 60 * 1000,
        secure: config.https,
        httpOnly: true,
        signed: true,
        overwrite: true,
        sameSite: 'lax'
    }));

    app.use(passport.initialize());
    app.use(passport.session());

    // Request Processing Configuration
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));

    if (config.enableTestUtils) {
        app.use('/utils/', utilsRouter());
    }

    app.use(cookieParser());
    app.use(csurf({cookie: {secure: config.https, httpOnly: true}}));

    // Resource Delivery Configuration
    app.use(compression());

    // Cachebusting version string
    if (production) {
        // Version only changes on reboot
        app.locals.version = version;
    } else {
        // Version changes every request
        app.use(function(req, res, next) {
            res.locals.version = moment.now().toString();
            return next();
        });
    }

    if (!production) {
        app.use('/public', sassMiddleware({
            src: path.join(__dirname, '../assets/sass'),
            dest: path.join(__dirname, '../assets/stylesheets'),
            debug: false,
            outputStyle: 'compressed',
            prefix: '/stylesheets/',
            includePaths: [
                'node_modules/govuk_frontend_toolkit/stylesheets',
                'node_modules/govuk_template_jinja/assets/stylesheets',
                'node_modules/govuk-elements-sass/public/sass'
            ]
        }));
    }

    //  Static Resources Configuration
    const cacheControl = {maxAge: config.staticResourceCacheDuration * 1000};

    [
        '../public',
        '../assets',
        '../assets/stylesheets',
        '../node_modules/govuk_template_jinja/assets',
        '../node_modules/govuk_frontend_toolkit'
    ].forEach(dir => {
        app.use('/public', express.static(path.join(__dirname, dir), cacheControl));
    });

    [
        '../node_modules/govuk_frontend_toolkit/images'
    ].forEach(dir => {
        app.use('/public/images/icons', express.static(path.join(__dirname, dir), cacheControl));
    });

    // GovUK Template Configuration
    app.locals.asset_path = '/public/';

    function addTemplateVariables(req, res, next) {
        res.locals.user = req.user;
        next();
    }

    app.use(addTemplateVariables);

    // Don't cache dynamic resources
    app.use(helmet.noCache());

    // Request logging
    app.use(expressWinston.logger({
        winstonInstance: logger,
        meta: true,
        dynamicMeta: function(req, res) {
            let meta = {
                userEmail: req.user ? req.user.staffId : null,
                requestId: req.id,
                sessionTag: req.user ? req.user.sessionTag : null
            };

            if (res._headers.location) {
                meta.res_header_location = res._headers.location;
            }

            return meta;
        },
        colorize: true,
        requestWhitelist: ['url', 'method', 'originalUrl', 'query', 'body'],
        ignoredRoutes: ['/health', '/favicon.ico']
    }));

    app.use(flash());

    app.use('/logout', (req, res) => {
        if (req.user) {
            req.logout();
        }
        res.redirect(authLogoutUrl);
    });

    // token refresh
    app.use(async (req, res, next) => {
        if (production && req.user) {
            const timeToRefresh = new Date() > req.user.refreshTime;
            if (timeToRefresh) {
                try {
                    const newToken = await signInService.getRefreshedToken(req.user);
                    req.user.token = newToken.token;
                    req.user.refreshToken = newToken.refreshToken;
                    req.user.refreshTime = newToken.refreshTime;
                } catch (error) {
                    logger.error(`Elite 2 token refresh error: ${req.user.username}`, error.stack);
                    return res.redirect('/logout');
                }
            }
        }
        next();
    });

    // Update a value in the cookie so that the set-cookie will be sent.
    // Only changes every minute so that it's not sent with every request.
    app.use(function(req, res, next) {
        req.session.nowInMinutes = Math.floor(Date.now() / 60e3);
        next();
    });

    // Express Routing Configuration
    app.get('/health', (req, res, next) => {
        healthcheck((err, result) => {
            if (err) {
                return next(err);
            }
            if (!result.healthy) {
                res.status(503);
            }

            res.json(result);
        });
    });

    app.get('/health-detailed', (req, res, next) => {
        healthcheck((err, result) => {
            if (err) {
                return next(err);
            }
            if (!result.healthy) {
                res.status(503);
            }

            res.json(result);
        }, true);
    });

    app.get('/feedback', (req, res) => {
        return res.render('feedback', {returnURL: req.get('referer')});
    });

    if (production) {
        app.use(ensureHttps);
    }

    app.get('/notfound', (req, res) => {
        res.status(404);
        return res.render('notfound');
    });

    const authLogoutUrl = config.authStrategy === 'oauth' ?
        `${config.nomis.authExternalUrl}/logout?client_id=${config.nomis.apiClientId}&redirect_uri=${config.domain}` : '/login';

    app.get('/autherror', (req, res) => {
        res.status(401);
        return res.render('autherror', {
            authURL: authLogoutUrl
        });
    });

    if (config.authStrategy === 'oauth') {
        app.get('/login', passport.authenticate('oauth2'));
    }

    if (config.authStrategy === 'local') {
        app.use('/login', signInRouter(passport));
    }

    app.get('/login/callback', passport.authenticate('oauth2', {successReturnToOrRedirect: '/', failureRedirect: '/autherror'}));

    const secureRoute = standardRouter({licenceService, prisonerService, audit, signInService});

    app.use((req, res, next) => {
        res.locals.tagManagerKey = config.tagManagerKey;
        next();
    });

    app.use('/', defaultRouter());

    app.use('/hdc/taskList/', secureRoute(taskListRouter({prisonerService, licenceService, caseListService, audit}),
            {licenceRequired: false}));
    app.use('/caseList/', secureRoute(caseListRouter({caseListService})));
    app.use('/admin/', secureRoute(adminRouter({userAdminService}), {auditKey: 'USER_MANAGEMENT'}));
    app.use('/hdc/contact/', secureRoute(contactRouter({userAdminService})));
    app.use('/hdc/pdf/', secureRoute(pdfRouter({pdfService, prisonerService}), {auditKey: 'CREATE_PDF'}));
    app.use('/hdc/search/', secureRoute(searchRouter({searchService})));
    app.use('/hdc/send/', secureRoute(sendRouter({licenceService, prisonerService, notificationService, audit})));
    app.use('/hdc/sent/', secureRoute(sentRouter({licenceService, prisonerService})));
    app.use('/user/', secureRoute(userRouter({userService})));

    app.use('/hdc/', secureRoute(addressRouter({licenceService})));
    app.use('/hdc/', secureRoute(approvalRouter({licenceService, prisonerService})));
    app.use('/hdc/', secureRoute(bassReferralRouter({licenceService})));
    app.use('/hdc/', secureRoute(conditionsRouter({licenceService, conditionsService})));
    app.use('/hdc/', secureRoute(curfewRouter({licenceService})));
    app.use('/hdc/', secureRoute(eligibilityRouter({licenceService})));
    app.use('/hdc/', secureRoute(finalChecksRouter({licenceService})));
    app.use('/hdc/', secureRoute(reviewRouter({licenceService, conditionsService, prisonerService})));
    app.use('/hdc/', secureRoute(reportingRouter({licenceService})));
    app.use('/hdc/', secureRoute(riskRouter({licenceService})));
    app.use('/hdc/', secureRoute(victimRouter({licenceService})));
    app.use('/hdc/', secureRoute(varyRouter({licenceService})));

    // hide functionality until authorisation strategy is established
    if (!production) {
        app.use('/api/', apiRouter({reportingService}));
    }

    // Error Handler
    app.use(function(req, res, next) {
        res.redirect('/notfound');
    });

    app.use(handleKnownErrors);
    app.use(renderErrors);

    return app;
};

function handleKnownErrors(error, req, res, next) {

    if (error.code === 'EBADCSRFTOKEN') {
        logger.error('Bad csurf token: ' + error.stack);
    }

    if (error.name === 'NoToken') {
        logger.error('No token found for user');
        return res.redirect('/logout');
    }

    switch (error.status) {
        case 401:
            return res.redirect('/logout');
        case 403:
            logger.error('Unauthorised: ', error.stack);
            return res.redirect('/logout');
        default:
            next(error);
    }
}

function renderErrors(error, req, res, next) {
    logger.error('Unhandled error: ' + error.stack);

    res.locals.error = error;
    res.locals.stack = production ? null : error.stack;
    res.locals.message = production ?
        'Something went wrong. The error has been logged. Please try again' : error.message;

    res.status(error.status || 500);

    res.render('error');
}
<commit_msg>NN-1579: Retry auth error if auth failure due to state<commit_after>const logger = require('../log.js');
const expressWinston = require('express-winston');
const addRequestId = require('express-request-id')();
const moment = require('moment');

const bodyParser = require('body-parser');
const cookieSession = require('cookie-session');
const cookieParser = require('cookie-parser');
const express = require('express');
const path = require('path');
const flash = require('connect-flash');

const helmet = require('helmet');
const csurf = require('csurf');
const compression = require('compression');
const ensureHttps = require('./utils/ensureHttps');

const sassMiddleware = require('node-sass-middleware');

const config = require('../server/config');
const healthcheck = require('../server/healthcheck');

const passport = require('passport');
const auth = require('./authentication/auth');

const defaultRouter = require('../server/routes/default');
const signInRouter = require('./routes/signIn');

const adminRouter = require('../server/routes/admin/admin');
const apiRouter = require('../server/routes/api');
const caseListRouter = require('../server/routes/caseList');
const contactRouter = require('../server/routes/contact');
const pdfRouter = require('../server/routes/pdf');
const searchRouter = require('../server/routes/search');
const sendRouter = require('../server/routes/send');
const sentRouter = require('../server/routes/sent');
const taskListRouter = require('./routes/taskList');
const utilsRouter = require('../server/routes/utils');
const userRouter = require('../server/routes/user');

const standardRouter = require('./routes/routeWorkers/standardRouter');
const addressRouter = require('./routes/address');
const approvalRouter = require('./routes/approval');
const bassReferralRouter = require('./routes/bassReferral');
const conditionsRouter = require('./routes/conditions');
const curfewRouter = require('./routes/curfew');
const eligibilityRouter = require('./routes/eligibility');
const finalChecksRouter = require('./routes/finalChecks');
const reviewRouter = require('./routes/review');
const reportingRouter = require('./routes/reporting');
const riskRouter = require('./routes/risk');
const victimRouter = require('./routes/victim');
const varyRouter = require('./routes/vary');

const version = moment.now().toString();
const production = process.env.NODE_ENV === 'production';

module.exports = function createApp({
                                        signInService,
                                        licenceService,
                                        prisonerService,
                                        conditionsService,
                                        caseListService,
                                        pdfService,
                                        searchService,
                                        userAdminService,
                                        reportingService,
                                        notificationService,
                                        userService,
                                        audit
                                    }) {
    const app = express();

    auth.init(signInService, userService, audit, config.authStrategy);

    app.set('json spaces', 2);

    // Configure Express for running behind proxies
    // https://expressjs.com/en/guide/behind-proxies.html
    app.set('trust proxy', true);

    // View Engine Configuration
    app.set('views', path.join(__dirname, '../server/views'));
    app.set('view engine', 'pug');

    // Server Configuration
    app.set('port', process.env.PORT || 3000);

    // HACK: Azure doesn't support X-Forwarded-Proto so we add it manually
    // http://stackoverflow.com/a/18455265/173062
    app.use(function(req, res, next) {
        if (req.headers['x-arr-ssl'] && !req.headers['x-forwarded-proto']) {
            req.headers['x-forwarded-proto'] = 'https';
        }
        return next();
    });

    // Secure code best practice - see:
    // 1. https://expressjs.com/en/advanced/best-practice-security.html,
    // 2. https://www.npmjs.com/package/helmet
    app.use(helmet());

    app.use(addRequestId);

    app.use(cookieSession({
        name: 'session',
        keys: [config.sessionSecret],
        maxAge: 60 * 60 * 1000,
        secure: config.https,
        httpOnly: true,
        signed: true,
        overwrite: true,
        sameSite: 'lax'
    }));

    app.use(passport.initialize());
    app.use(passport.session());

    // Request Processing Configuration
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));

    if (config.enableTestUtils) {
        app.use('/utils/', utilsRouter());
    }

    app.use(cookieParser());
    app.use(csurf({cookie: {secure: config.https, httpOnly: true}}));

    // Resource Delivery Configuration
    app.use(compression());

    // Cachebusting version string
    if (production) {
        // Version only changes on reboot
        app.locals.version = version;
    } else {
        // Version changes every request
        app.use(function(req, res, next) {
            res.locals.version = moment.now().toString();
            return next();
        });
    }

    if (!production) {
        app.use('/public', sassMiddleware({
            src: path.join(__dirname, '../assets/sass'),
            dest: path.join(__dirname, '../assets/stylesheets'),
            debug: false,
            outputStyle: 'compressed',
            prefix: '/stylesheets/',
            includePaths: [
                'node_modules/govuk_frontend_toolkit/stylesheets',
                'node_modules/govuk_template_jinja/assets/stylesheets',
                'node_modules/govuk-elements-sass/public/sass'
            ]
        }));
    }

    //  Static Resources Configuration
    const cacheControl = {maxAge: config.staticResourceCacheDuration * 1000};

    [
        '../public',
        '../assets',
        '../assets/stylesheets',
        '../node_modules/govuk_template_jinja/assets',
        '../node_modules/govuk_frontend_toolkit'
    ].forEach(dir => {
        app.use('/public', express.static(path.join(__dirname, dir), cacheControl));
    });

    [
        '../node_modules/govuk_frontend_toolkit/images'
    ].forEach(dir => {
        app.use('/public/images/icons', express.static(path.join(__dirname, dir), cacheControl));
    });

    // GovUK Template Configuration
    app.locals.asset_path = '/public/';

    function addTemplateVariables(req, res, next) {
        res.locals.user = req.user;
        next();
    }

    app.use(addTemplateVariables);

    // Don't cache dynamic resources
    app.use(helmet.noCache());

    // Request logging
    app.use(expressWinston.logger({
        winstonInstance: logger,
        meta: true,
        dynamicMeta: function(req, res) {
            let meta = {
                userEmail: req.user ? req.user.staffId : null,
                requestId: req.id,
                sessionTag: req.user ? req.user.sessionTag : null
            };

            if (res._headers.location) {
                meta.res_header_location = res._headers.location;
            }

            return meta;
        },
        colorize: true,
        requestWhitelist: ['url', 'method', 'originalUrl', 'query', 'body'],
        ignoredRoutes: ['/health', '/favicon.ico']
    }));

    app.use(flash());

    app.use('/logout', (req, res) => {
        if (req.user) {
            req.logout();
        }
        res.redirect(authLogoutUrl);
    });

    // token refresh
    app.use(async (req, res, next) => {
        if (production && req.user) {
            const timeToRefresh = new Date() > req.user.refreshTime;
            if (timeToRefresh) {
                try {
                    const newToken = await signInService.getRefreshedToken(req.user);
                    req.user.token = newToken.token;
                    req.user.refreshToken = newToken.refreshToken;
                    req.user.refreshTime = newToken.refreshTime;
                } catch (error) {
                    logger.error(`Elite 2 token refresh error: ${req.user.username}`, error.stack);
                    return res.redirect('/logout');
                }
            }
        }
        next();
    });

    // Update a value in the cookie so that the set-cookie will be sent.
    // Only changes every minute so that it's not sent with every request.
    app.use(function(req, res, next) {
        req.session.nowInMinutes = Math.floor(Date.now() / 60e3);
        next();
    });

    // Express Routing Configuration
    app.get('/health', (req, res, next) => {
        healthcheck((err, result) => {
            if (err) {
                return next(err);
            }
            if (!result.healthy) {
                res.status(503);
            }

            res.json(result);
        });
    });

    app.get('/health-detailed', (req, res, next) => {
        healthcheck((err, result) => {
            if (err) {
                return next(err);
            }
            if (!result.healthy) {
                res.status(503);
            }

            res.json(result);
        }, true);
    });

    app.get('/feedback', (req, res) => {
        return res.render('feedback', {returnURL: req.get('referer')});
    });

    if (production) {
        app.use(ensureHttps);
    }

    app.get('/notfound', (req, res) => {
        res.status(404);
        return res.render('notfound');
    });

    const authLogoutUrl = config.authStrategy === 'oauth' ?
        `${config.nomis.authExternalUrl}/logout?client_id=${config.nomis.apiClientId}&redirect_uri=${config.domain}` : '/login';

    app.get('/autherror', (req, res) => {
        res.status(401);
        return res.render('autherror', {
            authURL: authLogoutUrl
        });
    });

    if (config.authStrategy === 'oauth') {
        app.get('/login', passport.authenticate('oauth2'));
    }

    if (config.authStrategy === 'local') {
        app.use('/login', signInRouter(passport));
    }

    app.get('/login/callback', (req, res, next) => {
        passport.authenticate('oauth2', (err, user, info) => {
            if (err) {
                return res.redirect('/autherror');
            }
            if (!user) {
                if (info && info.message === 'Unable to verify authorization request state.') {
                    // failure to due authorisation state not being there on return, so retry
                    logger.info('Retrying auth callback as no state found');
                    return res.redirect('/');
                }
                logger.info(`Auth failure due to ${JSON.stringify(info)}`);
                return res.redirect('/autherror');
            }
            req.logIn(user, err2 => {
                if (err2) {
                    return next(err2);
                }
                return res.redirect('/');
            });
            return null;
        })(req, res, next);
    });

    const secureRoute = standardRouter({licenceService, prisonerService, audit, signInService});

    app.use((req, res, next) => {
        res.locals.tagManagerKey = config.tagManagerKey;
        next();
    });

    app.use('/', defaultRouter());

    app.use('/hdc/taskList/', secureRoute(taskListRouter({prisonerService, licenceService, caseListService, audit}),
            {licenceRequired: false}));
    app.use('/caseList/', secureRoute(caseListRouter({caseListService})));
    app.use('/admin/', secureRoute(adminRouter({userAdminService}), {auditKey: 'USER_MANAGEMENT'}));
    app.use('/hdc/contact/', secureRoute(contactRouter({userAdminService})));
    app.use('/hdc/pdf/', secureRoute(pdfRouter({pdfService, prisonerService}), {auditKey: 'CREATE_PDF'}));
    app.use('/hdc/search/', secureRoute(searchRouter({searchService})));
    app.use('/hdc/send/', secureRoute(sendRouter({licenceService, prisonerService, notificationService, audit})));
    app.use('/hdc/sent/', secureRoute(sentRouter({licenceService, prisonerService})));
    app.use('/user/', secureRoute(userRouter({userService})));

    app.use('/hdc/', secureRoute(addressRouter({licenceService})));
    app.use('/hdc/', secureRoute(approvalRouter({licenceService, prisonerService})));
    app.use('/hdc/', secureRoute(bassReferralRouter({licenceService})));
    app.use('/hdc/', secureRoute(conditionsRouter({licenceService, conditionsService})));
    app.use('/hdc/', secureRoute(curfewRouter({licenceService})));
    app.use('/hdc/', secureRoute(eligibilityRouter({licenceService})));
    app.use('/hdc/', secureRoute(finalChecksRouter({licenceService})));
    app.use('/hdc/', secureRoute(reviewRouter({licenceService, conditionsService, prisonerService})));
    app.use('/hdc/', secureRoute(reportingRouter({licenceService})));
    app.use('/hdc/', secureRoute(riskRouter({licenceService})));
    app.use('/hdc/', secureRoute(victimRouter({licenceService})));
    app.use('/hdc/', secureRoute(varyRouter({licenceService})));

    // hide functionality until authorisation strategy is established
    if (!production) {
        app.use('/api/', apiRouter({reportingService}));
    }

    // Error Handler
    app.use(function(req, res, next) {
        res.redirect('/notfound');
    });

    app.use(handleKnownErrors);
    app.use(renderErrors);

    return app;
};

function handleKnownErrors(error, req, res, next) {

    if (error.code === 'EBADCSRFTOKEN') {
        logger.error('Bad csurf token: ' + error.stack);
    }

    if (error.name === 'NoToken') {
        logger.error('No token found for user');
        return res.redirect('/logout');
    }

    switch (error.status) {
        case 401:
            return res.redirect('/logout');
        case 403:
            logger.error('Unauthorised: ', error.stack);
            return res.redirect('/logout');
        default:
            next(error);
    }
}

function renderErrors(error, req, res, next) {
    logger.error('Unhandled error: ' + error.stack);

    res.locals.error = error;
    res.locals.stack = production ? null : error.stack;
    res.locals.message = production ?
        'Something went wrong. The error has been logged. Please try again' : error.message;

    res.status(error.status || 500);

    res.render('error');
}
<|endoftext|>


<commit_before>/**
 * Created by Abhinav on 05-03-2017.
 */
var express = require('express');
var fs = require('fs');
var async=require('async');
var MongoClient = require('mongodb').MongoClient;
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var type = require('type-of-is');
var base64url = require('base64-url');
var historyid;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-nodejs-quickstart.json
var SCOPES = ['https://mail.google.com'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
var HISTORY_PATH = TOKEN_DIR + 'History_id.txt';
var gcredentials="";
var mongo=require("./setupmongo.js");
var app=express();
app.listen(3000);
//mongo();
var url = 'mongodb://localhost:27017/automated';
// Use connect method to connect to the Server
var db;
    MongoClient.connect(url, function (err, dbs) {

        console.log("Connected correctly to server");
        db=dbs;
    });

app.get('/users/google/callback', function(req, res) {
    console.log(req.query.code);
    res.end("");
});

fs.readFile('../client_secret.json', function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Gmail API.
    gcredentials=JSON.parse(content);
    authorize(JSON.parse(content), start);
});

// Load client secrets from a local file.

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials,callback) {

    var clientSecret = credentials.web.client_secret;
    var clientId = credentials.web.client_id;
    var redirectUrl = credentials.web.redirect_uris[0];

    var auth = new googleAuth();
    var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

    google.options({
        auth: oauth2Client
    });

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function(err, token) {
        if (err) {
            getNewToken(oauth2Client, callback);
        } else {
            oauth2Client.credentials = JSON.parse(token);
            callback(oauth2Client,list);
        }
    });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */

function getNewToken(oauth2Client, callback) {
    var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES
    });
    console.log('Authorize this app by visiting this url: ', authUrl);
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Enter the code that appears here and press enter: ', function(code) {
        rl.close();
        oauth2Client.getToken(code, function(err, token) {
            if (err) {
                console.log('Error while trying to retrieve access token', err);
                return;
            }
            oauth2Client.credentials = token;
            storeToken(token);
            callback(oauth2Client,list);
        });
    });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
    try {
        fs.mkdirSync(TOKEN_DIR);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(TOKEN_PATH, JSON.stringify(token));
    console.log('Token stored to ' + TOKEN_PATH);
}
function storehistoryid(token) {
    try {
        fs.mkdirSync(HISTORY_PATH);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(HISTORY_PATH, JSON.stringify(token));
    console.log('Token stored to ' + HISTORY_PATH);
}

function start(auth,list){
    fs.readFile(HISTORY_PATH,function(err, hId) {
        if (err) {
            console.log(err);
        } else {
            historyid=JSON.parse(hId);

            list(auth);
        }
    });

}

function list(auth){
    console.log(historyid);
    var gmail = google.gmail('v1');
    gmail.users.history.list({
        auth: auth,
        userId: 'me',
        startHistoryId: historyid,
        historyTypes:'messageAdded',
        labelId:'INBOX'

    },  function (err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            getNewToken(auth,start);

          /* auth.refreshAccessToken(function(err, tokens) {
           storeToken(tokens)
           });*/
        }
        else{
        try
        {var id = response.history;
            historyid=response.historyId;
            storehistoryid(historyid);
           // console.log(response);
            console.log(id.length);
            for(var i=0;id[i];i++){
                // console.log(id[i].messages[0].id);

               // async.waterfall([getmessage(id[i].messages[0].id,auth,gmail,send),send(subject,gmail,auth,mailto,body)]);
                getmessage(id[i].messages[0].id,auth,gmail);
                if(i==id.length-1){
                setTimeout(function (auth){
                    list(auth);
                },5000);}
            }
        }
        catch(err) {
            //console.log(collection);
            console.log("no new messages");
            setTimeout(function (auth){
            list(auth);
        },5000);}}
    });

}

function getmessage(id,auth,gmail) {console.log(id);
    gmail.users.messages.get({
        auth: auth,
        userId: 'me',
        id: id,
    },function (err,response){
        if (err){console.log("here take a error ");
            return;}
        else
        {   for(var i=0;response.payload.headers[i];i++){
            if(response.payload.headers[i].name=="From"){
                var mailto=response.payload.headers[i].value;
                console.log(mailto);}
            else if(response.payload.headers[i].name=="Subject")
                var inputsubject=response.payload.headers[i].value;
        }
            var inputbody=response.payload.parts[0].body.data;
            inputbody =base64url.unescape(inputbody);
            inputbody=base64url.decode(inputbody);
            if(inputbody.lastIndexOf("\n")>0) {
                inputbody= inputbody.substring(0, inputbody.lastIndexOf("\n"));
                inputbody=inputbody.replace(/\s/g,'').toLowerCase();
            }
            makesubject(auth,gmail,mailto,inputsubject,inputbody);
            }

    })
return;
}
function makesubject(auth,gmail,mailto,inputsubject,inputbody){
    console.log(inputbody);

    //console.log(mailto,inputsubject);
    var subject;
    var body="Subject or query is invalid.";
    if(inputsubject.replace(/\s/g,'').toLowerCase()=="search_database")
    {
        //setTimeout(function(){subject="Here is the requested query";},500);
        var collection=db.collection("dishes");
        collection.find({firstname:inputbody}).toArray(function(err, docs) {
            body="";
            subject="Here is the requested query";
            for(var i=0;docs[i];i++){
           // body.concat(docs[i].name)
            body=body+(i+1)+".
";
            body=body+"Name:"+docs[i].firstname+" "+docs[i].lastname+"
";
            body=body+"Id:"+docs[i]._id+"

";
            //console.log(docs[i].name);
            }

            send(subject,gmail,auth,mailto,body);
        });

    }
    else{
        subject="Invalid Query!!";
        send(subject,gmail,auth,mailto,body);
    }
    }

function yo(subject,gmail,auth,mailto,body){console.log(subject);};
function send(subject,gmail,auth,mailto,body) { var string="To:"+mailto+"\n" +
    "From:Automated bot <automatedquery@gmail.com>\n"+
    "Content-type: text/html;charset=UTF-8\n"+
    "MIME-Version: 1.0\n"+
    "Subject:"+subject+"\n\n"+
    "
"+body+"
\n";

    var r=base64url.escape(base64url.encode(string));
    console.log(r);
    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        resource: {raw:r}}
    )}
/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listLabels1(auth) {
    var gmail = google.gmail('v1');
    gmail.users.messages.list({
        auth: auth,
        userId: 'me',
        maxResults: 5,
        labelIds: "INBOX"

    }, function (err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }
        var id = response.messages;
        {
            console.log(id);
            getmessage(id[0].id,auth,gmail);
        }
    });
}

<commit_msg>first major commit<commit_after>/**
 * Created by Abhinav on 05-03-2017.
 */
var express = require('express');
var fs = require('fs');
var async=require('async');
var MongoClient = require('mongodb').MongoClient;
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var type = require('type-of-is');
var base64url = require('base64-url');
var historyid;
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-nodejs-quickstart.json
var SCOPES = ['https://mail.google.com'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'gmail-nodejs-quickstart.json';
var HISTORY_PATH = TOKEN_DIR + 'History_id.txt';
var gcredentials="";
var mongo=require("./setupmongo.js");
var app=express();
app.listen(3000);
//mongo();
var url = 'mongodb://localhost:27017/automated';
// Use connect method to connect to the Server
var db;
    MongoClient.connect(url, function (err, dbs) {

        console.log("Connected correctly to server");
        db=dbs;
    });

app.get('/users/google/callback', function(req, res) {
    console.log(req.query.code);
    res.end("");
});

fs.readFile('../client_secret.json', function processClientSecrets(err, content) {
    if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
    }
    // Authorize a client with the loaded credentials, then call the
    // Gmail API.
    gcredentials=JSON.parse(content);
    authorize(JSON.parse(content), start);
});

// Load client secrets from a local file.

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials,callback) {

    var clientSecret = credentials.web.client_secret;
    var clientId = credentials.web.client_id;
    var redirectUrl = credentials.web.redirect_uris[0];

    var auth = new googleAuth();
    var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

    google.options({
        auth: oauth2Client
    });

    // Check if we have previously stored a token.
    fs.readFile(TOKEN_PATH, function(err, token) {
        if (err) {
            getNewToken(oauth2Client, callback);
        } else {
            oauth2Client.credentials = JSON.parse(token);
            callback(oauth2Client,list);
        }
    });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */

function getNewToken(oauth2Client, callback) {
    var authUrl = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: SCOPES
    });
    console.log('Authorize this app by visiting this url: ', authUrl);
    var rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.question('Enter the code that appears here and press enter: ', function(code) {
        rl.close();
        oauth2Client.getToken(code, function(err, token) {
            if (err) {
                console.log('Error while trying to retrieve access token', err);
                return;
            }
            oauth2Client.credentials = token;
            storeToken(token);
            callback(oauth2Client,list);
        });
    });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
    try {
        fs.mkdirSync(TOKEN_DIR);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(TOKEN_PATH, JSON.stringify(token));
    console.log('Token stored to ' + TOKEN_PATH);
}
function storehistoryid(token) {
    try {
        fs.mkdirSync(HISTORY_PATH);
    } catch (err) {
        if (err.code != 'EEXIST') {
            throw err;
        }
    }
    fs.writeFile(HISTORY_PATH, JSON.stringify(token));
    console.log('Token stored to ' + HISTORY_PATH);
}

function start(auth,list){
    fs.readFile(HISTORY_PATH,function(err, hId) {
        if (err) {
            console.log(err);
        } else {
            historyid=JSON.parse(hId);

            list(auth);
        }
    });

}

function list(auth){
    console.log(historyid);
    var gmail = google.gmail('v1');
    gmail.users.history.list({
        auth: auth,
        userId: 'me',
        startHistoryId: historyid,
        historyTypes:'messageAdded',
        labelId:'INBOX'

    },  function (err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            getNewToken(auth,start);

          /* auth.refreshAccessToken(function(err, tokens) {
           storeToken(tokens)
           });*/
        }
        else{
        try
        {var id = response.history;
            historyid=response.historyId;
            storehistoryid(historyid);
           // console.log(response);
            console.log(id.length);
            for(var i=0;id[i];i++){
                // console.log(id[i].messages[0].id);

               // async.waterfall([getmessage(id[i].messages[0].id,auth,gmail,send),send(subject,gmail,auth,mailto,body)]);
                getmessage(id[i].messages[0].id,auth,gmail);
                if(i==id.length-1){
                setTimeout(function (auth){
                    list(auth);
                },5000);}
            }
        }
        catch(err) {
            //console.log(collection);
            console.log("no new messages");
            setTimeout(function (auth){
            list(auth);
        },5000);}}
    });

}

function getmessage(id,auth,gmail) {console.log(id);
    gmail.users.messages.get({
        auth: auth,
        userId: 'me',
        id: id,
    },function (err,response){
        if (err){console.log("here take a error ");
            return;}
        else
        {   for(var i=0;response.payload.headers[i];i++){
            if(response.payload.headers[i].name=="From"){
                var mailto=response.payload.headers[i].value;
                console.log(mailto);}
            else if(response.payload.headers[i].name=="Subject")
                var inputsubject=response.payload.headers[i].value;
        }
            var inputbody=response.payload.parts[0].body.data;
            inputbody =base64url.unescape(inputbody);
            inputbody=base64url.decode(inputbody);
            if(inputbody.lastIndexOf("\n")>0) {
                inputbody= inputbody.substring(0, inputbody.lastIndexOf("\n"));
               // inputbody=inputbody.replace(/\s/g,'').toLowerCase();
            }
            makesubject(auth,gmail,mailto,inputsubject,inputbody);
            }

    })
return;
}
function makesubject(auth,gmail,mailto,inputsubject,inputbody){
    console.log(inputbody);

    //console.log(mailto,inputsubject);
    var subject;
    var body="Subject or query is invalid.";
    if(inputsubject.replace(/\s/g,'').toLowerCase()=="search_database")
    {
        //setTimeout(function(){subject="Here is the requested query";},500);
        var collection=db.collection("dishes");
        var search = inputbody.split('\n')[0].replace(/\s/g,'').toLowerCase();
        inputbody=inputbody.split('\n')[1].replace(/\s/g,'').toLowerCase();
        if(search=="firstname"){
        collection.find({firstname:inputbody}).toArray(function(err, docs) {
            body="";
            subject="Here is the requested query";
            for(var i=0;docs[i];i++){
           // body.concat(docs[i].name)
            body=body+(i+1)+".
";
            body=body+"Name:"+docs[i].firstname+" "+docs[i].lastname+"
";
            body=body+"Id:"+docs[i]._id+"

";
            //console.log(docs[i].name);
            }

            send(subject,gmail,auth,mailto,body);
        });

    }
        else if(search=="lastname"){
            collection.find({lastname:inputbody}).toArray(function(err, docs) {
                body="";
                subject="Here is the requested query";
                for(var i=0;docs[i];i++){
                    // body.concat(docs[i].name)
                    body=body+(i+1)+".
";
                    body=body+"Name:"+docs[i].firstname+" "+docs[i].lastname+"
";
                    body=body+"Id:"+docs[i]._id+"

";
                    //console.log(docs[i].name);
                }

                send(subject,gmail,auth,mailto,body);
            });

        }
        else if(search=="phoneno"){
            collection.find({phoneno:inputbody}).toArray(function(err, docs) {
                body="";
                subject="Here is the requested query";
                for(var i=0;docs[i];i++){
                    // body.concat(docs[i].name)
                    body=body+(i+1)+".
";
                    body=body+"Name:"+docs[i].firstname+" "+docs[i].lastname+"
";
                    body=body+"Id:"+docs[i]._id+"

";
                    //console.log(docs[i].name);
                }

                send(subject,gmail,auth,mailto,body);
            });

        }
    }
    else{
        subject="Invalid Query!!";
        send(subject,gmail,auth,mailto,body);
    }
    }

function yo(subject,gmail,auth,mailto,body){console.log(subject);};
function send(subject,gmail,auth,mailto,body) { var string="To:"+mailto+"\n" +
    "From:Automated bot <automatedquery@gmail.com>\n"+
    "Content-type: text/html;charset=UTF-8\n"+
    "MIME-Version: 1.0\n"+
    "Subject:"+subject+"\n\n"+
    "
"+body+"
\n";

    var r=base64url.escape(base64url.encode(string));
    console.log(r);
    gmail.users.messages.send({
        auth: auth,
        userId: 'me',
        resource: {raw:r}}
    )}
/**
 * Lists the labels in the user's account.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listLabels1(auth) {
    var gmail = google.gmail('v1');
    gmail.users.messages.list({
        auth: auth,
        userId: 'me',
        maxResults: 5,
        labelIds: "INBOX"

    }, function (err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }
        var id = response.messages;
        {
            console.log(id);
            getmessage(id[0].id,auth,gmail);
        }
    });
}

<|endoftext|>


<commit_before>const express = require('express');
const { fork } = require('child_process');
const cors = require('cors');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
var multer = require('multer');
var bodyParser = require('body-parser');
const routes = require('./app.routes.js');
var File = require("./models/file");
db = require('./app.db.js');
// Middleware
var app = express();
app.use(function (req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    // res.header("Access-Control-Allow-Origin", "http://localhost:" + process.env.NODE_PORT + "/api");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});
app.use(cors({ origin: ['http://localhost:4200', 'http://localhost:8080', 'http://localhost:8080'] }));
app.use(bodyParser.urlencoded({
    limit: '400mb',
    extended: true
}));
app.use(bodyParser.json({limit: '400mb'}));

// Routes
db.getConnection().then( db => {
    console.log("OK READY!");
    routes.init(app);
});

//#region Notify User with email when the file is uploaded and parsed into DB

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'oncoscape.sttrcancer@gmail.com',
        pass: process.env.GMAIL_PASSWORD
    }
});

//#endregion

//#region Uploaded File storage on the server

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.env.APP_ROOT + '/uploads')
    },
    filename: function (req, file, cb) {
        var newFileName = file.fieldname + '-' + Date.now() + '.xlsx';
        cb(null, newFileName);
    }
});
var upload = multer({
    storage: storage,
    preservePath: true
}).single('file');

//#endregion

//#region Data Upload Functions

app.use('/api/upload', express.static(process.env.APP_ROOT + '/uploads'));
app.post('/api/upload/:id/:email', function (req, res) {
    var projectID = req.params.id;
    var userEmail = req.params.email;
    var mailOptions = {
        from: 'oncoscape.sttrcancer@gmail.com',
        to: userEmail,
        subject: 'Notification from Oncoscape Data Uploading App',
        text: 'Data are in database, ready to share.'
    };
    var molecularColleciton = mongoose.model(projectID + "_data_molecular", File.schema);
    var sampleMapCollection = mongoose.model(projectID + "_data_samples", File.schema);
    var clinicalColleciton = mongoose.model(projectID + "_data_clinical", File.schema);
    var uploadingSummaryCollection = mongoose.model(projectID + "_uploadingSummary", File.schema);
    upload(req, res, function (err) {
        console.log("This section is triggered");
        if (err) {
            console.log(err);
            return;
        } else {
            const writing2Mongo = fork(process.env.APP_ROOT + '/server/fileUpload.js',
                { execArgv: ['--max-old-space-size=1000'] });
            writing2Mongo.send({
                filePath: res.req.file.path,
                projectID: projectID
            });
            writing2Mongo.on('message', () => {
                res.end('Writing is done');
                console.log("*********************!!!!!!!********************");
                transporter.sendMail(mailOptions, function (error, info) {
                    if (error) {
                        console.log(error);
                    } else {
                        console.log('Email sent: ' + info.response);
                    }
                });
            });
        }
    });
    res.status(200).end();
});

//#endregion

// Start Listening
app.listen(process.env.NODE_PORT, function () {
    console.log("UP");
});
<commit_msg>redeploy<commit_after>const express = require('express');
const { fork } = require('child_process');
const cors = require('cors');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
var multer = require('multer');
var bodyParser = require('body-parser');
const routes = require('./app.routes.js');
var File = require("./models/file");
db = require('./app.db.js');
// Middleware
var app = express();
app.use(function (req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    // res.header("Access-Control-Allow-Origin", "http://localhost:" + process.env.NODE_PORT + "/api");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});
app.use(cors({ origin: ['http://localhost:4200', 'http://localhost:8080', 'http://localhost:8080'] }));
app.use(bodyParser.urlencoded({
    limit: '400mb',
    extended: true
}));
app.use(bodyParser.json({limit: '400mb'}));

// Routes
db.getConnection().then( db => {
    console.log("OK READY");
    routes.init(app);
});

//#region Notify User with email when the file is uploaded and parsed into DB

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'oncoscape.sttrcancer@gmail.com',
        pass: process.env.GMAIL_PASSWORD
    }
});

//#endregion

//#region Uploaded File storage on the server

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.env.APP_ROOT + '/uploads')
    },
    filename: function (req, file, cb) {
        var newFileName = file.fieldname + '-' + Date.now() + '.xlsx';
        cb(null, newFileName);
    }
});
var upload = multer({
    storage: storage,
    preservePath: true
}).single('file');

//#endregion

//#region Data Upload Functions

app.use('/api/upload', express.static(process.env.APP_ROOT + '/uploads'));
app.post('/api/upload/:id/:email', function (req, res) {
    var projectID = req.params.id;
    var userEmail = req.params.email;
    var mailOptions = {
        from: 'oncoscape.sttrcancer@gmail.com',
        to: userEmail,
        subject: 'Notification from Oncoscape Data Uploading App',
        text: 'Data are in database, ready to share.'
    };
    var molecularColleciton = mongoose.model(projectID + "_data_molecular", File.schema);
    var sampleMapCollection = mongoose.model(projectID + "_data_samples", File.schema);
    var clinicalColleciton = mongoose.model(projectID + "_data_clinical", File.schema);
    var uploadingSummaryCollection = mongoose.model(projectID + "_uploadingSummary", File.schema);
    upload(req, res, function (err) {
        console.log("This section is triggered");
        if (err) {
            console.log(err);
            return;
        } else {
            const writing2Mongo = fork(process.env.APP_ROOT + '/server/fileUpload.js',
                { execArgv: ['--max-old-space-size=1000'] });
            writing2Mongo.send({
                filePath: res.req.file.path,
                projectID: projectID
            });
            writing2Mongo.on('message', () => {
                res.end('Writing is done');
                console.log("*********************!!!!!!!********************");
                transporter.sendMail(mailOptions, function (error, info) {
                    if (error) {
                        console.log(error);
                    } else {
                        console.log('Email sent: ' + info.response);
                    }
                });
            });
        }
    });
    res.status(200).end();
});

//#endregion

// Start Listening
app.listen(process.env.NODE_PORT, function () {
    console.log("UP");
});
<|endoftext|>


<commit_before>const express = require('express');
const { fork } = require('child_process');
const cors = require('cors');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
var multer = require('multer');
var bodyParser = require('body-parser');
const routes = require('./app.routes.js');
var File = require("./models/file");
db = require('./app.db.js');
// Middleware
var app = express();
app.use(function (req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    // res.header("Access-Control-Allow-Origin", "http://localhost:" + process.env.NODE_PORT + "/api");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});
app.use(cors({ origin: ['http://localhost:4200', 'http://localhost:8080'] }));
app.use(bodyParser.urlencoded({
    limit: '400mb',
    extended: true
}));
app.use(bodyParser.json({limit: '400mb'}));

// Routes
db.getConnection().then( db => {
    console.log("OK READY!");
    routes.init(app);
});

//#region Notify User with email when the file is uploaded and parsed into DB

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'oncoscape.sttrcancer@gmail.com',
        pass: process.env.GMAIL_PASSWORD
    }
});

//#endregion

//#region Uploaded File storage on the server

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/home/sttrweb/Oncoscape/uploads')
        // cb(null, process.env.APP_ROOT + '/uploads')
    },
    filename: function (req, file, cb) {
        var newFileName = file.fieldname + '-' + Date.now() + '.xlsx';
        cb(null, newFileName);
    }
});
var upload = multer({
    storage: storage,
    preservePath: true
}).single('file');

//#endregion

//#region Data Upload Functions

// app.use('/api/upload', express.static(process.env.APP_ROOT + '/uploads'));
app.use('/api/upload', express.static('/home/sttrweb/Oncoscape/uploads'));
app.post('/api/upload/:id/:email', function (req, res) {
    console.log('POST API/UPLOAD is being called.');
    var projectID = req.params.id;
    var userEmail = req.params.email;
    console.log('projectID: ', projectID);
    console.log('userEmail: ', userEmail);
    var molecularColleciton = mongoose.model(projectID + "_data_molecular", File.schema);
    var sampleMapCollection = mongoose.model(projectID + "_data_samples", File.schema);
    var clinicalColleciton = mongoose.model(projectID + "_data_clinical", File.schema);
    var uploadingSummaryCollection = mongoose.model(projectID + "_uploadingSummary", File.schema);
    console.log('test1');
    console.log(upload.toString());
    upload(req, res, function (err) {
        console.log("This section is triggered");
        if (err) {
            console.log(err);
            console.log('test2');
            var mailOptions = {
                from: 'oncoscape.sttrcancer@gmail.com',
                to: userEmail,
                subject: 'Notification from Oncoscape Data Uploading App',
                text: 'Data uploading Error: ' + err
            };
            transporter.sendMail(mailOptions, function (error, info) {
                if (error) {
                    console.log(error);
                } else {
                    console.log('Email sent: ' + info.response);
                }
            });
            return;
        } else {
            console.log('test3');
            // const writing2Mongo = fork(process.env.APP_ROOT + '/server/fileUpload.js',
            const writing2Mongo = fork('/home/sttrweb/Oncoscape/server/fileUpload.js',
                { execArgv: ['--max-old-space-size=4000'] });
            console.log('**', res.req.file);
            writing2Mongo.send({
                filePath: res.req.file.path,
                projectID: projectID
            });
            writing2Mongo.on('message', () => {
                res.end('Writing is done');
                console.log("*******************!!!!!!!*******************");
                var mailOptions = {
                    from: 'oncoscape.sttrcancer@gmail.com',
                    to: userEmail,
                    subject: 'Notification from Oncoscape Data Uploading App',
                    text: 'Data are in database, ready to share.'
                };
                transporter.sendMail(mailOptions, function (error, info) {
                    if (error) {
                        console.log(error);
                    } else {
                        console.log('Email sent: ' + info.response);
                    }
                });
            });
        }
    });
    res.status(200).end();
});

//#endregion

// Start Listening
app.listen(process.env.NODE_PORT, function () {
    console.log("UP");
});
<commit_msg>new try<commit_after>const express = require('express');
const { fork } = require('child_process');
const cors = require('cors');
const mongoose = require('mongoose');
const nodemailer = require('nodemailer');
var multer = require('multer');
var bodyParser = require('body-parser');
const routes = require('./app.routes.js');
var File = require("./models/file");
db = require('./app.db.js');
var Permission = require("./models/permission");
// Middleware
var app = express();
app.use(function (req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    // res.header("Access-Control-Allow-Origin", "http://localhost:" + process.env.NODE_PORT + "/api");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    res.header("Access-Control-Allow-Credentials", true);
    next();
});
app.use(cors({ origin: ['http://localhost:4200', 'http://localhost:8080'] }));
app.use(bodyParser.urlencoded({
    limit: '400mb',
    extended: true
}));
app.use(bodyParser.json({limit: '400mb'}));

// Routes
db.getConnection().then( db => {
    console.log("OK READY!");
    routes.init(app);
});

//#region Notify User with email when the file is uploaded and parsed into DB

var transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
        user: 'oncoscape.sttrcancer@gmail.com',
        pass: process.env.GMAIL_PASSWORD
    }
});

//#endregion

//#region Uploaded File storage on the server

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '/home/sttrweb/Oncoscape/uploads')
        // cb(null, process.env.APP_ROOT + '/uploads')
    },
    filename: function (req, file, cb) {
        var newFileName = file.fieldname + '-' + Date.now() + '.xlsx';
        cb(null, newFileName);
    }
});
var upload = multer({
    storage: storage,
    preservePath: true
}).single('file');
//#endregion

//#region Data Upload Functions

// app.use('/api/upload', express.static(process.env.APP_ROOT + '/uploads'));
app.use('/api/upload', express.static('/home/sttrweb/Oncoscape/uploads'));
app.post('/api/upload/:id/:email', Permissions.jwtVerification, function (req, res) {
    var projectID = req.params.id;
    var userEmail = req.params.email;
    var mailOptions = {
        from: 'jennylouzhang@gmail.com',
        to: userEmail,
        subject: 'Notification from Oncoscape Data Uploading App',
        text: 'Data are in database, ready to share.'
      };
    var molecularColleciton = mongoose.model(projectID + "_data_molecular", File.schema);
    var sampleMapCollection = mongoose.model(projectID + "_data_samples", File.schema);
    var clinicalColleciton = mongoose.model(projectID + "_data_clinical", File.schema);
    var uploadingSummaryCollection = mongoose.model(projectID + "_uploadingSummary", File.schema);
    upload(req, res, function (err) {
        console.log("This section is triggered");
        if (err) {
            console.log(err);
            return;
        } else {
            // const writing2Mongo = fork(process.env.APP_ROOT + '/server/fileUpload.js',
            const writing2Mongo = fork('/home/sttrweb/Oncoscape/server/fileUpload.js',
            { execArgv: ['--max-old-space-size=1000']});
            writing2Mongo.send({ filePath: res.req.file.path,
                                 projectID: projectID
                              });
            writing2Mongo.on('message', () => {
                res.end('Writing is done');
                console.log("*******************!!!!!!********************");
                transporter.sendMail(mailOptions, function(error, info){
                    if (error) {
                      console.log(error);
                    } else {
                      console.log('Email sent: ' + info.response);
                    }
                  });
            });
        }
    });
    res.status(200).end();
});

//#endregion

// Start Listening
app.listen(process.env.NODE_PORT, function () {
    console.log("UP");
});
<|endoftext|>


<commit_before>/* eslint-disable */
const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 1338 : process.env.PORT;
const path = require('path');
const express = require('express');
const app = express();

import morgan from 'morgan';
import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import { ApolloProvider } from 'react-apollo';
import { renderToStringWithData } from 'react-apollo/server';
import store from '../app/src/store.js';
import { routes } from '../app/src/routes.js';
import { createNetworkInterface } from 'apollo-client';
import Html from './utils/Html';
import createApolloClient from './utils/create-apollo-client';

const baseUrl = typeof process.env.BASE_URL !== 'undefined' ?
  process.env.BASE_URL : 'https://udacity-api.herokuapp.com/';
const apiUrl = `${baseUrl}graphql`;

app.use(morgan('combined'));

app.use(express.static(__dirname + '/public'));

app.use((req, res) => {
  match({ routes, location: req.url },
    (error, redirectLocation, renderProps) => {
      if (redirectLocation) {
        res.redirect(redirectLocation.pathname + redirectLocation.search);
      } else if (error) {
        console.error('ROUTER ERROR:', error); // eslint-disable-line no-console
        res.status(500);
      } else if (renderProps) {
        console.log(`Called match with renderProps: ${renderProps}`);
        const client = createApolloClient({
          ssrMode: true,
          networkInterface: createNetworkInterface({
            uri: apiUrl,
            credentials: 'same-origin',
            headers: req.headers,
          }),
        });

        const component = (
          <ApolloProvider client={client} store={store}>
            <RouterContext {...renderProps} />
          </ApolloProvider>
        );
        getDataFromTree(component).then((context) => {
          const content = renderToString(component);

          const html = (
            <Html
              content={content}
              scriptHash="71eea9b122d4c98f79af"
              cssHash="f0d91d73dead263291a5a8f01ecd79de"
              state={{ data: context.store.getState().apollo.data }}
            />
          );
          res.status(200).send(`<!doctype html>\n${renderToStaticMarkup(html)}`);
        }).catch(e => console.error('RENDERING ERROR:', e)); // eslint-disable-line no-console
      } else {
        res.status(404).send('Not found');
      }
    })
});

app.listen(port, '0.0.0.0', (err) => {
  if (err) {
    return console.warn(err);
  }
  return console.info(`==> 😎 Listening on port ${port}. Open http://0.0.0.0:${port}/ in your browser.`);
});
/* eslint-enable */
<commit_msg>Fix: forgot to import getDataFromTree in server app<commit_after>/* eslint-disable */
const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 1338 : process.env.PORT;
const path = require('path');
const express = require('express');
const app = express();

import morgan from 'morgan';
import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import { ApolloProvider } from 'react-apollo';
import { getDataFromTree } from 'react-apollo/server';
import store from '../app/src/store.js';
import { routes } from '../app/src/routes.js';
import { createNetworkInterface } from 'apollo-client';
import Html from './utils/Html';
import createApolloClient from './utils/create-apollo-client';

const baseUrl = typeof process.env.BASE_URL !== 'undefined' ?
  process.env.BASE_URL : 'https://udacity-api.herokuapp.com/';
const apiUrl = `${baseUrl}graphql`;

app.use(morgan('combined'));

app.use(express.static(__dirname + '/public'));

app.use((req, res) => {
  match({ routes, location: req.url },
    (error, redirectLocation, renderProps) => {
      if (redirectLocation) {
        res.redirect(redirectLocation.pathname + redirectLocation.search);
      } else if (error) {
        console.error('ROUTER ERROR:', error); // eslint-disable-line no-console
        res.status(500);
      } else if (renderProps) {
        console.log(`Called match with renderProps: ${renderProps}`);
        const client = createApolloClient({
          ssrMode: true,
          networkInterface: createNetworkInterface({
            uri: apiUrl,
            credentials: 'same-origin',
            headers: req.headers,
          }),
        });

        const component = (
          <ApolloProvider client={client} store={store}>
            <RouterContext {...renderProps} />
          </ApolloProvider>
        );
        getDataFromTree(component).then((context) => {
          const content = renderToString(component);

          const html = (
            <Html
              content={content}
              scriptHash="71eea9b122d4c98f79af"
              cssHash="f0d91d73dead263291a5a8f01ecd79de"
              state={{ data: context.store.getState().apollo.data }}
            />
          );
          res.status(200).send(`<!doctype html>\n${renderToStaticMarkup(html)}`);
        }).catch(e => console.error('RENDERING ERROR:', e)); // eslint-disable-line no-console
      } else {
        res.status(404).send('Not found');
      }
    })
});

app.listen(port, '0.0.0.0', (err) => {
  if (err) {
    return console.warn(err);
  }
  return console.info(`==> 😎 Listening on port ${port}. Open http://0.0.0.0:${port}/ in your browser.`);
});
/* eslint-enable */
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var koa = require('koa');
var router = require('koa-router')();
var serve = require('koa-static');
var koaBody = require('koa-body');
var gzip = require('koa-gzip');

var app = koa();
var iwebRouter = require('./router');

// uui定制
var customized = require("./customized");
var down = require("./down");

iwebRouter.setRouters(router, '.');

app.use(gzip());

app.use(koaBody({
  formidable: {uploadDir: __dirname},
  textLimit: '50mb',
  formLimit: '50mb'
}));

app.use(router.routes())
  .use(router.allowedMethods());

app.use(serve(path.join(__dirname, '../')));

app.listen( 8000 );

// 起服务时清楚定制生成的临时文件
deleteFolderRecursive('../dist/pages/custom/temp/');

console.log('server started at http://localhost:8000');

function deleteFolderRecursive(path) {
    var files = [];
    if( fs.existsSync(path) ) {
        files = fs.readdirSync(path);
        files.forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) {
                deleteFolderRecursive(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};
<commit_msg>app.js调整fs相关路径为：path.resolve(__dirname, p)<commit_after>var fs = require('fs');
var path = require('path');
var koa = require('koa');
var router = require('koa-router')();
var serve = require('koa-static');
var koaBody = require('koa-body');
var gzip = require('koa-gzip');

var app = koa();
var iwebRouter = require('./router');

// uui定制
var customized = require("./customized");
var down = require("./down");

iwebRouter.setRouters(router, '.');

app.use(gzip());

app.use(koaBody({
  formidable: {uploadDir: __dirname},
  textLimit: '50mb',
  formLimit: '50mb'
}));

app.use(router.routes())
  .use(router.allowedMethods());

app.use(serve(path.join(__dirname, '../')));

app.listen( 8000 );

// 起服务时清楚定制生成的临时文件
deleteFolderRecursive('../dist/pages/custom/temp/');

console.log('server started at http://localhost:8000');

function deleteFolderRecursive(path) {
    var files = [];
    if( fs.existsSync(getResolvePath(path)) ) {
        files = fs.readdirSync(getResolvePath(path));
        files.forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.statSync(getResolvePath(curPath)).isDirectory()) {
                deleteFolderRecursive(curPath);
            } else {
                fs.unlinkSync(getResolvePath(curPath));
            }
        });
        fs.rmdirSync(getResolvePath(path));
    }
};

function getResolvePath(p){
	return path.resolve(__dirname, p)
}
<|endoftext|>


<commit_before>/* Require modules */

var config = require('./config.json')
    , jsonServer = require('json-server')
    , http = require('http')
    , Router = require('node-simple-router')
    , fs = require('fs')
    , restler = require('restler')
    , isRoot = require('is-root');

/* Functions */

// Function to construct dnsmasq hosts file based on json-server's database
function updateHostsFile(callback){
  var database = require('./' + config.database);

  fs.writeFile(config.dnsmasqhostsfile, '', function(){
    database.hosts.forEach(function(host){
      fs.appendFile(config.dnsmasqhostsfile, host.ip + ' ' + host.host + '\n');
    })
  })

  // @TODO: make sure the fs functions are synchronous and callback gets called when its done.
  callback(true);
}

/* Logic */

// Function to start the RESTful json-server
function startJSONserver(){
  // Create json-server
  var server = jsonServer.create();

  // Set default middlewares (logger, static, cors and no-cache)
  server.use(jsonServer.defaults);

  // Set router
  var router = jsonServer.router(config.database);
  server.use(router);

  // Start json-server on port 3000
  server.listen(3000);
}

// Function to start the actual API server
function startAPIserver(){
  // Create router instance
  var router = new Router();

  /* Set routes */

  // GET /update - to update the hosts file manually
  router.get('/update', function(request, response) {
    updateHostsFile(function(){
      response.writeHead(200,
        {
          'Content-type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        }
      );
      response.end('{"success": true}');
    });
  });

  // GET /show - to list all host entries
  router.get('/show', function(request, response) {
    restler.get('http://localhost:3000/hosts').on('complete', function(restData) {
      response.writeHead(200,
        {
          'Content-type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        }
      );
      response.end(JSON.stringify(restData));
    });
  });

  // POST /add - to add new hosts
  router.post('/add', function(request, response) {
    // First make sure we haven't already added the host
    restler.get('http://localhost:3000/hosts?host=' + request.post.host).on('complete', function(restData) {
      // Host didnt already exist if object is empty => continue
      console.log(restData.length);
      if(restData.length == 0){
        // Add new host via REST API
        restler.post('http://localhost:3000/hosts', {
          data: {
            host: request.post.host,
            ip: request.post.ip
          }
        }).on('complete', function(restData, restResponse) {
          if (restResponse.statusCode == 201) {
            // Return response
            response.writeHead(200,
              {
                'Content-type': 'application/json',
                'Access-Control-Allow-Origin': '*',
              }
            );
            // response.end(restResponse.rawEncoded);
            response.end('{"success": true}');
          }
        });
      } else {
        // Return response
        response.writeHead(200,
          {
            'Content-type': 'application/json',
            'Access-Control-Allow-Origin': '*',
          }
        );
        // Return error message
        response.end('{"success": false, "payload":{ "error": "Host already exist"}}');
      }
    });
  });

  // Create HTTP server
  var server = http.createServer(router);

  // Start server on port 4000
  server.listen(4000);
  console.log('API server successfuly started: http://localhost:4000');
}

// Check if run as root
if (!isRoot()){
  console.log('Error: This application needs root permissions! Make sure to run as root user.');
  process.exit(1);
} else {
  startJSONserver();
  startAPIserver();
}
<commit_msg>Use === to compare<commit_after>/* Require modules */

var config = require('./config.json')
    , jsonServer = require('json-server')
    , http = require('http')
    , Router = require('node-simple-router')
    , fs = require('fs')
    , restler = require('restler')
    , isRoot = require('is-root');

/* Functions */

// Function to construct dnsmasq hosts file based on json-server's database
function updateHostsFile(callback){
  var database = require('./' + config.database);

  fs.writeFile(config.dnsmasqhostsfile, '', function(){
    database.hosts.forEach(function(host){
      fs.appendFile(config.dnsmasqhostsfile, host.ip + ' ' + host.host + '\n');
    })
  })

  // @TODO: make sure the fs functions are synchronous and callback gets called when its done.
  callback(true);
}

/* Logic */

// Function to start the RESTful json-server
function startJSONserver(){
  // Create json-server
  var server = jsonServer.create();

  // Set default middlewares (logger, static, cors and no-cache)
  server.use(jsonServer.defaults);

  // Set router
  var router = jsonServer.router(config.database);
  server.use(router);

  // Start json-server on port 3000
  server.listen(3000);
}

// Function to start the actual API server
function startAPIserver(){
  // Create router instance
  var router = new Router();

  /* Set routes */

  // GET /update - to update the hosts file manually
  router.get('/update', function(request, response) {
    updateHostsFile(function(){
      response.writeHead(200,
        {
          'Content-type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        }
      );
      response.end('{"success": true}');
    });
  });

  // GET /show - to list all host entries
  router.get('/show', function(request, response) {
    restler.get('http://localhost:3000/hosts').on('complete', function(restData) {
      response.writeHead(200,
        {
          'Content-type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        }
      );
      response.end(JSON.stringify(restData));
    });
  });

  // POST /add - to add new hosts
  router.post('/add', function(request, response) {
    // First make sure we haven't already added the host
    restler.get('http://localhost:3000/hosts?host=' + request.post.host).on('complete', function(restData) {
      // Host didnt already exist if object is empty => continue
      console.log(restData.length);
      if(restData.length === 0){
        // Add new host via REST API
        restler.post('http://localhost:3000/hosts', {
          data: {
            host: request.post.host,
            ip: request.post.ip
          }
        }).on('complete', function(restData, restResponse) {
          if (restResponse.statusCode === 201) {
            // Return response
            response.writeHead(200,
              {
                'Content-type': 'application/json',
                'Access-Control-Allow-Origin': '*',
              }
            );
            // response.end(restResponse.rawEncoded);
            response.end('{"success": true}');
          }
        });
      } else {
        // Return response
        response.writeHead(200,
          {
            'Content-type': 'application/json',
            'Access-Control-Allow-Origin': '*',
          }
        );
        // Return error message
        response.end('{"success": false, "payload":{ "error": "Host already exist"}}');
      }
    });
  });

  // Create HTTP server
  var server = http.createServer(router);

  // Start server on port 4000
  server.listen(4000);
  console.log('API server successfuly started: http://localhost:4000');
}

// Check if run as root
if (!isRoot()){
  console.log('Error: This application needs root permissions! Make sure to run as root user.');
  process.exit(1);
} else {
  startJSONserver();
  startAPIserver();
}
<|endoftext|>