Files
twenty_crm/packages/twenty-server/src/utils/apply-cors-to-exceptions.ts
Pushpender 8f7ca6a0e3 Fix Google Auth displays Status: 401 on screen (#7659)
When the user presses the cancel button, the server sends the following
response:

![image](https://github.com/user-attachments/assets/cb68cf01-b32c-4680-a811-cd917db88ca9)

{"statusCode": 401, "message": "Unauthorized"}

Now, when the user clicks the cancel button, they are redirected to the
home page for login.

Related Issue
Fixes #7584

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
2024-10-18 00:21:57 +02:00

39 lines
1.1 KiB
TypeScript

import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
} from '@nestjs/common';
import { Response } from 'express';
// In case of exception in middleware run before the CORS middleware (eg: JSON Middleware that checks the request body),
// the CORS headers are missing in the response.
// This class add CORS headers to exception response to avoid misleading CORS error
@Catch()
export class ApplyCorsToExceptions implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
if (!response.header) {
return;
}
response.header('Access-Control-Allow-Origin', '*');
response.header(
'Access-Control-Allow-Methods',
'GET,HEAD,PUT,PATCH,POST,DELETE',
);
response.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept',
);
const status =
exception instanceof HttpException ? exception.getStatus() : 500;
response.status(status).json(exception.response);
}
}