<commit_before>"use strict"; 

var express                 = require('../express-inherit'),
    current_absolute_url    = require('../middleware/route').current_absolute_url,
    base_url                = require('../middleware/route').base_url,
    passport                = require('../passport'),
    popit                   = require('../popit'),
    legacyAccountUpgrade    = require('../middleware/legacy-account-upgrade');

var app = express();


var capture_common_parameters = function (req,res,next) {

  // If there is a redirect_to param use it to store the destination for
  // post auth
  var redirect_to = req.param('redirect_to');
  if (redirect_to) {
    req.session.post_login_redirect_to = redirect_to;
  }
  
  // Are we trying to login as a guest?
  res.locals.as_guest = req.param('as_guest') && req.popit.allow_guest_access() || false;
  res.locals.isUpgrading = typeof req.session.legacyInstanceId === 'string';

  next();
};

module.exports.capture_common_parameters = capture_common_parameters;

app.get('/login', capture_common_parameters, function (req,res) {

  // pass through some of the values
  res.locals.email  = req.param('email');
  res.locals.errors = [];

  res.render('login.html');
});

app.post(
  '/login',
  
  capture_common_parameters,
  
  // Intercept legacy account logins and force the user to upgrade to a new
  // site-wide account.
  function(req, res, next) {
    var errors = res.locals.errors = [];
    res.locals.email = req.param('email');

    passport.authenticate('legacy', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        return next();
      }
      // If we've got this far then the user has logged into a legacy account
      // Check if the user has already upgraded
      var Permission = req.popit.permissions();
      Permission.count({instance: req.popit.instance_id()}, function(err, count) {
        if (err) {
          return next(err);
        }
        if (count === 0) {
          req.session.legacyInstanceId = req.popit.instance_id();
          res.render('legacy-upgrade.html');
        } else {
          errors.push('This legacy account has been upgraded.');
          errors.push('Please login with a site-wide account');
          res.render('login.html');
        }
      });
    })(req, res, next);
  },
  // If this is for a guest then do the right thing
  // Otherwise get the email and password.
  // check we have both.
  // load the user
  function (req, res, next ) {

    // If we are trying to log in as guest skip on to next handler.
    if ( res.locals.as_guest  ) {
      req.session.is_guest = true;
      return next();
    }

    var errors = res.locals.errors = [];
    res.locals.email = req.body.email || '';

    passport.authenticate('local', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        errors.push(info.message);
        return res.render('login.html');
      }
      req.login(user, function(err) {
        if (err) {
          return next(err);
        }
        res.locals.user = user;
        next();
      });
    })(req, res, next);
  },

  legacyAccountUpgrade,

  // now logged in, redirect to where we should go
  function(req, res, next) {

    var redirect_to = req.session.post_login_redirect_to || '/';

    delete req.session.post_login_redirect_to;
    res.req.flash('info', 'You are now logged in.');
    res.redirect( redirect_to );
  }

);


app.get('/logout', function (req,res,next) {
  req.session = null;
  res.redirect('/');
});

app.get('/forgotten-password', function(req, res) {
  res.render('forgotten-password.html');
});

module.exports.app = app;


module.exports.middleware = function (req,res,next) {

  res.locals.user = req.user;
  req.permissions = {};
  res.locals.permissions = {};

  if ( req.session.is_guest ) {
    if ( req.popit.allow_guest_access() ) {
      res.locals.guest = true;
      req.guest        = true;      
    } else {
      // guest access on longer allowed. Delete this from session
      delete req.session.is_guest;
    }
  }

  if ( req.user ) {
    req.popit.permissions().getPermissions( req.user._id, req.popit.instance_id(), function(err, permissions) {
      if ( err ) {
        req.permissions = {};
        res.locals.permissions = {};
        return next();
      }
      req.permissions = permissions;
      res.locals.permissions = permissions;
    });
  }
  next();

};


module.exports.requireUser = function requireUser(req, res, next) {
  // if we have a user then continue
  if ( req.permissions.can_edit_instance ) {
      return next();
  }

  // Store our url on the session and get the user to log in.
  req.session.post_login_redirect_to = current_absolute_url(req);
  res.redirect( base_url(req) + '/login' );
};

module.exports.requireUserOrGuest = function requireUserOrGuest(req, res, next) {
  // if we have a user then continue
  if ( req.guest ) return next();

  // Otherwise pass on control
  module.exports.requireUser(req,res,next);
};

module.exports.apiRequireUser = function apiRequireUser (req, res, next) {  
  passport.authenticate(
    ['basic', 'legacy-basic'],
    { session: false }
  )(req, res, next);
};


module.exports.apiRequireUserOrGuest = function apiRequireUserOrGuest (req, res, next) {  
  // If we are already guest then continue
  if (req.popit.allow_guest_access && req.guest) return next();

  // Otherwise pass on control
  module.exports.apiRequireUser(req,res,next);
};

<commit_msg>Fix bug with the auth middleware<commit_after>"use strict"; 

var express                 = require('../express-inherit'),
    current_absolute_url    = require('../middleware/route').current_absolute_url,
    base_url                = require('../middleware/route').base_url,
    passport                = require('../passport'),
    popit                   = require('../popit'),
    legacyAccountUpgrade    = require('../middleware/legacy-account-upgrade');

var app = express();


var capture_common_parameters = function (req,res,next) {

  // If there is a redirect_to param use it to store the destination for
  // post auth
  var redirect_to = req.param('redirect_to');
  if (redirect_to) {
    req.session.post_login_redirect_to = redirect_to;
  }
  
  // Are we trying to login as a guest?
  res.locals.as_guest = req.param('as_guest') && req.popit.allow_guest_access() || false;
  res.locals.isUpgrading = typeof req.session.legacyInstanceId === 'string';

  next();
};

module.exports.capture_common_parameters = capture_common_parameters;

app.get('/login', capture_common_parameters, function (req,res) {

  // pass through some of the values
  res.locals.email  = req.param('email');
  res.locals.errors = [];

  res.render('login.html');
});

app.post(
  '/login',
  
  capture_common_parameters,
  
  // Intercept legacy account logins and force the user to upgrade to a new
  // site-wide account.
  function(req, res, next) {
    var errors = res.locals.errors = [];
    res.locals.email = req.param('email');

    passport.authenticate('legacy', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        return next();
      }
      // If we've got this far then the user has logged into a legacy account
      // Check if the user has already upgraded
      var Permission = req.popit.permissions();
      Permission.count({instance: req.popit.instance_id()}, function(err, count) {
        if (err) {
          return next(err);
        }
        if (count === 0) {
          req.session.legacyInstanceId = req.popit.instance_id();
          res.render('legacy-upgrade.html');
        } else {
          errors.push('This legacy account has been upgraded.');
          errors.push('Please login with a site-wide account');
          res.render('login.html');
        }
      });
    })(req, res, next);
  },
  // If this is for a guest then do the right thing
  // Otherwise get the email and password.
  // check we have both.
  // load the user
  function (req, res, next ) {

    // If we are trying to log in as guest skip on to next handler.
    if ( res.locals.as_guest  ) {
      req.session.is_guest = true;
      return next();
    }

    var errors = res.locals.errors = [];
    res.locals.email = req.body.email || '';

    passport.authenticate('local', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        errors.push(info.message);
        return res.render('login.html');
      }
      req.login(user, function(err) {
        if (err) {
          return next(err);
        }
        res.locals.user = user;
        next();
      });
    })(req, res, next);
  },

  legacyAccountUpgrade,

  // now logged in, redirect to where we should go
  function(req, res, next) {

    var redirect_to = req.session.post_login_redirect_to || '/';

    delete req.session.post_login_redirect_to;
    res.req.flash('info', 'You are now logged in.');
    res.redirect( redirect_to );
  }

);


app.get('/logout', function (req,res,next) {
  req.session = null;
  res.redirect('/');
});

app.get('/forgotten-password', function(req, res) {
  res.render('forgotten-password.html');
});

module.exports.app = app;


module.exports.middleware = function (req,res,next) {

  res.locals.user = req.user;
  req.permissions = res.locals.permissions = {};

  if ( req.session.is_guest ) {
    if ( req.popit.allow_guest_access() ) {
      res.locals.guest = true;
      req.guest        = true;      
    } else {
      // guest access on longer allowed. Delete this from session
      delete req.session.is_guest;
    }
  }

  if ( req.user ) {
    req.popit.permissions().getPermissions( req.user._id, req.popit.instance_id(), function(err, permissions) {
      if ( err ) {
        return next(err);
      }
      req.permissions = res.locals.permissions = permissions;
      next();
    });
  } else {
    next();
  }

};


module.exports.requireUser = function requireUser(req, res, next) {
  // if we have a user then continue
  if ( req.permissions.can_edit_instance ) {
      return next();
  }

  // Store our url on the session and get the user to log in.
  req.session.post_login_redirect_to = current_absolute_url(req);
  res.redirect( base_url(req) + '/login' );
};

module.exports.requireUserOrGuest = function requireUserOrGuest(req, res, next) {
  // if we have a user then continue
  if ( req.guest ) return next();

  // Otherwise pass on control
  module.exports.requireUser(req,res,next);
};

module.exports.apiRequireUser = function apiRequireUser (req, res, next) {  
  passport.authenticate(
    ['basic', 'legacy-basic'],
    { session: false }
  )(req, res, next);
};


module.exports.apiRequireUserOrGuest = function apiRequireUserOrGuest (req, res, next) {  
  // If we are already guest then continue
  if (req.popit.allow_guest_access && req.guest) return next();

  // Otherwise pass on control
  module.exports.apiRequireUser(req,res,next);
};


{'fraction_non_alphanumeric': 0.1377370474548589, 'fraction_numerical': 0.00018147173577715272, 'mean_word_length': 2.6149557231879306, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7082465', 'n_tokens_mistral': 3524, 'n_tokens_neox': 3442, 'n_words': 850}