{"size": 928, "ext": "js", "max_stars_repo_path": "src/routes/middleware/authenticate.middleware.js", "max_stars_repo_name": "vladimirogaston/tpv-users", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/routes/middleware/authenticate.middleware.js", "max_issues_repo_name": "vladimirogaston/tpv-users", "max_issues_repo_issues_event_min_datetime": "2021-06-13T00:32:15.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-13T00:32:43.000Z", "max_forks_repo_path": "src/routes/middleware/authenticate.middleware.js", "max_forks_repo_name": "vladimirogaston/tpv-users", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": 6, "max_forks_count": null, "avg_line_length": 29.935483871, "max_line_length": 71, "alphanum_fraction": 0.5452586207}
const jwt = require('jsonwebtoken')
const dotenv = require('dotenv')
const HttpException = require('../../controllers/HttpException')

module.exports = (rol) => {
    return async function (req, res, next) {
        const authHeader = req.headers['authorization']
        if (!authHeader || !authHeader.startsWith('Bearer')) {
            throw new HttpException(403, 'Bad formed header exception')
        }

        dotenv.config()
        const secretKey = process.env.SECRET_JWT
        const token = authHeader && authHeader.split(' ')[2]
        
        let decoded;
        try {
            decoded = jwt.verify(token, secretKey)
        } catch (err) {
            res.status(500).send('ERROR VERIFY')
        }
        
        const userROLE = decoded.role
        if (rol) {
            if (rol !== userROLE) {
                res.status(500).send('ERROR VERIFY ROLE')
            }
        }
        next()
    }
}