ecomm/src/middlewares/checkAuth.ts

35 lines
1,020 B
TypeScript
Raw Normal View History

2023-06-09 15:39:20 +00:00
import express, { Request, Response, NextFunction } from 'express';
import jwt, { JwtPayload } from 'jsonwebtoken';
import cookieParser from 'cookie-parser';
interface AuthenticatedRequest extends Request {
userId?: string;
}
// Middleware function to authenticate requests
export function authenticateToken(req: AuthenticatedRequest, res: Response, next: NextFunction) {
const token = req.cookies.access_token;
if (!token) {
return res.status(401).json({ error: 'Unauthorized' });
}
2023-06-10 14:02:55 +00:00
jwt.verify(token, process.env.JWT_SECRET as string, (err: any, decoded: { userId: any; }) => {
2023-06-09 15:39:20 +00:00
if (err) {
return res.status(401).json({ error: 'In Valid Token' });
}
2023-06-09 16:04:21 +00:00
req.body.userId = decoded.userId;
2023-06-09 15:39:20 +00:00
next();
});
}
// Set JWT as cookie in the response
export function setJwtCookie(res: Response, token: string) {
res.cookie('access_token', token, { httpOnly: true });
}
// Clear JWT cookie in the response
export function clearJwtCookie(res: Response) {
res.clearCookie('access_token');
}