forked from EvolutionAPI/evolution-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.guard.ts
More file actions
108 lines (98 loc) · 4.61 KB
/
auth.guard.ts
File metadata and controls
108 lines (98 loc) · 4.61 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { InstanceDto } from '@api/dto/instance.dto';
import { cache, prismaRepository, waMonitor } from '@api/server.module';
import { Integration } from '@api/types/wa.types';
import { Auth, configService, Database } from '@config/env.config';
import { Logger } from '@config/logger.config';
import { ForbiddenException, UnauthorizedException } from '@exceptions';
import { NextFunction, Request, Response } from 'express';
const logger = new Logger('GUARD');
async function apikey(req: Request, _: Response, next: NextFunction) {
const env = configService.get<Auth>('AUTHENTICATION').API_KEY;
const key = req.get('apikey');
const db = configService.get<Database>('DATABASE');
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 {
if (param?.instanceName) {
const instance = await prismaRepository.instance.findUnique({
where: { name: param.instanceName },
});
const keyToCompare = key.length > 255 ? key.substring(0, 255) : key;
if (instance.token === keyToCompare) {
// Se o token fornecido é maior que 255 e a instância é WhatsApp Business, salva no cache
if (key.length > 255 && instance.integration === Integration.WHATSAPP_BUSINESS) {
const cacheKey = `instance:${param.instanceName}:fullToken`;
await cache.set(cacheKey, key, 0);
logger.log({ message: 'Stored full token in cache from request', instanceName: param.instanceName });
// Atualiza a instância em memória se existir
if (waMonitor.waInstances[param.instanceName]) {
const waInstance = waMonitor.waInstances[param.instanceName];
if (waInstance && typeof (waInstance as any).setInstance === 'function') {
try {
await (waInstance as any).setInstance({
instanceName: param.instanceName,
instanceId: instance.id,
integration: instance.integration,
token: key,
number: instance.number,
businessId: instance.businessId,
});
logger.log({ message: 'Updated full token in memory', instanceName: param.instanceName });
} catch (error) {
logger.error({ message: 'Error updating token in memory', error, instanceName: param.instanceName });
}
}
}
}
return next();
}
} else {
if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) {
const keyToCompare = key.length > 255 ? key.substring(0, 255) : key;
const instanceByKey = await prismaRepository.instance.findFirst({
where: { token: keyToCompare },
});
if (instanceByKey) {
// Se o token fornecido é maior que 255 e a instância é WhatsApp Business, salva no cache
if (key.length > 255 && instanceByKey.integration === Integration.WHATSAPP_BUSINESS) {
const cacheKey = `instance:${instanceByKey.name}:fullToken`;
await cache.set(cacheKey, key, 0);
logger.log({ message: 'Stored full token in cache from request', instanceName: instanceByKey.name });
// Atualiza a instância em memória se existir
if (waMonitor.waInstances[instanceByKey.name]) {
const waInstance = waMonitor.waInstances[instanceByKey.name];
if (waInstance && typeof (waInstance as any).setInstance === 'function') {
try {
await (waInstance as any).setInstance({
instanceName: instanceByKey.name,
instanceId: instanceByKey.id,
integration: instanceByKey.integration,
token: key,
number: instanceByKey.number,
businessId: instanceByKey.businessId,
});
logger.log({ message: 'Updated full token in memory', instanceName: instanceByKey.name });
} catch (error) {
logger.error({ message: 'Error updating token in memory', error, instanceName: instanceByKey.name });
}
}
}
}
return next();
}
}
}
} catch (error) {
logger.error(error);
}
throw new UnauthorizedException();
}
export const authGuard = { apikey };