fix: cors issue for http server

This commit is contained in:
abdou6666 2025-01-23 15:44:22 +01:00 committed by Mohamed Marrouchi
parent af7b8e7204
commit d9ef2152b7
3 changed files with 34 additions and 2 deletions

View File

@ -22,6 +22,7 @@ import { HexabotModule } from './app.module';
import { config } from './config';
import { LoggerService } from './logger/logger.service';
import { seedDatabase } from './seeder';
import { SettingService } from './setting/services/setting.service';
import { swagger } from './swagger';
import { getSessionStore } from './utils/constants/session-store';
import { ObjectIdPipe } from './utils/pipes/object-id.pipe';
@ -43,8 +44,16 @@ async function bootstrap() {
app.use(bodyParser.urlencoded({ verify: rawBodyBuffer, extended: true }));
app.use(bodyParser.json({ verify: rawBodyBuffer }));
const settingService = app.get<SettingService>(SettingService);
const allowedDomains = await settingService.getAllowedDomains();
app.enableCors({
origin: config.security.cors.allowOrigins,
origin: (origin, callback) => {
if (!origin || allowedDomains.has(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
methods: config.security.cors.methods,
credentials: config.security.cors.allowCredentials,
allowedHeaders: config.security.cors.headers.split(','),

View File

@ -14,7 +14,10 @@ import { Cache } from 'cache-manager';
import { config } from '@/config';
import { Config } from '@/config/types';
import { LoggerService } from '@/logger/logger.service';
import { SETTING_CACHE_KEY } from '@/utils/constants/cache';
import {
ALLOWED_DOMAINS_CACHE_KEY,
SETTING_CACHE_KEY,
} from '@/utils/constants/cache';
import { Cacheable } from '@/utils/decorators/cacheable.decorator';
import { BaseService } from '@/utils/generics/base-service';
@ -110,6 +113,7 @@ export class SettingService extends BaseService<Setting> {
*/
async clearCache() {
this.cacheManager.del(SETTING_CACHE_KEY);
this.cacheManager.del(ALLOWED_DOMAINS_CACHE_KEY);
}
/**
@ -121,6 +125,23 @@ export class SettingService extends BaseService<Setting> {
this.clearCache();
}
/**
* Retrieves allowed_domains from the cache if available, or loads them from the
* repository and caches the result.
*
* @returns A promise that resolves to a Set of`allowed_domains` string.
*/
@Cacheable(ALLOWED_DOMAINS_CACHE_KEY)
async getAllowedDomains() {
// combines all allowed_doamins and whitelist them for cors
const settings = await this.find({ label: 'allowed_domains' });
const whiteListedOrigins = new Set(
settings.flatMap((setting) => setting.value.split(',')),
);
return whiteListedOrigins;
}
/**
* Retrieves settings from the cache if available, or loads them from the
* repository and caches the result.

View File

@ -16,3 +16,5 @@ export const MENU_CACHE_KEY = 'menu';
export const LANGUAGES_CACHE_KEY = 'languages';
export const DEFAULT_LANGUAGE_CACHE_KEY = 'default_language';
export const ALLOWED_DOMAINS_CACHE_KEY = 'allowed-domains';