app.js
This file
Path
examples/auth/app.js
127 lines · 3.2 KiB · JavaScript
Last changed by
remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
History of this fileTake it
The walk stopped after 200 commits: lines older than 82731da point at it.
Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da
lines 1–5why, one step back1/**2 * Module dependencies.3 */45var express = require('../..')remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
lines 6–9why, one step back6 , hash = require('./pass').hash7 , bodyParser = require('body-parser')8 , cookieParser = require('cookie-parser')9 , session = require('express-session')Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da
lines 10–19why, one step back1011var app = module.exports = express();1213// config1415app.set('view engine', 'ejs');16app.set('views', __dirname + '/views');1718// middleware19remove last pieces of connect dependencyRoman Shtylmanbefore adoption1396e08
lines 20–22why, one step back20app.use(bodyParser());21app.use(cookieParser('shhhh, very secret'));22app.use(session());Merge pull request #1503 from shesek/settings-inheritanceTJ Holowaychukbefore adoption82731da
lines 23–127why, one step back2324// Session-persisted message middleware2526app.use(function(req, res, next){27 var err = req.session.error28 , msg = req.session.success;29 delete req.session.error;30 delete req.session.success;31 res.locals.message = '';32 if (err) res.locals.message = '<p class="msg error">' + err + '</p>';33 if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';34 next();35});3637// dummy database3839var users = {40 tj: { name: 'tj' }41};4243// when you create a user, generate a salt44// and hash the password ('foobar' is the pass here)4546hash('foobar', function(err, salt, hash){47 if (err) throw err;48 // store the salt & hash in the "db"49 users.tj.salt = salt;50 users.tj.hash = hash;51});525354// Authenticate using our plain-object database of doom!5556function authenticate(name, pass, fn) {57 if (!module.parent) console.log('authenticating %s:%s', name, pass);58 var user = users[name];59 // query the db for the given username60 if (!user) return fn(new Error('cannot find user'));61 // apply the same algorithm to the POSTed password, applying62 // the hash against the pass / salt, if there is a match we63 // found the user64 hash(pass, user.salt, function(err, hash){65 if (err) return fn(err);66 if (hash == user.hash) return fn(null, user);67 fn(new Error('invalid password'));68 })69}7071function restrict(req, res, next) {72 if (req.session.user) {73 next();74 } else {75 req.session.error = 'Access denied!';76 res.redirect('/login');77 }78}7980app.get('/', function(req, res){81 res.redirect('login');82});8384app.get('/restricted', restrict, function(req, res){85 res.send('Wahoo! restricted area, click to <a href="/logout">logout</a>');86});8788app.get('/logout', function(req, res){89 // destroy the user's session to log them out90 // will be re-created next request91 req.session.destroy(function(){92 res.redirect('/');93 });94});9596app.get('/login', function(req, res){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 req.session.success = 'Authenticated as ' + user.name111 + ' click to <a href="/logout">logout</a>. '112 + ' You may now access <a href="/restricted">/restricted</a>.';113 res.redirect('back');114 });115 } else {116 req.session.error = 'Authentication failed, please check your '117 + ' username and password.'118 + ' (use "tj" and "foobar")';119 res.redirect('login');120 }121 });122});123124if (!module.parent) {125 app.listen(3000);126 console.log('Express started on port 3000');127}