Creating login middleware in Express Node js

app.js

...
app.use(require('./login')); /* include middleware login */
...

index.js

var express = require('express');
var router = express.Router();
router.all('/', function (req, res) {
  res.render('index', {
    title: 'Express'
  });
});
module.exports = router;

login.js

var users = {'dave' : 'expressrocks'};
module.exports = function (req, res, next) {
  var method = req.method.toLowerCase(), //cache the method
      user = req.body.user,
      logout = (method === 'delete'),
      login = (user && method === 'post');
  if (logout) { delete req.session.user; }
  if (login) {
    Object.keys(users).forEach(function (name) {
      if (user.name === name && user.pwd === users[name]) {
        req.session.user = {
          name: user.name,
          pwd: user.pwd
        };
      }
    });
  }
  if (!req.session.user) { return next(); }
  res.locals.user = req.session.user;
  next();
};

index.jade

if user
  form(method='post')
    input(name="_method", type="hidden", value="DELETE")
    p Hello #{user.name}!
      a(href='javascript:', onClick='forms[0].submit()') [logout]
else
  p Please log in
  form(method='post')
    fieldset
      legend Login
      p
        label(for="user[name]") Username:
        input(name="user[name]")
      p
        label(for="user[pwd]") Password:
        input(type="password", name="user[pwd]")
        input(type="submit")
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s