title: Passport middleware, check if the user already has a living session from
body: <p>I am building a web application using <a href="https://github.com/angular-fullstack/generator-angular-fullstack" rel="nofollow noreferrer">angular-fullstack</a>. The stack is using <a href="https://www.npmjs.com/package/express-sessions" rel="nofollow noreferrer">express-sessions</a> for session storage (in Mongodb) and passport.js for authentication.</p>
  
  <p>I want to limit each user to a single login session. I am trying find a way to check if a user already has a living session when they login.</p>
  
  <p>Is there a way to programmatically call a route to query mongodb from the passport middleware?</p>
  
  <pre><code>'use strict';
  
  import path from 'path';
  
  import passport from 'passport';
  import {Strategy as LocalStrategy} from 'passport-local';
  
  import express from 'express';
  import session from 'express-session';
  
  import _ from 'lodash';
  import Session from '../../api/session/session.model';
  
  var app = express();
  require('run-middleware')(app);
  
  function localAuthenticate(User, email, password, done, req) {
    User.findOne({
      email: email.toLowerCase()
    }).exec()
      .then(user =&gt; {
  
        if (!user) {
          return done(null, false, {
            message: 'This email is not registered.'
          });
        }
  
        // HERE is where I am trying to check if a user
        // already has a living session when they login
  
        // I tried to use the runMiddleware
        // to query mongodb for all the existing sessions
        // but I get this error: http://pastebin.com/YTeu5AwA
        app.runMiddleware('/sessions',{},function(code,data){
          console.log(code) // 200 
          console.log(data) // { user: '20', name: 'Moyshale' }
        });
  
        // Is there a way to access and use an existing route?
  
        user.authenticate(password, function(authError, authenticated) {
          if (authError) {
            return done(authError);
          }
          if (!authenticated) {
            return done(null, false, { message: 'This password is not correct.' });
          } else {
            return done(null, user);
          }
        });
      })
      .catch(err =&gt; done(err));
  }
  
  export function setup(User, config) {
  
    passport.use(new LocalStrategy({
      passReqToCallback: true,
      usernameField: 'email',
      passwordField: 'password' // this is the virtual field on the model
    }, function(req, email, password, done) {
      return localAuthenticate(User, email, password, done, req);
    }));
  }
  </code></pre>