<commit_before>
// app.js
// Copyright QILabs.org
// by @f03lipe

// This is the main server script.
// Set up everything.

// Import environment keys (if in development)
try { require('./config/env.js') } catch (e) {}

// Libraries
var _
,	express = require('express')				// *THE* nodejs framework
,	passport= require('passport') 				// Authentication framework
,	swig 	= require('swig')					// template language processor
,	expressWinston = require('express-winston')
,	winston = require('winston')
// Utils
,	pathLib = require('path')
,	fsLib 	= require('fs')
,	_ 		= require('underscore')
// Configuration
,	mongoose = require('./config/mongoose.js') // Set-up mongoose
;

var app = module.exports = express();
require('./config/app_config.js')(app);
require('./config/passport.js')();

/*
** Template engines and static files. **/
app.engine('html', swig.renderFile);
app.set('view engine', 'html'); 			// make '.html' the default
app.set('views', app.config.viewsRoot); 	// set views for error and 404 pages
app.set('view cache', false);
app.use(require('connect').compress());
app.use(express.static(pathLib.join(app.config.staticRoot, 'robots.txt')));
app.use(express.static(pathLib.join(app.config.staticRoot, 'people.txt')));
app.use(express.favicon(pathLib.join(app.config.staticRoot, 'favicon.ico')));

if (app.get('env') === 'development') {
	swig.setDefaults({ cache: false });
}

/******************************************************************************/
/* BEGINNING of a DO_NO_TOUCH_ZONE ********************************************/
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(require('express-validator')());
app.use(app.config.staticUrl, express.static(app.config.staticRoot));
app.use(express.cookieParser());
app.use(express.session({
	secret: process.env.SESSION_SECRET || 'mysecret',
	maxAge: new Date(Date.now() + 3600000),
	store: 	new (require('connect-mongo')(express))({
		mongoose_connection: mongoose.connection
	})
}));
app.use(express.csrf());
/** END of a DO_NO_TOUCH_ZONE -----------------------------------------------**/
/**--------------------------------------------------------------------------**/


/******************************************************************************/
/** BEGINNING of a SHOULD_NOT_TOUCH_ZONE **************************************/
app.use(function(req, res, next){
	res.locals.token = req.session._csrf; // Add csrf token to views.
	next();
});
app.use(require('connect-flash')());
app.use(passport.initialize());
app.use(passport.session());
/** END of a SHOULD_NOT_TOUCH_ZONE ------------------------------------------**/
/**--------------------------------------------------------------------------**/

app.use(require('./config/middlewares/flash_messages.js'));
app.use(require('./config/middlewares/local_user.js'));

app.use(function(req, res, next) {
	res.endJson = function (data) {
		res.end(JSON.stringify(data));
	};

	res.render404 = function () {
		res.status(404);
		if (req.accepts('html')) { // respond with html page;
			res.render('pages/404', { url: req.url, user: req.user });
		} else if (req.accepts('json')) { // respond with json;
			res.send({ error: true, name: 'Notfound' });
		}
	};

	res.handleErrResult = function (callback) {
		var self = this;
		return function (err, result) {
			if (err) {
				res.render404();
			} else if (!result) {
				res.render404();
			} else {
				callback.apply(self, [].splice.call(arguments,1));
			}
		}
	};

	req.paramToObjectId = function (param) {
		try {
			return new mongoose.Types.ObjectId.createFromHexString(req.params[param])
		} catch (e) {
			res.status(400).endJson({error:true, name:'InvalidId'})
			return false;
		}
	};

	req.logMe = function () {
		console.log.apply(console, ["<"+req.user.username+">:"].concat([].slice.call(arguments)));
	};

	next();
});


/******************************************************************************/
/** Logging (must be after app.use(app.router)) *******************************/
// app.use(function (req, res, next) {<commit_msg>Improved paramToObjectId<commit_after>
// app.js
// Copyright QILabs.org
// by @f03lipe

// This is the main server script.
// Set up everything.

// Import environment keys (if in development)
try { require('./config/env.js') } catch (e) {}

// Libraries
var _
,	express = require('express')				// *THE* nodejs framework
,	passport= require('passport') 				// Authentication framework
,	swig 	= require('swig')					// template language processor
,	expressWinston = require('express-winston')
,	winston = require('winston')
// Utils
,	pathLib = require('path')
,	fsLib 	= require('fs')
,	_ 		= require('underscore')
// Configuration
,	mongoose = require('./config/mongoose.js') // Set-up mongoose
;

var app = module.exports = express();
require('./config/app_config.js')(app);
require('./config/passport.js')();

/*
** Template engines and static files. **/
app.engine('html', swig.renderFile);
app.set('view engine', 'html'); 			// make '.html' the default
app.set('views', app.config.viewsRoot); 	// set views for error and 404 pages
app.set('view cache', false);
app.use(require('connect').compress());
app.use(express.static(pathLib.join(app.config.staticRoot, 'robots.txt')));
app.use(express.static(pathLib.join(app.config.staticRoot, 'people.txt')));
app.use(express.favicon(pathLib.join(app.config.staticRoot, 'favicon.ico')));

if (app.get('env') === 'development') {
	swig.setDefaults({ cache: false });
}

/******************************************************************************/
/* BEGINNING of a DO_NO_TOUCH_ZONE ********************************************/
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(require('express-validator')());
app.use(app.config.staticUrl, express.static(app.config.staticRoot));
app.use(express.cookieParser());
app.use(express.session({
	secret: process.env.SESSION_SECRET || 'mysecret',
	maxAge: new Date(Date.now() + 3600000),
	store: 	new (require('connect-mongo')(express))({
		mongoose_connection: mongoose.connection
	})
}));
app.use(express.csrf());
/** END of a DO_NO_TOUCH_ZONE -----------------------------------------------**/
/**--------------------------------------------------------------------------**/


/******************************************************************************/
/** BEGINNING of a SHOULD_NOT_TOUCH_ZONE **************************************/
app.use(function(req, res, next){
	res.locals.token = req.session._csrf; // Add csrf token to views.
	next();
});
app.use(require('connect-flash')());
app.use(passport.initialize());
app.use(passport.session());
/** END of a SHOULD_NOT_TOUCH_ZONE ------------------------------------------**/
/**--------------------------------------------------------------------------**/

app.use(require('./config/middlewares/flash_messages.js'));
app.use(require('./config/middlewares/local_user.js'));

app.use(function(req, res, next) {
	res.endJson = function (data) {
		res.end(JSON.stringify(data));
	};

	res.render404 = function () {
		res.status(404);
		if (req.accepts('html')) { // respond with html page;
			res.render('pages/404', { url: req.url, user: req.user });
		} else if (req.accepts('json')) { // respond with json;
			res.send({ error: true, name: 'Notfound' });
		}
	};

	res.handleErrResult = function (callback) {
		var self = this;
		return function (err, result) {
			if (err) {
				res.render404();
			} else if (!result) {
				res.render404();
			} else {
				callback.apply(self, [].splice.call(arguments,1));
			}
		}
	};

	req.paramToObjectId = function (param) {
		try {
			return new mongoose.Types.ObjectId.createFromHexString(req.params[param])
		} catch (e) {
			res.status(400).endJson({error:true, name:'InvalidId', arg:{param:param}})
			return false;
		}
	};

	req.logMe = function () {
		console.log.apply(console, ["<"+req.user.username+">:"].concat([].slice.call(arguments)));
	};

	next();
});


/******************************************************************************/
/** Logging (must be after app.use(app.router)) *******************************/
// app.use(function (req, res, next) {
{'fraction_non_alphanumeric': 0.31398773006134967, 'fraction_numerical': 0.007607361963190184, 'mean_word_length': 3.5258189894503054, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1239382', 'n_tokens_mistral': 2696, 'n_tokens_neox': 2520, 'n_words': 466}