<commit_before>'use strict';

/**
 * Module Dependencies
 */

var User          = require('../models/User');
var debug         = require('debug')('skeleton');  // https://github.com/visionmedia/debug
var async         = require('async');
var crypto        = require('crypto');
var config        = require('../config/config');
var passport      = require('passport');
var nodemailer    = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var LoginAttempt  = require('../models/LoginAttempt');

/**
 * User Controller
 */

module.exports.controller = function (app) {

  /**
   * GET /login
   * Render login page
   */

  app.get('/login', function (req, res) {
    // Check if user is already logged in
    if (req.user) {
      req.flash('info', { msg: 'You are already logged in!' });
      return res.redirect('/');
    }
    // Turn off login form if too many attempts
    var tooManyAttempts = req.session.tooManyAttempts || false;
    req.session.tooManyAttempts = null;
    // Render Login form
    res.render('account/login', {
      tooManyAttempts: tooManyAttempts,
      url: req.url
    });
  });

  /**
   * POST /login
   * Log the user in
   */

  app.post('/login', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the data
     */

    workflow.on('validate', function () {

      // Validate the form fields
      req.assert('email', 'Your email cannot be empty.').notEmpty();
      req.assert('email', 'Your email is not valid').isEmail();
      req.assert('password', 'Your password cannot be blank').notEmpty();
      req.assert('password', 'Your password must be at least 4 characters long.').len(4);

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('/login');
      }

      // next step
      workflow.emit('abuseFilter');
    });

    /**
     * Step 2: Prevent brute force login hacking
     */

    workflow.on('abuseFilter', function () {

      var getIpCount = function (done) {
        var conditions = { ip: req.ip };
        LoginAttempt.count(conditions, function (err, count) {
          if (err) {
            return done(err);
          }
          done(null, count);
        });
      };

      var getIpUserCount = function (done) {
        var conditions = { ip: req.ip, user: req.body.email.toLowerCase() };
        LoginAttempt.count(conditions, function (err, count) {
          if (err) {
            return done(err);
          }
          done(null, count);
        });
      };

      var asyncFinally = function (err, results) {
        if (err) {
          return workflow.emit('exception', err);
        }

        if (results.ip >= config.loginAttempts.forIp || results.ipUser >= config.loginAttempts.forUser) {
          req.flash('error', { msg: 'You\'ve reached the maximum number of login attempts. Please try again later or reset your password.' });
          req.session.tooManyAttempts = true;
          return res.redirect('/login');
        }
        else {
          workflow.emit('authenticate');
        }

      };

      async.parallel({ ip: getIpCount, ipUser: getIpUserCount }, asyncFinally);
    });

    /**
     * Step 3: Authenticate the user
     */

    workflow.on('authenticate', function () {

      // Authenticate the user
      passport.authenticate('local', function (err, user, info) {
        if (err) {
          req.flash('error', { msg: err.message });
          return res.redirect('back');
        }

        if (!user) {

          // Update abuse count
          var fieldsToSet = { ip: req.ip, user: req.body.email };
          LoginAttempt.create(fieldsToSet, function (err, doc) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            } else {
              // User Not Found (Return)
              req.flash('error', { msg: info.message });
              return res.redirect('/login');
            }
          });

        } else {

          // update the user's record with login timestamp
          user.activity.last_logon = Date.now();
          user.save(function (err) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            }
          });

          // Log user in
          req.logIn(user, function (err) {
            if (err) {
              req.flash('error', { msg: err.message });
		//return res.redirect('back');
		return;
            }
<commit_msg>do not bother with login timestamps<commit_after>'use strict';

/**
 * Module Dependencies
 */

var User          = require('../models/User');
var debug         = require('debug')('skeleton');  // https://github.com/visionmedia/debug
var async         = require('async');
var crypto        = require('crypto');
var config        = require('../config/config');
var passport      = require('passport');
var nodemailer    = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var LoginAttempt  = require('../models/LoginAttempt');

/**
 * User Controller
 */

module.exports.controller = function (app) {

  /**
   * GET /login
   * Render login page
   */

  app.get('/login', function (req, res) {
    // Check if user is already logged in
    if (req.user) {
      req.flash('info', { msg: 'You are already logged in!' });
      return res.redirect('/');
    }
    // Turn off login form if too many attempts
    var tooManyAttempts = req.session.tooManyAttempts || false;
    req.session.tooManyAttempts = null;
    // Render Login form
    res.render('account/login', {
      tooManyAttempts: tooManyAttempts,
      url: req.url
    });
  });

  /**
   * POST /login
   * Log the user in
   */

  app.post('/login', function (req, res, next) {

    // Begin a workflow
    var workflow = new (require('events').EventEmitter)();

    /**
     * Step 1: Validate the data
     */

    workflow.on('validate', function () {

      // Validate the form fields
      req.assert('email', 'Your email cannot be empty.').notEmpty();
      req.assert('email', 'Your email is not valid').isEmail();
      req.assert('password', 'Your <PASSWORD>').notEmpty();
      req.assert('password', 'Your password must be at least 4 characters long.').len(4);

      var errors = req.validationErrors();

      if (errors) {
        req.flash('error', errors);
        return res.redirect('/login');
      }

      // next step
      workflow.emit('abuseFilter');
    });

    /**
     * Step 2: Prevent brute force login hacking
     */

    workflow.on('abuseFilter', function () {

      var getIpCount = function (done) {
        var conditions = { ip: req.ip };
        LoginAttempt.count(conditions, function (err, count) {
          if (err) {
            return done(err);
          }
          done(null, count);
        });
      };

      var getIpUserCount = function (done) {
        var conditions = { ip: req.ip, user: req.body.email.toLowerCase() };
        LoginAttempt.count(conditions, function (err, count) {
          if (err) {
            return done(err);
          }
          done(null, count);
        });
      };

      var asyncFinally = function (err, results) {
        if (err) {
          return workflow.emit('exception', err);
        }

        if (results.ip >= config.loginAttempts.forIp || results.ipUser >= config.loginAttempts.forUser) {
          req.flash('error', { msg: 'You\'ve reached the maximum number of login attempts. Please try again later or reset your password.' });
          req.session.tooManyAttempts = true;
          return res.redirect('/login');
        }
        else {
          workflow.emit('authenticate');
        }

      };

      async.parallel({ ip: getIpCount, ipUser: getIpUserCount }, asyncFinally);
    });

    /**
     * Step 3: Authenticate the user
     */

    workflow.on('authenticate', function () {

      // Authenticate the user
      passport.authenticate('local', function (err, user, info) {
        if (err) {
          req.flash('error', { msg: err.message });
          return res.redirect('back');
        }

        if (!user) {

          // Update abuse count
          var fieldsToSet = { ip: req.ip, user: req.body.email };
          LoginAttempt.create(fieldsToSet, function (err, doc) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            } else {
              // User Not Found (Return)
              req.flash('error', { msg: info.message });
              return res.redirect('/login');
            }
          });

        } else {

            // update the user's record with login timestamp
	    /*
          user.activity.last_logon = Date.now();
          user.save(function (err) {
            if (err) {
              req.flash('error', { msg: err.message });
              return res.redirect('back');
            }
          });*/

          // Log user in
          req.logIn(user, function (err) {
            if (err) {
              req.flash('error', { msg: err.message });
		//return res.redirect('back');
		return;
            }

{'fraction_non_alphanumeric': 0.14627831715210357, 'fraction_numerical': 0.0010787486515641855, 'mean_word_length': 1.932932616260677, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 8, 'https://': 2, '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': '6569432', 'n_tokens_mistral': 2683, 'n_tokens_neox': 2571, 'n_words': 673}