Skip to content

Instantly share code, notes, and snippets.

@vickonrails
Created February 5, 2018 09:15
Show Gist options
  • Save vickonrails/ebeae894f7e3cabf4ea8ab37be403834 to your computer and use it in GitHub Desktop.
Save vickonrails/ebeae894f7e3cabf4ea8ab37be403834 to your computer and use it in GitHub Desktop.
const express = require('express'),
body_parser = require('body-parser'),
hbs = require('express-handlebars').create({defaultLayout: 'main',extname:'hbs'});
session = require('express-session'),
csurf = require('csurf'),
app = express();
//setting the app port
app.set('port', process.env.PORT || 3000);
//configuring the app for handlebars
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');
//setting up a session csrf
app.use(session({
name: 'My session csrf',
secret: 'My super session secret',
cookie: {
maxAge: null,
httpOnly: true,
secure: true
}
})
);
app.use(csurf());
//configuring the body parser middleware
app.use(body_parser.urlencoded());
//Route to login
app.get('/login', (request,response)=>{
console.log(request.csrfToken());
response.render('login',{
csrfToken : request.csrfToken(),
title: 'Login'
});
});
app.listen(3000,()=>console.log('Express app started at port 3000'));
<b>Here's the generated csrf token</b> ({{csrfToken}})<br><br>
<form method='POST' action='/process'>
<!-- We pass the _csrf token as a hidden input -->
<input type='hidden' name='_csrf' csurf={{csrfToken}}/>
<input type='text' name='name'/>
<input type='submit'/>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment