text: var _ = require('lodash');
  var async = require('async');
  var crypto = require('crypto');
  var nodemailer = require('nodemailer');
  var passport = require('passport');
  var User = require('../models/User');
  
  /**
   * GET /login
   * Login page.
   */
  exports.getLogin = function(req, res) {
    if (req.user) {
      return res.redirect('/');
    }
    res.render('account/login', {
      title: 'Login'
    });
  };
  
  /**
   * POST /login
   * Sign in using email and password.
   */
  exports.postLogin = function(req, res, next) {
    req.assert('email', 'Email is not valid').isEmail();
    req.assert('password', 'Password cannot be blank').notEmpty();
  
    var errors = req.validationErrors();
  
    if (errors) {
      req.flash('errors', errors);
      return res.redirect('/login');
    }
    passport.authenticate('local', function(err, user, info) {
      if (err) {
        return next(err);
      }
      if (!user) {
        req.flash('errors', { msg: info.message });
        return res.redirect('/login');
      }
      req.logIn(user, function(err) {
        if (err) {
          return next(err);
        }
        req.flash('success', { msg: 'Success! You are logged in.' });
        res.redirect('/');
      });
    })(req, res, next);
  };
  
  exports.postLoginMobile = function(req,res) {
    if (!req.body.email || !req.body.password) {
      response = {
        code: 400,
        msg: 'Bad parameters.'
      }
      return res.send(response);
    }
  
    User.findOne({ email: req.body.email }, function(err, user) {
      if (!user) {
        response = {
          code: 400,
          msg: 'Email not found.'
        }
        return res.send(response);
      }
      user.comparePassword(req.body.password, function(err, isMatch) {
        if (isMatch) {
          response = {};
          if (user.plaid_access_token) {
            response = {
              code: 200,
              msg: 'Logged in!.',
              access_token: user.plaid_access_token,
              user: req.user
            }
          } else {
            response = {
              code: 200,
              msg: 'Logged in!.',
              user: req.user
            }
          }
          
          return res.send(response);
        } else {
          response = {
            code: 400,
            msg: 'Invalid email or password.'
          }
          return res.send(response);
          }
      });
    });
  }
  
  /**
   * GET /logout
   * Log out.
   */
  exports.logout = function(req, res) {
    req.logout();
    res.redirect('/');
  };
  
  /**
   * GET /signup
   * Signup page.
   */
  exports.getSignup = function(req, res) {
    if (req.user) {
      return res.redirect('/');
    }
    res.render('account/signup', {
      title: 'Create Account'
    });
  };
  
  /**
   * POST /signup
   * Create a new local account.
   */
  exports.postSignup = function(req, res, next) {
    req.assert('email', 'Email is not valid').isEmail();
    req.assert('password', 'Password must be at least 4 characters long').len(4);
    req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
  
    var errors = req.validationErrors();
  
    if (errors) {
      req.flash('errors', errors);
      return res.redirect('/signup');
    }
  
    var user = new User({
      email: req.body.email,
      password: req.body.password
    });
  
    User.findOne({ email: req.body.email }, function(err, existingUser) {
      if (existingUser) {
        req.flash('errors', { msg: 'Account with that email address already exists.' });
        return res.redirect('/signup');
      }
      user.save(function(err) {
        if (err) {
          return next(err);
        }
        req.logIn(user, function(err) {
          if (err) {
            return next(err);
          }
          res.redirect('/');
        });
      });
    });
  };
  
  exports.postSignupMobile = function(req, res) {
    if (!req.body.email || !req.body.password) {
      response = {
        code: 400,
        msg: 'Bad parameters.'
      }
      return res.send(response);
    }
  
    var user = new User({
      email: req.body.email,
      password: req.body.password
    });
  
    User.findOne({ email: req.body.email }, function(err, existingUser) {
      if (existingUser) {
        response = {
          code: 400,
          msg: 'User already exists.'
        }
        return res.send(response);
      }
      user.save(function(err) {
        if (err) {
          response = {
            code: 500,
            msg: 'There was an issue with creating the user.'
          }
          return res.send(response);
        }
        response = {
          code: 200,
          msg: 'Success!',
          user: user
        }
        return res.send(response);
      });
    });
  }
  
  /**
   * GET /account
   * Profile page.
   */
  exports.getAccount = function(req, res) {
    res.render('account/profile', {
      title: 'Account Management'
    });
  };
  
  /**
   * POST /account/profile
   * Update profile information.
   */
  exports.postUpdateProfile = function(req, res, next) {
    User.findById(req.user.id, function(err, user) {
      if (err) {
        return next(err);
      }
      user.email = req.body.email || '';
      user.profile.firstName = req.body.firstName || '';
      user.profile.lastName = req.body.lastName || '';
      user.save(function(err) {
        if (err) {
          return next(err);
        }
        req.flash('success', { msg: 'Profile information updated.' });
        res.redirect('/account');
      });
    });
  };
  
  /**
   * POST /account/password
   * Update current password.
   */
  exports.postUpdatePassword = function(req, res, next) {
    req.assert('password', 'Password must be at least 4 characters long').len(4);
    req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
  
    var errors = req.validationErrors();
  
    if (errors) {
      req.flash('errors', errors);
      return res.redirect('/account');
    }
  
    User.findById(req.user.id, function(err, user) {
      if (err) {
        return next(err);
      }
      user.password = req.body.password;
      user.save(function(err) {
        if (err) {
          return next(err);
        }
        req.flash('success', { msg: 'Password has been changed.' });
        res.redirect('/account');
      });
    });
  };
  
  /**
   * POST /account/delete
   * Delete user account.
   */
  exports.postDeleteAccount = function(req, res, next) {
    User.remove({ _id: req.user.id }, function(err) {
      if (err) {
        return next(err);
      }
      req.logout();
      req.flash('info', { msg: 'Your account has been deleted.' });
      res.redirect('/');
    });
  };
  
  /**
   * GET /reset/:token
   * Reset Password page.
   */
  exports.getReset = function(req, res) {
    if (req.isAuthenticated()) {
      return res.redirect('/');
    }
    User
      .findOne({ resetPasswordToken: req.params.token })
      .where('resetPasswordExpires').gt(Date.now())
      .exec(function(err, user) {
        if (err) {
          return next(err);
        }
        if (!user) {
          req.flash('errors', { msg: 'Password reset token is invalid or has expired.' });
          return res.redirect('/forgot');
        }
        res.render('account/reset', {
          title: 'Password Reset'
        });
      });
  };
  
  /**
   * POST /reset/:token
   * Process the reset password request.
   */
  exports.postReset = function(req, res, next) {
    req.assert('password', 'Password must be at least 4 characters long.').len(4);
    req.assert('confirm', 'Passwords must match.').equals(req.body.password);
  
    var errors = req.validationErrors();
  
    if (errors) {
      req.flash('errors', errors);
      return res.redirect('back');
    }
  
    async.waterfall([
      function(done) {
        User
          .findOne({ resetPasswordToken: req.params.token })
          .where('resetPasswordExpires').gt(Date.now())
          .exec(function(err, user) {
            if (err) {
              return next(err);
            }
            if (!user) {
              req.flash('errors', { msg: 'Password reset token is invalid or has expired.' });
              return res.redirect('back');
            }
            user.password = req.body.password;
            user.resetPasswordToken = undefined;
            user.resetPasswordExpires = undefined;
            user.save(function(err) {
              if (err) {
                return next(err);
              }
              req.logIn(user, function(err) {
                done(err, user);
              });
            });
          });
      },
      function(user, done) {
        var transporter = nodemailer.createTransport({
          service: 'SendGrid',
          auth: {
            user: process.env.SENDGRID_USER,
            pass: process.env.SENDGRID_PASSWORD
          }
        });
        var mailOptions = {
          to: user.email,
          from: 'erictimmerman@college.harvard.edu',
          subject: 'Your Cash Strapped password has been changed',
          text: 'Hello,\n\n' +
            'This is a confirmation that the password for your account ' + user.email + ' has just been changed.\n'
        };
        transporter.sendMail(mailOptions, function(err) {
          req.flash('success', { msg: 'Success! Your password has been changed.' });
          done(err);
        });
      }
    ], function(err) {
      if (err) {
        return next(err);
      }
      res.redirect('/');
    });
  };
  
  /**
   * GET /forgot
   * Forgot Password page.
   */
  exports.getForgot = function(req, res) {
    if (req.isAuthenticated()) {
      return res.redirect('/');
    }
    res.render('account/forgot', {
      title: 'Forgot Password'
    });
  };
  
  /**
   * POST /forgot
   * Create a random token, then the send user an email with a reset link.
   */
  exports.postForgot = function(req, res, next) {
    req.assert('email', 'Please enter a valid email address.').isEmail();
  
    var errors = req.validationErrors();
  
    if (errors) {
      req.flash('errors', errors);
      return res.redirect('/forgot');
    }
  
    async.waterfall([
      function(done) {
        crypto.randomBytes(16, function(err, buf) {
          var token = buf.toString('hex');
          done(err, token);
        });
      },
      function(token, done) {
        User.findOne({ email: req.body.email.toLowerCase() }, function(err, user) {
          if (!user) {
            req.flash('errors', { msg: 'No account with that email address exists.' });
            return res.redirect('/forgot');
          }
          user.resetPasswordToken = token;
          user.resetPasswordExpires = Date.now() + 3600000; // 1 hour
          user.save(function(err) {
            done(err, token, user);
          });
        });
      },
      function(token, user, done) {
        var transporter = nodemailer.createTransport({
          service: 'SendGrid',
          auth: {
            user: process.env.SENDGRID_USER,
            pass: process.env.SENDGRID_PASSWORD
          }
        });
        var mailOptions = {
          to: user.email,
          from: 'erictimmerman@college.harvard.edu',
          subject: 'Reset your password on Cash Strapped',
          text: 'You are receiving this email because you (or someone else) have requested the reset of the password for your account.\n\n' +
            'Please click on the following link, or paste this into your browser to complete the process:\n\n' +
            'http://' + req.headers.host + '/reset/' + token + '\n\n' +
            'If you did not request this, please ignore this email and your password will remain unchanged.\n'
        };
        transporter.sendMail(mailOptions, function(err) {
          req.flash('info', { msg: 'An e-mail has been sent to ' + user.email + ' with further instructions.' });
          done(err, 'done');
        });
      }
    ], function(err) {
      if (err) {
        return next(err);
      }
      res.redirect('/forgot');
    });
  };
  