Created
January 22, 2013 02:16
-
-
Save sirkitree/4591482 to your computer and use it in GitHub Desktop.
Sample code for validating captcha using express.session() and the captchagen module.
This file contains hidden or 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
| // 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}); | |
| } | |
| }; |
This file contains hidden or 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
| /** | |
| * 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); | |
| }); |
This file contains hidden or 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
| 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