47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
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,
|
|
message: 'Authentication failed',
|
|
});
|
|
}
|
|
|
|
// If not a match, fallback to default response
|
|
return response.status(status).json({
|
|
statusCode: status,
|
|
message,
|
|
});
|
|
}
|
|
}
|