index.js
This file
Path
examples/auth/index.js
134 lines · 3.5 KiB · JavaScript
Last changed by
fix(refactor): prefix built-in node module importsSzymon Łągiewkabefore adoption4111359
History of this fileTake it
Merge tag '4.17.3'Douglas Christopher Wilsonbefore adoption318fd4b
lines 1–2why, one step back1'use strict'2examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 3–7why, one step back3/**4 * Module dependencies.5 */67var express = require('../..');Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 8why, one step back8var hash = require('pbkdf2-password')()fix(refactor): prefix built-in node module importsSzymon Łągiewkabefore adoption4111359
line 9why, one step back9var path = require('node:path');examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 10–16why, one step back10var session = require('express-session');1112var app = module.exports = express();1314// config1516app.set('view engine', 'ejs');Merge tag '4.15.2'Douglas Christopher Wilsonbefore adoptione5dbb0c
line 17why, one step back17app.set('views', path.join(__dirname, 'views'));examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 18–20why, one step back1819// middleware20deps: body-parser@2.0.0-beta.1Douglas Christopher Wilsonbefore adoptionaf341b0
line 21why, one step back21app.use(express.urlencoded())examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 22–49why, one step back22app.use(session({23 resave: false, // don't save session if unmodified24 saveUninitialized: false, // don't create session until something stored25 secret: 'shhhh, very secret'26}));2728// Session-persisted message middleware2930app.use(function(req, res, next){31 var err = req.session.error;32 var msg = req.session.success;33 delete req.session.error;34 delete req.session.success;35 res.locals.message = '';36 if (err) res.locals.message = '<p class="msg error">' + err + '</p>';37 if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';38 next();39});4041// dummy database4243var users = {44 tj: { name: 'tj' }45};4647// when you create a user, generate a salt48// and hash the password ('foobar' is the pass here)49Merge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 50why, one step back50hash({ password: 'foobar' }, function (err, pass, salt, hash) {examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 51–63why, one step back51 if (err) throw err;52 // store the salt & hash in the "db"53 users.tj.salt = salt;54 users.tj.hash = hash;55});565758// Authenticate using our plain-object database of doom!5960function authenticate(name, pass, fn) {61 if (!module.parent) console.log('authenticating %s:%s', name, pass);62 var user = users[name];63 // query the db for the given usernameMerge tag '4.17.3'Douglas Christopher Wilsonbefore adoption318fd4b
line 64why, one step back64 if (!user) return fn(null, null)examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 65–67why, one step back65 // apply the same algorithm to the POSTed password, applying66 // the hash against the pass / salt, if there is a match we67 // found the userMerge tag '4.15.0'Douglas Christopher Wilsonbefore adoption501e24e
line 68why, one step back68 hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
line 69why, one step back69 if (err) return fn(err);Merge tag '4.16.4'Douglas Christopher Wilsonbefore adoption302a615
line 70why, one step back70 if (hash === user.hash) return fn(null, user)Merge tag '4.17.3'Douglas Christopher Wilsonbefore adoption318fd4b
line 71why, one step back71 fn(null, null)examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 72–103why, one step back72 });73}7475function restrict(req, res, next) {76 if (req.session.user) {77 next();78 } else {79 req.session.error = 'Access denied!';80 res.redirect('/login');81 }82}8384app.get('/', function(req, res){85 res.redirect('/login');86});8788app.get('/restricted', restrict, function(req, res){89 res.send('Wahoo! restricted area, click to <a href="/logout">logout</a>');90});9192app.get('/logout', function(req, res){93 // destroy the user's session to log them out94 // will be re-created next request95 req.session.destroy(function(){96 res.redirect('/');97 });98});99100app.get('/login', function(req, res){101 res.render('login');102});103Merge tag '4.17.3'Douglas Christopher Wilsonbefore adoption318fd4b
line 104why, one step back104app.post('/login', function (req, res, next) {deps: body-parser@2.0.0-beta.1Douglas Christopher Wilsonbefore adoptionaf341b0
line 105why, one step back105 if (!req.body) return res.sendStatus(400)examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
line 106why, one step back106 authenticate(req.body.username, req.body.password, function(err, user){Merge tag '4.17.3'Douglas Christopher Wilsonbefore adoption318fd4b
line 107why, one step back107 if (err) return next(err)examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 108–118why, one step back108 if (user) {109 // Regenerate session when signing in110 // to prevent fixation111 req.session.regenerate(function(){112 // Store the user's primary key113 // in the session store to be retrieved,114 // or in this case the entire user object115 req.session.user = user;116 req.session.success = 'Authenticated as ' + user.name117 + ' click to <a href="/logout">logout</a>. '118 + ' You may now access <a href="/restricted">/restricted</a>.';Delete `back` as a magic string (#5933)Blake Embreybefore adoptionbdd81f8
line 119why, one step back119 res.redirect(req.get('Referrer') || '/');examples: make main app file names consistentDouglas Christopher Wilsonbefore adoptionb1d0c19
lines 120–134why, one step back120 });121 } else {122 req.session.error = 'Authentication failed, please check your '123 + ' username and password.'124 + ' (use "tj" and "foobar")';125 res.redirect('/login');126 }127 });128});129130/* istanbul ignore next */131if (!module.parent) {132 app.listen(3000);133 console.log('Express started on port 3000');134}