var express = require('express');
var router = express.Router();
const passport = require('../passport-config');

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('authentification');
});

router.post('/authentification', passport.authenticate('local', {
    successRedirect: '/dashboard',
    failureRedirect: '/'
}));

router.get('/dashboard', isAuthenticated, function(req, res, next) {
    res.render('deconnexion');
});

router.get('/logout', isAuthenticated, function(req, res, next) {
    req.logout(function(err) {
        if (err) {
            return next(err);
        }
        res.redirect('/');
    });
});

function isAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/');
}

module.exports = router;