app.js
This file
Path
examples/auth/app.js
122 lines · 3.2 KiB · JavaScript
Last changed by
hmac for auth exampleTj Holowaychukbefore adoption8ca0a45
History of this fileTake it
The walk stopped after 200 commits: lines older than 99b49d2 point at it.
updated docsTj Holowaychukbefore adoption99b49d2
lines 1–37why, one step back12/**3 * Module dependencies.4 */56var express = require('../../lib/express')7 , crypto = require('crypto');89var app = express.createServer(10 express.bodyParser()11 , express.cookieParser()12 , express.session({ secret: 'keyboard cat' })13);1415app.set('views', __dirname + '/views');16app.set('view engine', 'ejs');1718// Message helper, ideally we would use req.flash()19// however this is more light-weight for an example2021app.dynamicHelpers({22 message: function(req){23 var err = req.session.error24 , msg = req.session.success;25 delete req.session.error;26 delete req.session.success;27 if (err) return '<p class="msg error">' + err + '</p>';28 if (msg) return '<p class="msg success">' + msg + '</p>';29 }30});3132// Generate a salt for the user to prevent rainbow table attacks3334var users = {35 tj: {36 name: 'tj'37 , salt: 'randomly-generated-salt'hmac for auth exampleTj Holowaychukbefore adoption8ca0a45
line 38why, one step back38 , pass: hash('foobar', 'randomly-generated-salt')updated docsTj Holowaychukbefore adoption99b49d2
lines 39–43why, one step back39 }40};4142// Used to generate a hash of the plain-text password + salt43hmac for auth exampleTj Holowaychukbefore adoption8ca0a45
lines 44–45why, one step back44function hash(msg, key) {45 return crypto.createHmac('sha256', key).update(msg).digest('hex');updated docsTj Holowaychukbefore adoption99b49d2
lines 46–53why, one step back46}47// Authenticate using our plain-object database of doom!4849function authenticate(name, pass, fn) {50 var user = users[name];51 // query the db for the given username52 if (!user) return fn(new Error('cannot find user'));53 // apply the same algorithm to the POSTed password, applyinghmac for auth exampleTj Holowaychukbefore adoption8ca0a45
line 54why, one step back54 // the hash against the pass / salt, if there is a match weupdated docsTj Holowaychukbefore adoption99b49d2
line 55why, one step back55 // found the userhmac for auth exampleTj Holowaychukbefore adoption8ca0a45
line 56why, one step back56 if (user.pass == hash(pass, user.salt)) return fn(null, user);updated docsTj Holowaychukbefore adoption99b49d2
lines 57–122why, one step back57 // Otherwise password is invalid58 fn(new Error('invalid password'));59}6061function restrict(req, res, next) {62 if (req.session.user) {63 next();64 } else {65 req.session.error = 'Access denied!';66 res.redirect('/login');67 }68}6970function accessLogger(req, res, next) {71 console.log('/restricted accessed by %s', req.session.user.name);72 next();73}7475app.get('/', function(req, res){76 res.redirect('/login');77});7879app.get('/restricted', restrict, accessLogger, function(req, res){80 res.send('Wahoo! restricted area');81});8283app.get('/logout', function(req, res){84 // destroy the user's session to log them out85 // will be re-created next request86 req.session.destroy(function(){87 res.redirect('home');88 });89});9091app.get('/login', function(req, res){92 if (req.session.user) {93 req.session.success = 'Authenticated as ' + req.session.user.name94 + ' click to <a href="/logout">logout</a>. '95 + ' You may now access <a href="/restricted">/restricted</a>.';96 }97 res.render('login');98});99100app.post('/login', function(req, res){101 authenticate(req.body.username, req.body.password, function(err, user){102 if (user) {103 // Regenerate session when signing in104 // to prevent fixation 105 req.session.regenerate(function(){106 // Store the user's primary key 107 // in the session store to be retrieved,108 // or in this case the entire user object109 req.session.user = user;110 res.redirect('back');111 });112 } else {113 req.session.error = 'Authentication failed, please check your '114 + ' username and password.'115 + ' (use "tj" and "foobar")';116 res.redirect('back');117 }118 });119});120121app.listen(3000);122console.log('Express started on port 3000');