Created
May 11, 2013 13:21
-
-
Save gildean/5559948 to your computer and use it in GitHub Desktop.
Express with csrf tokens. (Note: the main.jade goes to a dir named 'views' under the dir where the app.js resides.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'), | |
app = express(), | |
server = require('http').createServer(app).listen(9999); | |
app.set('view engine', 'jade'); | |
app.set('views', __dirname + '/views'); | |
app.use(express.bodyParser()); | |
app.use(express.cookieParser()); | |
app.use(express.session({ secret: 'secret' })); | |
app.use(express.csrf()); | |
app.locals.pretty = true; | |
app.use(getToken); | |
app.post('/save', saveEdit); | |
app.get('/', mainView); | |
app.use(function (req, res, next) { | |
next(new Error('Not found')); | |
}); | |
app.use(function (err, req, res, next) { | |
res.send((err.status || 500), err.message); | |
}); | |
function getToken(req, res, next) { | |
res.locals.token = req.session._csrf; | |
next(); | |
} | |
function saveEdit(req, res, next) { | |
res.send(200, 'Post had the correct token: ' + req.body._csrf + ' and the value: ' + req.body.name); | |
} | |
function mainView(req, res, next) { | |
res.render('main'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!!! | |
body | |
h2 correct post | |
form(action="/save", method="post") | |
input(type="text", name="name", placeholder="name") | |
input(type="hidden", name="_csrf", value="#{token}") | |
input(type="submit", value="save correct") | |
h2 incorrect post | |
form(action="/save", method="post") | |
input(type="text", name="name", placeholder="name") | |
input(type="submit", value="save incorrect") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment