nodejs-authentication/app/v1/middlewares/verifyJWT.js
2025-03-11 10:51:27 +00:00

39 lines
1.5 KiB
JavaScript

var fs = require('fs');
const path = require("path");
const jwt = require('jsonwebtoken')
const tokenSecret = fs.readFileSync(path.resolve(
__dirname, '..', 'utils/files/secret-token.key')
, { encoding: 'utf-8' }
);
const api_version = path.resolve(__dirname, '..').split(path.sep).pop();
var verifyJWT = async function verify(req, res, next) {
var application = req.app.get('application');
var models = application.app[api_version].models;
var connection = application.config.dbMySQLConnection();
var user = new models.user(connection, models);
if (req.headers != null && (req.headers.hasOwnProperty('auth_token') || req.headers.hasOwnProperty('authorization'))) {
try {
const auth_token = req.headers.hasOwnProperty('auth_token') ? req.headers.auth_token : req.headers.authorization
jwt.verify(auth_token, tokenSecret, async function (err, decoded) {
if (err) return res.status(401).send({ code: 401, error: 'Unauthorized' });
let user_model = await user.getOne({ 'auth_token': auth_token })
if (user_model != null) {
next()
} else {
return res.status(401).send({ code: 401, error: 'Unauthorized' });
}
});
} catch (error) {
return res.status(401).send({ code: 401, errors: 'Unauthorized' });
}
} else {
return res.status(401).send({ code: 401, errors: 'Unauthorized' });
}
}
module.exports = {
verifyJWT
}