{"size": 1376, "ext": "js", "max_stars_repo_path": "controllers/login.js", "max_stars_repo_name": "richardcyrus/nosh", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "controllers/login.js", "max_issues_repo_name": "richardcyrus/nosh", "max_issues_repo_issues_event_min_datetime": "2019-07-18T01:32:56.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-14T15:49:05.000Z", "max_forks_repo_path": "controllers/login.js", "max_forks_repo_name": "richardcyrus/nosh", "max_forks_repo_forks_event_min_datetime": "2019-01-26T18:58:19.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-26T18:58:19.000Z"}
{"max_stars_count": null, "max_issues_count": 5, "max_forks_count": 1, "avg_line_length": 26.4615384615, "max_line_length": 72, "alphanum_fraction": 0.4978197674}
/**
 * The Coding Boot Camp at UNC Charlotte.
 * (c) 2019 Richard Cyrus, Teddy Johnson, Sara Minerva, Yobany Perez
 */

// eslint-disable-next-line no-unused-vars
const debug = require('debug')('nosh:loginController');
const passport = require('passport');
const { validationResult } = require('express-validator');

module.exports = {
    getLogin: (req, res) => {
        if (req.isAuthenticated()) {
            return res.redirect('/welcome');
        }

        res.render('account/login', {
            page: 'login-page',
            title: 'Login',
            csrf: req.csrfToken(),
        });
    },

    postLogin: (req, res, next) => {
        const validationErrors = validationResult(req);

        if (!validationErrors.isEmpty()) {
            req.flash('errors', validationErrors.array());
            return res.redirect('/login');
        }

        passport.authenticate('local', (err, user, info) => {
            if (err) {
                return next(err);
            }

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

            req.login(user, (err) => {
                if (err) {
                    return next(err);
                }

                return res.redirect(req.session.returnTo || '/welcome');
            });
        })(req, res, next);
    },
};
