app.js
This file
Path
examples/auth/app.js
126 lines · 3.5 KiB · JavaScript
Last changed by
Merge branch 'features/route-middleware'Tj Holowaychukbefore adoptionae75153
History of this fileTake it
Merge branch 'auth-example'Tj Holowaychukbefore adoption5cf248c
line 1why, one step back1Exposing ./support libs to examplesTj Holowaychukbefore adoption9b7470d
lines 2–4why, one step back2// Expose modules in ./support for demo purposes3require.paths.unshift(__dirname + '/../../support');4Merge branch 'auth-example'Tj Holowaychukbefore adoption5cf248c
lines 5–64why, one step back5/**6 * Module dependencies.7 */89var express = require('../../lib/express'),10 crypto = require('crypto');1112var app = express.createServer();1314app.set('views', __dirname + '/views');15app.set('view engine', 'ejs');1617app.use(express.bodyDecoder());18app.use(express.cookieDecoder());19app.use(express.session());2021// Message helper, ideally we would use req.flash()22// however this is more light-weight for an example2324app.dynamicHelpers({25 message: function(req){26 var err = req.session.error,27 msg = req.session.success;28 delete req.session.error;29 delete req.session.success;30 if (err) return '<p class="msg error">' + err + '</p>';31 if (msg) return '<p class="msg success">' + msg + '</p>';32 }33});3435// Generate a salt for the user to prevent rainbow table attacks3637var users = {38 tj: {39 name: 'tj',40 salt: 'randomly-generated-salt',41 pass: md5('foobar' + 'randomly-generated-salt')42 }43};4445// Used to generate a hash of the plain-text password + salt4647function md5(str) {48 return crypto.createHash('md5').update(str).digest('hex');49}5051// Authenticate using our plain-object database of doom!5253function authenticate(name, pass, fn) {54 var user = users[name];55 // query the db for the given username56 if (!user) return fn(new Error('cannot find user'));57 // apply the same algorithm to the POSTed password, applying58 // the md5 against the pass / salt, if there is a match we59 // found the user60 if (user.pass == md5(pass + user.salt)) return fn(null, user);61 // Otherwise password is invalid62 fn(new Error('invalid password'));63}64Merge branch 'features/route-middleware'Tj Holowaychukbefore adoptionae75153
lines 65–78why, one step back65function restrict(req, res, next) {66 if (req.session.user) {67 next();68 } else {69 req.session.error = 'Access denied!';70 res.redirect('/login');71 }72}7374function accessLogger(req, res, next) {75 console.log('/restricted accessed by %s', req.session.user.name);76 next();77}78Merge branch 'auth-example'Tj Holowaychukbefore adoption5cf248c
lines 79–82why, one step back79app.get('/', function(req, res){80 res.redirect('/login');81});82Merge branch 'features/route-middleware'Tj Holowaychukbefore adoptionae75153
lines 83–86why, one step back83app.get('/restricted', restrict, accessLogger, function(req, res){84 res.send('Wahoo! restricted area');85});86Merge branch 'auth-example'Tj Holowaychukbefore adoption5cf248c
lines 87–97why, one step back87app.get('/logout', function(req, res){88 // destroy the user's session to log them out89 // will be re-created next request90 req.session.destroy(function(){91 res.redirect('home');92 });93});9495app.get('/login', function(req, res){96 if (req.session.user) {97 req.session.success = 'Authenticated as ' + req.session.user.nameMerge branch 'features/route-middleware'Tj Holowaychukbefore adoptionae75153
lines 98–99why, one step back98 + ' click to <a href="/logout">logout</a>. '99 + ' You may now access <a href="/restricted">/restricted</a>.';Merge branch 'auth-example'Tj Holowaychukbefore adoption5cf248c
lines 100–113why, one step back100 }101 res.render('login');102});103104app.post('/login', function(req, res){105 authenticate(req.body.username, req.body.password, function(err, user){106 if (user) {107 // Regenerate session when signing in108 // to prevent fixation 109 req.session.regenerate(function(){110 // Store the user's primary key 111 // in the session store to be retrieved,112 // or in this case the entire user object113 req.session.user = user;Typo in auth exampleTj Holowaychukbefore adoption72765ba
line 114why, one step back114 res.redirect('back');Merge branch 'auth-example'Tj Holowaychukbefore adoption5cf248c
lines 115–119why, one step back115 });116 } else {117 req.session.error = 'Authentication failed, please check your '118 + ' username and password.'119 + ' (use "tj" and "foobar")';Typo in auth exampleTj Holowaychukbefore adoption72765ba
line 120why, one step back120 res.redirect('back');Merge branch 'auth-example'Tj Holowaychukbefore adoption5cf248c
lines 121–126why, one step back121 }122 });123});124125app.listen(3000);126console.log('Express started on port 3000');