{"size": 1190, "ext": "js", "max_stars_repo_path": "src/middlewares/guard.js", "max_stars_repo_name": "Alvarez-P/express-mongo-template", "max_stars_repo_stars_event_min_datetime": "2020-11-30T13:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-22T01:20:58.000Z", "max_issues_repo_path": "src/middlewares/guard.js", "max_issues_repo_name": "Alvarez-P/express-mongo-template", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/middlewares/guard.js", "max_forks_repo_name": "Alvarez-P/express-mongo-template", "max_forks_repo_forks_event_min_datetime": "2020-11-30T15:57:25.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-30T15:57:25.000Z"}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": 1, "avg_line_length": 31.3157894737, "max_line_length": 70, "alphanum_fraction": 0.6462184874}
const HttpError = require('../classes/httpError')
const { Configuration, Keys } = require('../config')
const { headersSchm } = require('../schemes/auth')
const fetch = require('../utils/fetch')

/**
 * @function guard
 * @description Middleware for 404 errors
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next middleware function
 */
const guard = async (req, res, next) => {
  try {
    const headerValidation = headersSchm.validate(req.headers)
    if (headerValidation.error)
      throw new HttpError(400, 'Header de autorización inválido', {
        field: ['headers', 'Authorization'],
        value: headerValidation.error.details[0].context.value,
      })
    const token = req.headers.authorization.split(' ')[1]
    const isValid = await fetch.POST(
      `${Configuration.get(Keys.AUTH_API_URL)}/token/verify/`,
      { token }
    )
    if (isValid.status !== 200)
      throw new HttpError(401, 'El token es inválido o ha expirado', {
        field: ['headers', 'Authorization'],
        value: token,
      })
    next()
  } catch (error) {
    next(error)
  }
}

module.exports = guard
