examples/auth/index.js JAVASCRIPT 135 lines View on github.com → Search inside
1'use strict'23/**4 * Module dependencies.5 */67var express = require('../..');8var hash = require('pbkdf2-password')()9var path = require('node:path');10var session = require('express-session');1112var app = module.exports = express();1314// config1516app.set('view engine', 'ejs');17app.set('views', path.join(__dirname, 'views'));1819// middleware2021app.use(express.urlencoded())22app.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// placeholder 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)4950hash({ password: 'foobar' }, function (err, pass, salt, hash) {51  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 username64  if (!user) return fn(null, null)65  // apply the same algorithm to the POSTed password, applying66  // the hash against the pass / salt, if there is a match we67  // found the user68  hash({ password: pass, salt: user.salt }, function (err, pass, salt, hash) {69    if (err) return fn(err);70    if (hash === user.hash) return fn(null, user)71    fn(null, null)72  });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});103104app.post('/login', function (req, res, next) {105  if (!req.body) return res.sendStatus(400)106  authenticate(req.body.username, req.body.password, function(err, user){107    if (err) return next(err)108    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>.';119        res.redirect(req.get('Referrer') || '/');120      });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}

Code quality findings 12

Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var express = require('../..');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var hash = require('pbkdf2-password')()
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var path = require('node:path');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var session = require('express-session');
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var app = module.exports = express();
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var err = req.session.error;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var msg = req.session.success;
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var users = {
Remove debugging statements or use a logging library
info correctness console-log
if (!module.parent) console.log('authenticating %s:%s', name, pass);
Use let or const to avoid scope issues and hoisting
info correctness var-declaration
var user = users[name];
Use strict equality (===) to prevent type coercion bugs
info correctness loose-equality
if (hash === user.hash) return fn(null, user)
Remove debugging statements or use a logging library
info correctness console-log
console.log('Express started on port 3000');

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.