Skip to content

Commit

Permalink
Now in the manager, when logging in with the client's apikey, the lis…
Browse files Browse the repository at this point in the history
…ting only shows the instance corresponding to the provided apikey (only with MongoDB)
  • Loading branch information
DavidsonGomes committed May 23, 2024
1 parent 395b81a commit 2fcb476
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 13 deletions.
30 changes: 23 additions & 7 deletions src/api/controllers/instance.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2';
import { v4 } from 'uuid';

import { ConfigService, HttpServer, WaBusiness } from '../../config/env.config';
import { Auth, ConfigService, HttpServer, WaBusiness } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { BadRequestException, InternalServerErrorException } from '../../exceptions';
import { BadRequestException, InternalServerErrorException, UnauthorizedException } from '../../exceptions';
import { InstanceDto, SetPresenceDto } from '../dto/instance.dto';
import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service';
import { RabbitmqService } from '../integrations/rabbitmq/services/rabbitmq.service';
Expand Down Expand Up @@ -679,11 +679,27 @@ export class InstanceController {
};
}

public async fetchInstances({ instanceName, instanceId, number }: InstanceDto) {
if (instanceName) {
this.logger.verbose('requested fetchInstances from ' + instanceName + ' instance');
this.logger.verbose('instanceName: ' + instanceName);
return this.waMonitor.instanceInfo(instanceName);
public async fetchInstances({ instanceName, instanceId, number }: InstanceDto, key: string) {
const env = this.configService.get<Auth>('AUTHENTICATION').API_KEY;

let name = instanceName;
let arrayReturn = false;

if (env.KEY !== key) {
const instanceByKey = await this.repository.auth.findByKey(key);
console.log('instanceByKey', instanceByKey);
if (instanceByKey) {
name = instanceByKey._id;
arrayReturn = true;
} else {
throw new UnauthorizedException();
}
}

if (name) {
this.logger.verbose('requested fetchInstances from ' + name + ' instance');
this.logger.verbose('instanceName: ' + name);
return this.waMonitor.instanceInfo(name, arrayReturn);
} else if (instanceId || number) {
return this.waMonitor.instanceInfoById(instanceId, number);
}
Expand Down
19 changes: 15 additions & 4 deletions src/api/guards/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,30 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
const env = configService.get<Auth>('AUTHENTICATION').API_KEY;
const key = req.get('apikey');

if (!key) {
throw new UnauthorizedException();
}

if (env.KEY === key) {
return next();
}

if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
throw new ForbiddenException('Missing global api key', 'The global api key must be set');
}
const param = req.params as unknown as InstanceDto;

try {
const param = req.params as unknown as InstanceDto;
const instanceKey = await repository.auth.find(param.instanceName);
if (instanceKey.apikey === key) {
return next();
if (param?.instanceName) {
const instanceKey = await repository.auth.find(param.instanceName);
if (instanceKey?.apikey === key) {
return next();
}
} else {
const instanceByKey = await repository.auth.findByKey(key);
if (instanceByKey) {
return next();
}
}
} catch (error) {
logger.error(error);
Expand Down
14 changes: 14 additions & 0 deletions src/api/repository/auth.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,20 @@ export class AuthRepository extends Repository {
}
}

public async findByKey(key: string): Promise<AuthRaw> {
try {
this.logger.verbose('finding auth');
if (this.dbSettings.ENABLED) {
this.logger.verbose('finding auth in db');
return await this.authModel.findOne({ apikey: key });
}

return {};
} catch (error) {
return {};
}
}

public async list(): Promise<AuthRaw[]> {
try {
if (this.dbSettings.ENABLED) {
Expand Down
4 changes: 3 additions & 1 deletion src/api/routes/instance.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,15 @@ export class InstanceRouter extends RouterBroker {
logger.verbose('request body: ');
logger.verbose(req.body);

const key = req.get('apikey');

logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({
request: req,
schema: null,
ClassRef: InstanceDto,
execute: (instance) => instanceController.fetchInstances(instance),
execute: (instance) => instanceController.fetchInstances(instance, key),
});

return res.status(HttpStatus.OK).json(response);
Expand Down
5 changes: 4 additions & 1 deletion src/api/services/monitor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class WAMonitoringService {
}
}

public async instanceInfo(instanceName?: string) {
public async instanceInfo(instanceName?: string, arrayReturn = false) {
this.logger.verbose('get instance info');
if (instanceName && !this.waInstances[instanceName]) {
throw new NotFoundException(`Instance "${instanceName}" not found`);
Expand Down Expand Up @@ -171,6 +171,9 @@ export class WAMonitoringService {

this.logger.verbose('return instance info: ' + instances.length);

if (arrayReturn) {
return [instances.find((i) => i.instance.instanceName === instanceName) ?? instances];
}
return instances.find((i) => i.instance.instanceName === instanceName) ?? instances;
}

Expand Down

0 comments on commit 2fcb476

Please sign in to comment.