Skip to content
Myr

app.js

This file

Path

examples/auth/app.js

124 lines · 3.3 KiB · JavaScript

Last changed by

docsTj Holowaychukbefore adoption579836e

History of this file

Take it

The walk stopped after 200 commits: lines older than fda31b7 point at it.

Added simple web-service exampleTj Holowaychukbefore adoptionfda31b7

lines 1–32why, one step back
1
2/**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 attacks

docsTj Holowaychukbefore adoption579836e

lines 33–34why, one step back
33// for better security take a look at the bcrypt c++ addon:
34// https://github.com/ncb000gt/node.bcrypt.js

Added simple web-service exampleTj Holowaychukbefore adoptionfda31b7

lines 35–124why, one step back
35
36var users = {37 tj: {38 name: 'tj'39 , salt: 'randomly-generated-salt'40 , pass: hash('foobar', 'randomly-generated-salt')41 }42};4344// Used to generate a hash of the plain-text password + salt4546function hash(msg, key) {47 return crypto.createHmac('sha256', key).update(msg).digest('hex');48}49// Authenticate using our plain-object database of doom!5051function authenticate(name, pass, fn) {52 var user = users[name];53 // query the db for the given username54 if (!user) return fn(new Error('cannot find user'));55 // apply the same algorithm to the POSTed password, applying56 // the hash against the pass / salt, if there is a match we57 // found the user58 if (user.pass == hash(pass, user.salt)) return fn(null, user);59 // Otherwise password is invalid60 fn(new Error('invalid password'));61}6263function restrict(req, res, next) {64 if (req.session.user) {65 next();66 } else {67 req.session.error = 'Access denied!';68 res.redirect('/login');69 }70}7172function accessLogger(req, res, next) {73 console.log('/restricted accessed by %s', req.session.user.name);74 next();75}7677app.get('/', function(req, res){78 res.redirect('/login');79});8081app.get('/restricted', restrict, accessLogger, function(req, res){82 res.send('Wahoo! restricted area');83});8485app.get('/logout', function(req, res){86 // destroy the user's session to log them out87 // will be re-created next request88 req.session.destroy(function(){89 res.redirect('home');90 });91});9293app.get('/login', function(req, res){94 if (req.session.user) {95 req.session.success = 'Authenticated as ' + req.session.user.name96 + ' click to <a href="/logout">logout</a>. '97 + ' You may now access <a href="/restricted">/restricted</a>.';98 }99 res.render('login');100});101102app.post('/login', function(req, res){103 authenticate(req.body.username, req.body.password, function(err, user){104 if (user) {105 // Regenerate session when signing in106 // to prevent fixation 107 req.session.regenerate(function(){108 // Store the user's primary key 109 // in the session store to be retrieved,110 // or in this case the entire user object111 req.session.user = user;112 res.redirect('back');113 });114 } else {115 req.session.error = 'Authentication failed, please check your '116 + ' username and password.'117 + ' (use "tj" and "foobar")';118 res.redirect('back');119 }120 });121});122123app.listen(3000);124console.log('Express started on port 3000');