Fix authentication issue in instance creation

This commit is contained in:
Latta 2024-10-31 14:46:42 +01:00
parent 1665654676
commit cbf18b8914

View File

@ -13,28 +13,18 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
const db = configService.get<Database>('DATABASE'); const db = configService.get<Database>('DATABASE');
if (!key) { if (!key) {
throw new UnauthorizedException(); throw new UnauthorizedException('API key is missing');
} }
if (env.KEY === key) { if (env.KEY === key) {
return next(); return next();
} }
if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) { const isInstanceCreation = req.originalUrl.includes('/instance/create');
throw new ForbiddenException('Missing global api key', 'The global api key must be set'); const isFetchInstances = req.originalUrl.includes('/instance/fetchInstances');
}
const param = req.params as unknown as InstanceDto;
try { if (isInstanceCreation || isFetchInstances) {
if (param?.instanceName) { if (db.SAVE_DATA.INSTANCE) {
const instance = await prismaRepository.instance.findUnique({
where: { name: param.instanceName },
});
if (instance.token === key) {
return next();
}
} else {
if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) {
const instanceByKey = await prismaRepository.instance.findFirst({ const instanceByKey = await prismaRepository.instance.findFirst({
where: { token: key }, where: { token: key },
}); });
@ -42,12 +32,28 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
return next(); return next();
} }
} }
if (isInstanceCreation) {
throw new ForbiddenException('Invalid API key for instance creation', 'The provided API key is not authorized to create instances');
}
}
const param = req.params as unknown as InstanceDto;
try {
if (param?.instanceName) {
const instance = await prismaRepository.instance.findUnique({
where: { name: param.instanceName },
});
if (instance && instance.token === key) {
return next();
}
} }
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
} }
throw new UnauthorizedException(); throw new UnauthorizedException('Invalid API key');
} }
export const authGuard = { apikey }; export const authGuard = { apikey };