How to use the express.csrf function in express

To help you get started, we’ve selected a few express examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pyvandenbussche / lov / config / express.js View on Github external
/**
 * Module dependencies.
 */

var express = require('express')
  , csrf = express.csrf()
  , mongoStore = require('connect-mongo')(express)
  , flash = require('connect-flash')
  , winston = require('winston')
  , helpers = require('view-helpers')
  , pkg = require('../package.json')

var env = process.env.NODE_ENV || 'development'

module.exports = function (app, config, passport) {

  app.set('showStackError', true)

  // should be placed before express.static
  app.use(express.compress({
    filter: function (req, res) {
      return /json|text|javascript|css/.test(res.getHeader('Content-Type'))
github ohmlabs / ohm / server / ghost / core / server / middleware / middleware.js View on Github external
conditionalCSRF: function (req, res, next) {
        var csrf = express.csrf();
        // CSRF is needed for admin only
        if (res.isAdmin) {
            csrf(req, res, next);
            return;
        }
        next();
    },
github kevbook / Base-Node.js-App / app.js View on Github external
strategies : [
		auth.Facebook({
 			appId : config.fb.appId, 
 			appSecret: config.fb.appSecret, 
 			scope: "email, user_birthday",
 			callback: config.fb.callback
	}),
		auth.Twitter({
			consumerKey: config.twitter.consumerKey, 
			consumerSecret: config.twitter.consumerSecret
		})
	],
	trace: true,
}));

app.use(express.csrf());
//app.use(subdomain({base:'127.0.0.1', removeWWW: true}));
app.use(app.router);
app.use(errorHandler.notFound); // 404 handler
app.use(errorHandler.serverError); // 500 handler


/**
 * app booter
 */
require('./boot/db')(app);
require('./boot/router')(app);
app.dynamicHelpers(require('./boot/dynamichelpers'));


logger.log('server_start', 'server started on port ' + port, true);
github kig / message / app.js View on Github external
app.set('view engine', 'dot');
app.engine('dot', doT.__express);
app.use(express.logger('dev'));
app.use(connect.compress());
app.use(stylus.middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieSession({
	secret: config.sessionSecret,
	maxAge: new Date(Date.now() + 14*24*3600*1000)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.csrf());
app.use(app.router);

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


// Set up authentication strategies for Passport.js

var passportAuth = function(accessToken, refreshToken, profile, done) {
	profile.username = profile.provider + '-' + profile.id;
	schema.Person.findOrCreate(profile.username, profile, function(err, user) {
		if (err) { 
			done(err);
		} else {
github ericf / open-marriage / app.js View on Github external
});

// -- Middleware ---------------------------------------------------------------

if (config.isDevelopment) {
    app.use(express.logger('tiny'));
}

app.use(express.compress());
app.use(express.favicon(config.dirs.pub + '/favicon.ico'));
app.use(express.cookieParser());
app.use(express.cookieSession(config.session));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.csrf());
app.use(middleware.csrfToken);
app.use(middleware.invitation);
app.use(middleware.pjax('bare'));
app.use(middleware.checkDate);
app.use(app.router);
app.use(middleware.slash());
app.use(express.static(config.dirs.pub));
app.use(middleware.notfound);

if (config.isDevelopment) {
    app.use(express.errorHandler({
        dumpExceptions: true,
        showStack     : true
    }));
} else {
    app.use(middleware.error);
github rorymadden / angular-neo4j / server / index.js View on Github external
app.use(passport.initialize());
  app.use(passport.session());

  //csrf protection
  // add a check for the csrf token in the req.headers['x-xsrf-token'] - angular places it here
  // all other checks are the default express behaviour
  if(env !== 'test') {
    var csrfValue = function(req) {
      var token = (req.body && req.body._csrf)
        || (req.query && req.query._csrf)
        || (req.headers['x-csrf-token'])
        || (req.headers['x-xsrf-token']);
      return token;
    };
    app.use(express.csrf({value: csrfValue}));
    // put the csrf token from the header into the cookie for angular to pickup
    app.use(function(req, res, next) {
      res.cookie('XSRF-TOKEN', req.session._csrf);
      next();
    });
  }


  app.use(express.compress());

  // staticCache has been deprecated.
  // TODO: investigate varnish / nginx for caching
  // app.use(express.staticCache());


  // host dev files if in dev mode
github DanialK / advanced-security-in-backbone / app.js View on Github external
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.cookieParser('NOTHING'));
app.use(express.session());
// This middleware adds _csrf to 
// our session
// req.session._csrf
app.use(express.csrf());
app.use(express.methodOverride());
app.use(app.router);
app.use(function(req, res, next){
	res.setHeader('X-CSRF-Token', req.session._csrf);
	next();
});
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}


/* ------------------------------------------------
	Application Routes
   ------------------------------------------------*/
github mozilla / thimble.mozilla.org / services / login.webmaker.org / app / http / routes.js View on Github external
module.exports = function (http, modelsController, webmakerAuth) {
  var qs = require("querystring"),
    express = require("express"),
    basicAuth = express.basicAuth,
    csrf = express.csrf(),
    env = require("../../config/environment"),
    routes = {
      site: require("./controllers/site"),
      user: require("./controllers/user")(modelsController),
      user2: require("./controllers/user2"),
      user3: require("./controllers/user3")
    },
    userList = env.get("ALLOWED_USERS"),
    authMiddleware = basicAuth(function (user, pass) {
      if (typeof userList === "string") {
        var arrList = {};
        var extractUserPass = function (pair) {
          var terms = pair.split(":");
          arrList[terms[0]] = terms[1];
        };
        userList.split(",").forEach(extractUserPass);
github phoenixlzx / moedns / app.js View on Github external
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser(config.cookieSecret));
app.use(express.session({
    secret: config.cookieSecret,
    cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
    store: new MongoStore({
        db: config.mongodb,
        clear_interval: 3600
    })
}));
app.use(express.csrf());
app.use(i18n.init);
app.use(flash());
app.use(app.router);
app.use(lessMiddleware(path.join(__dirname, '/public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res) {
    req.flash('error', res.__('404'));
    res.status(404);
    res.render('index', {
        siteName: config.siteName,
        siteTagline: config.siteTagline,
        title: res.__('HOME') + ' - ' + config.siteName,
        allowReg: config.allowReg,
        user: req.session.user,
        success: req.flash('success').toString(),
github chemzqm / blog / lib / post / index.js View on Github external
var moment = require('moment');
var marked = require('color-marked');
var path = require('path');
var fs = require('fs');
var util = require('../util');


app.set('views', __dirname);
app.set('view engine', 'jade');

moment.lang('zh-cn');

var authenticate = util.authenticate;
var loadPost = util.loadPost;

app.get('/v/:number', express.csrf(), loadPost,function(req, res, next) {
  var post = req.Post;
  post.html = marked(post.content);
  res.render('index',{
    title: post.title,
    post: post,
    moment: moment,
    marked: marked,
    csrf: req.session._csrf
  });
});

app.post('/uploadimg', express.csrf(), function(req, res, next) {
  var file = req.files.uploadingFile;
  var name = file.name;
  var targetPath = file.path + path.extname(name);
  fs.rename(file.path, targetPath, function(err) {