2024-09-30 21:08:52 -04:00
|
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
|
import dotenv from 'dotenv';
|
|
|
|
|
import AppError from './AppError';
|
|
|
|
|
import { UNAUTHORIZED_NO_TOKEN_GIVEN, UNAUTHORIZED_INVALID_TOKEN } from '../constants/errorCodes';
|
|
|
|
|
import { Request, Response, NextFunction } from 'express';
|
2024-03-29 20:08:34 -04:00
|
|
|
|
|
|
|
|
dotenv.config();
|
|
|
|
|
|
|
|
|
|
class Token {
|
2024-09-30 21:08:52 -04:00
|
|
|
create(email: string, userId: string): string {
|
|
|
|
|
return jwt.sign({ email, userId }, process.env.JWT_SECRET as string, { expiresIn: '2h' });
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
|
|
|
|
|
2024-09-30 21:08:52 -04:00
|
|
|
authenticate(req: Request, res: Response, next: NextFunction): void {
|
2024-03-29 20:08:34 -04:00
|
|
|
try {
|
2024-09-30 21:08:52 -04:00
|
|
|
const authHeader = req.header('Authorization');
|
|
|
|
|
const token = authHeader && authHeader.split(' ')[1];
|
2024-03-29 20:08:34 -04:00
|
|
|
if (!token) {
|
|
|
|
|
throw new AppError(UNAUTHORIZED_NO_TOKEN_GIVEN);
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-30 21:08:52 -04:00
|
|
|
jwt.verify(token, process.env.JWT_SECRET as string, (error, payload) => {
|
2024-03-29 20:08:34 -04:00
|
|
|
if (error) {
|
2024-09-30 21:08:52 -04:00
|
|
|
throw new AppError(UNAUTHORIZED_INVALID_TOKEN);
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
|
|
|
|
req.user = payload;
|
2024-09-30 21:08:52 -04:00
|
|
|
next();
|
2024-03-29 20:08:34 -04:00
|
|
|
});
|
|
|
|
|
} catch (error) {
|
2024-09-30 21:08:52 -04:00
|
|
|
next(error);
|
2024-03-29 20:08:34 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-30 21:08:52 -04:00
|
|
|
export default new Token();
|