/
cors-origin-middleware.ts
36 lines (34 loc) · 1.17 KB
/
cors-origin-middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { RequestHandler } from 'express';
import cors from 'cors';
import { IUnleashConfig, IUnleashServices } from '../types';
export const allowRequestOrigin = (
requestOrigin: string,
allowedOrigins: string[],
): boolean => {
return allowedOrigins.some((allowedOrigin) => {
return allowedOrigin === requestOrigin || allowedOrigin === '*';
});
};
// Check the request's Origin header against a list of allowed origins.
// The list may include '*', which `cors` does not support natively.
export const corsOriginMiddleware = (
{ settingService }: Pick<IUnleashServices, 'settingService'>,
config: IUnleashConfig,
): RequestHandler => {
return cors(async (req, callback) => {
try {
const { frontendApiOrigins = [] } =
await settingService.getFrontendSettings();
callback(null, {
origin: allowRequestOrigin(
req.header('Origin'),
frontendApiOrigins,
),
maxAge: config.accessControlMaxAge,
exposedHeaders: 'ETag',
});
} catch (error) {
callback(error);
}
});
};