Spotdekho “app.js” file


 

/**
 * Module dependencies.
 */
var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var lusca = require('lusca');
var methodOverride = require('method-override');
var dotenv = require('dotenv');
var MongoStore = require('connect-mongo/es5')(session);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var expressValidator = require('express-validator');
var sass = require('node-sass-middleware');
var multer = require('multer');
var upload = multer({ dest: path.join(__dirname, 'uploads') });
var favicon = require('serve-favicon');
var fs = require('fs');
var mongo = require('mongoskin');
var passport = require('passport');
var force = require('express-force-domain');

/**
 * Create Express server.
 */

var app = express();
var options = {
      key: fs.readFileSync(__dirname +'/cert/privatekey.pem'),
      cert: fs.readFileSync(__dirname +'/cert/certificate.pem')
    };
var uuid = require('shortid');
var pass =  require('./routes/pass');
var hasher  = new pass();
var db;

/*
app.use(function(req, res, next) {
  if (req.headers.host.split(':', 1)[0].toLowerCase() === 'spotdekho.com'){
    res.header('Location', 'http://www.spotdekho.com' + req.url );
    return res.send(301);
  }
  next();
});
app.use(function(req, res, next) {
  if (req.headers.host.split(':', 1)[0].toLowerCase() === '104.199.224.2'){
    res.header('Location', 'http://www.spotdekho.com' + req.url );
    return res.send(301);
  }
  next();
});
*/

app.use( force('https://www.spotdekho.com') );

/**
 * Connect to MongoDB, "spotdekho" db which is storing spot/venue details
 */

process.argv.forEach(function (val, index, array) {
    if(index == 2 && val == "local"){
        db = mongo.db("mongodb://localhost:27017/spotdekho", {native_parser:true});
        app.set('server','local');
    }else{
        db = mongo.db("mongodb://localhost:27017/spotdekho", {native_parser:true});
        app.set('server','digital');
    }
});

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 *
 * Default path: .env (You can remove the path argument entirely, after renaming `.env.example` to `.env`)
 */
dotenv.load({ path: '.env' });

/**
 * Connect to MongoDB, "login" db which is storing login info details
 */
mongoose.connect(process.env.MONGODB || process.env.MONGOLAB_URI);
mongoose.connection.on('error', function() {
  process.exit(1);
});

/**
 * Express configuration.
 */
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(compress());
app.use(sass({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  sourceMap: true
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET,
  store: new MongoStore({
    url: process.env.MONGODB || process.env.MONGOLAB_URI,
    autoReconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function(req, res, next) {
  if (req.path ===  '/admin/postcomment/:id' || '/contactus'  || '/spotitReview' || '/spotit/adLogin' || '/spotitVenue' || '/spotitOffer' || '/spotitsubList') {
    next();
  } else {
    lusca.csrf()(req, res, next);
  }
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use(function(req, res, next) {
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  // After successful login, redirect back to /api, /contact or /
  if (/(api)|(^\/$)/i.test(req.path)) {
    req.session.returnTo = req.path;
  }
  next();
});

app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});
// Session-persisted message middleware

// upload image in the backside view -- to upload new pics of spots in server
app.post('/uploadPic', upload.single('upl'), function(req,res){
  var file = __dirname + "/uploads/" + req.file.originalname;
     fs.readFile( req.file.path, function (err, data) {
          fs.writeFile(file, data, function (err) {
           if( err ){
                response = {
                     message: 'Sorry, file couldn\'t be uploaded.',
                     filename: req.file.originalname
                };
           }else{
                 response = {
                     message: 'File uploaded successfully',
                     filename: req.file.originalname
                };
            }
            res.end( JSON.stringify( response ) );
         });
     });
});

// END - of upload image in the backside view -- to upload new pics of spots in server


app.use(function(req, res, next){
  var err = req.session.error;
  var msg = req.session.success;
  delete req.session.error;
  delete req.session.success;
  res.locals.message = '';
  if (err) res.locals.message = '<p class="msg error">' + err + '</p>';
  if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';
  next();
});

var app_secure = require('https');

app_secure.createServer(options, app).listen(process.env.PORT_SECURE || 3000);


/**
 * Controllers (route handlers).
 */
var index = require('./routes/index')(app,app_secure,hasher);
var venues = require('./routes/venues')(app,app_secure,uuid);
var offers = require('./routes/offers')(app,app_secure,uuid);
var subList = require('./routes/subList')(app,app_secure,uuid);
var review = require('./routes/review')(app,app_secure,uuid);


/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Page Not Found');
    err.status = 404;
    next(err);
});


// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

app.get('*',function(req,res,next){
  if(req.headers['x-forwarded-proto']!='https')
    res.redirect('https://' + req.header('Host') + req.url);
  else
    next() /* Continue to other routes if we're not redirecting */
})

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports= app;

 

Leave a Reply

Your email address will not be published. Required fields are marked *