BE/src/filters/auth-exception.filter.ts

47 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-07-10 17:06:39 +05:30
import {
ExceptionFilter,
Catch,
ArgumentsHost,
UnauthorizedException,
} from '@nestjs/common';
import { Response } from 'express';
@Catch(UnauthorizedException)
export class AuthExceptionFilter implements ExceptionFilter {
catch(exception: UnauthorizedException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const message = exception.message || 'Unauthorized';
// Check if message matches specific condition
if (message.toLocaleLowerCase() === 'authentication failed') {
// Clear cookies
response.clearCookie('access_token', {
httpOnly: true,
secure: true,
sameSite: 'none',
});
response.clearCookie('refresh_token', {
httpOnly: true,
secure: true,
sameSite: 'none',
});
// Send custom response
return response.status(status).json({
statusCode: status,
2025-07-11 11:30:58 +05:30
message: 'Authentication failed',
2025-07-10 17:06:39 +05:30
});
}
// If not a match, fallback to default response
return response.status(status).json({
statusCode: status,
message,
});
}
}