const jwt = require('jsonwebtoken');
const db = require('../models');
const redirectHome = require('./redirectHome');

const AdminModel = db.admin;
const TokenModel = db.token;

const authentification = async (req, res, next) => {
    try {
        const authToken = req.session.token;
        
        const decodedToken = jwt.verify(authToken, 'foo');
        const admin = await AdminModel.findByPk(decodedToken.id);
        const token = await TokenModel.findOne({
            where: {
                authToken: authToken
            }
        });           
         
        //  Si aucun admin ou token supprimé
        if(!admin || !token) {            
            req.session.destroy();                
            let errors = null;
            return res.send('tafa ihany ka');
            //res.render('pages/log/signin', { errors, req })      
        }
        else next();
    } catch(err) {
        console.log(err)  
        let errors = null;
        //return res.send('erreur' + err);
       res.render('pages/log/signin', { errors, req })      
        // res.redirect('/admin/signin');
    }
}

module.exports = authentification;