2024-03-29 20:08:34 -04:00
|
|
|
const jwt = require('jsonwebtoken')
|
|
|
|
|
const dotenv = require('dotenv')
|
|
|
|
|
const AppError = require('./AppError.js');
|
2024-04-05 20:10:59 -04:00
|
|
|
const { UNAUTHORIZED_NO_TOKEN_GIVEN, UNAUTHORIZED_INVALID_TOKEN } = require('../constants/errorCodes');
|
2024-03-29 20:08:34 -04:00
|
|
|
|
|
|
|
|
dotenv.config();
|
|
|
|
|
|
|
|
|
|
class Token {
|
|
|
|
|
|
2025-01-29 21:45:41 -05:00
|
|
|
create(email, userId, roles) {
|
|
|
|
|
return jwt.sign({ email, userId, roles }, process.env.JWT_SECRET);
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
authenticate(req, res, next) {
|
|
|
|
|
try {
|
|
|
|
|
const token = req.header('Authorization') && req.header('Authorization').split(' ')[1];
|
|
|
|
|
if (!token) {
|
|
|
|
|
throw new AppError(UNAUTHORIZED_NO_TOKEN_GIVEN);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
jwt.verify(token, process.env.JWT_SECRET, (error, payload) => {
|
|
|
|
|
if (error) {
|
|
|
|
|
throw new AppError(UNAUTHORIZED_INVALID_TOKEN)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req.user = payload;
|
|
|
|
|
});
|
2025-01-29 21:45:41 -05:00
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
} catch (error) {
|
|
|
|
|
return next(error);
|
|
|
|
|
}
|
2025-01-29 21:45:41 -05:00
|
|
|
|
2024-03-29 20:08:34 -04:00
|
|
|
return next();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
module.exports = new Token();
|