Skip to content

Instantly share code, notes, and snippets.

@sirkitree
Created January 22, 2013 02:16
Show Gist options
  • Select an option

  • Save sirkitree/4591482 to your computer and use it in GitHub Desktop.

Select an option

Save sirkitree/4591482 to your computer and use it in GitHub Desktop.
Sample code for validating captcha using express.session() and the captchagen module.
// POST
exports.addPost = function(req, res, next) {
// the user's answer
var theirCaptcha = req.body.captcha;
if (!theirCaptcha) {
return next("Missing captcha input");
}
if (theirCaptcha == req.session.captcha) {
// valid human
delete req.session.captcha;
req.session.isHuman = true;
// push to posts
data.posts.push(req.body);
res.json(req.body);
} else {
// invalid human
delete req.session.isHuman;
req.session.isHuman = false;
// notify user that catcha is invalid
res.json({captcha: false});
}
};
/**
* Module dependencies.
*/
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api');
var app = module.exports = express();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {
layout: false
});
app.use(express.bodyParser());
app.use(express.methodOverride());
// it's imperative to have .cookieParser() and .session() before .static()
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
// Routes
app.get('/captcha.png', routes.captcha);
// Start server
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
exports.captcha = function(req, res, next) {
var c = require('captchagen'),
captcha = c.generate(),
sess = req.session;
sess.captcha = captcha.text();
res.type('image/png');
res.end(captcha.buffer());
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment