Fix IP in ProvaService.ts and Add PUBLIC_URL
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
8dfe0d6f94
commit
949694fcfc
6 files changed
+305
-28
No files matched your search
@@ -27,29 +27,34 @@ export function VerificarProva() {
|
|||||||
const [loading, setLoading] = useState<boolean>(true);
|
const [loading, setLoading] = useState<boolean>(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchProva = async () => {
|
const fetchProvaDetails = async () => {
|
||||||
try {
|
try {
|
||||||
setLoading(true);
|
// Obter informações de conexão do cliente para incluir nos logs
|
||||||
const response = await fetch(`/api/provas/verificar/${hash}`);
|
// Estas informações serão enviadas junto com a solicitação de verificação
|
||||||
|
const connectionInfo = {
|
||||||
|
userAgent: navigator.userAgent,
|
||||||
|
language: navigator.language,
|
||||||
|
platform: navigator.platform,
|
||||||
|
screenWidth: window.screen.width,
|
||||||
|
screenHeight: window.screen.height,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
};
|
||||||
|
|
||||||
if (!response.ok) {
|
// Fazer a requisição para verificar a prova, incluindo informações do cliente
|
||||||
throw new Error(response.statusText || 'Falha na verificação');
|
const response = await api.post(`/provas/verificar/${hash}`, {
|
||||||
}
|
verificationContext: connectionInfo
|
||||||
|
});
|
||||||
|
|
||||||
const data = await response.json();
|
setResult(response.data);
|
||||||
console.log('Dados recebidos:', data);
|
setLoading(false);
|
||||||
setResult(data);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao verificar:', error);
|
console.error('Erro ao verificar prova:', error);
|
||||||
setError('Não foi possível verificar a autenticidade do documento.');
|
setError('Não foi possível verificar este documento. O hash pode ser inválido ou o documento não existe.');
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (hash) {
|
fetchProvaDetails();
|
||||||
fetchProva();
|
|
||||||
}
|
|
||||||
}, [hash]);
|
}, [hash]);
|
||||||
|
|
||||||
// Função segura para formatar datas
|
// Função segura para formatar datas
|
||||||
|
|||||||
@@ -14,6 +14,11 @@ dotenv.config();
|
|||||||
const app = express();
|
const app = express();
|
||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
// Configurar para confiar em proxies, permitindo a leitura de X-Forwarded-For
|
||||||
|
// Isso é necessário se sua aplicação estiver atrás de um balanceador de carga,
|
||||||
|
// proxy reverso ou Cloudflare
|
||||||
|
app.set('trust proxy', true);
|
||||||
|
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.use(bodyParser.json());
|
app.use(bodyParser.json());
|
||||||
app.use(bodyParser.urlencoded({ extended: true }));
|
app.use(bodyParser.urlencoded({ extended: true }));
|
||||||
@@ -24,6 +29,7 @@ app.use('/api/indices', indicesMonetariosRoutes);
|
|||||||
app.use('/api/pensao-alimenticia', pensaoAlimenticiaRoutes);
|
app.use('/api/pensao-alimenticia', pensaoAlimenticiaRoutes);
|
||||||
|
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
app.use(express.static(path.join(__dirname, 'public')));
|
||||||
|
app.set('trust proxy', true); // Importante para obter o IP real em ambientes com proxy
|
||||||
|
|
||||||
const PORT = process.env.PORT || 5000;
|
const PORT = process.env.PORT || 5000;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import { Request, Response, NextFunction } from 'express';
|
||||||
|
|
||||||
|
export const ipDetectionMiddleware = (req: Request, res: Response, next: NextFunction) => {
|
||||||
|
// Extrair o endereço IP real
|
||||||
|
req.realIP = determineRealIP(req);
|
||||||
|
|
||||||
|
// Registrar a detecção para debug
|
||||||
|
console.log(`Requisição de ${req.realIP} (original: ${req.ip})`);
|
||||||
|
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
|
||||||
|
function determineRealIP(req: Request): string {
|
||||||
|
// Array de possíveis fontes de IP, em ordem de preferência
|
||||||
|
const ipSources = [
|
||||||
|
req.headers['x-forwarded-for'],
|
||||||
|
req.headers['x-real-ip'],
|
||||||
|
req.headers['cf-connecting-ip'],
|
||||||
|
req.ip,
|
||||||
|
req.socket?.remoteAddress
|
||||||
|
];
|
||||||
|
|
||||||
|
// Filtrar valores nulos e processar x-forwarded-for que pode conter múltiplos IPs
|
||||||
|
for (const source of ipSources) {
|
||||||
|
if (source) {
|
||||||
|
// x-forwarded-for pode ter múltiplos IPs separados por vírgula
|
||||||
|
if (typeof source === 'string' && source.includes(',')) {
|
||||||
|
const firstIP = source.split(',')[0].trim();
|
||||||
|
if (firstIP && isValidIP(firstIP)) return firstIP;
|
||||||
|
} else if (isValidIP(source as string)) {
|
||||||
|
return source as string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback para um valor padrão se nenhum IP válido for encontrado
|
||||||
|
return '0.0.0.0';
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidIP(ip: string): boolean {
|
||||||
|
// Função simples para verificar se uma string parece um IP válido
|
||||||
|
return !!ip && ip !== 'unknown' && ip !== '::1' && ip !== 'localhost';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Estender a interface Request para incluir a propriedade realIP
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request {
|
||||||
|
realIP: string;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -175,15 +175,57 @@ router.get('/:id/status', async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Verificar documento
|
// Rota de verificação
|
||||||
router.get('/verificar/:hash', async (req, res) => {
|
router.get('/verificar/:hash', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { hash } = req.params;
|
const { hash } = req.params;
|
||||||
|
|
||||||
|
// Coletar informações de conexão do cliente
|
||||||
|
const clientInfo = {
|
||||||
|
ipAddress: req.ip,
|
||||||
|
remoteAddress: req.socket?.remoteAddress,
|
||||||
|
headers: req.headers,
|
||||||
|
userAgent: req.headers['user-agent'],
|
||||||
|
verificadoEm: new Date().toISOString()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Instanciar o serviço e verificar a prova
|
||||||
|
const provaService = new ProvaService();
|
||||||
const result = await provaService.verifyFile(hash);
|
const result = await provaService.verifyFile(hash);
|
||||||
res.json(result);
|
|
||||||
|
// Registrar a verificação no log de acessos (opcional)
|
||||||
|
try {
|
||||||
|
await prisma.verificacaoProva.create({
|
||||||
|
data: {
|
||||||
|
provaId: result.prova?.id,
|
||||||
|
hash,
|
||||||
|
ipAddress: req.headers['x-forwarded-for'] || req.ip || '127.0.0.1',
|
||||||
|
userAgent: req.headers['user-agent'] || 'Desconhecido',
|
||||||
|
timestamp: new Date(),
|
||||||
|
success: result.verified,
|
||||||
|
metadata: clientInfo
|
||||||
|
}
|
||||||
|
});
|
||||||
|
console.log('Verificação registrada com sucesso');
|
||||||
|
} catch (logError) {
|
||||||
|
console.error('Erro ao registrar verificação:', logError);
|
||||||
|
// Não interromper o fluxo por erro de log
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retornar os dados da verificação
|
||||||
|
return res.status(200).json({
|
||||||
|
...result,
|
||||||
|
verificacao: {
|
||||||
|
timestamp: new Date(),
|
||||||
|
ip: req.headers['x-forwarded-for'] || req.ip || '127.0.0.1'
|
||||||
|
}
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao verificar documento:', error);
|
console.error('Erro ao verificar arquivo:', error);
|
||||||
res.status(500).json({ error: 'Erro ao verificar documento' });
|
return res.status(500).json({
|
||||||
|
verified: false,
|
||||||
|
message: `Erro ao verificar: ${error.message}`
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -6,8 +6,10 @@ import * as fs from 'fs/promises';
|
|||||||
import * as path from 'path';
|
import * as path from 'path';
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
import { BlockchainService } from './BlockchainService';
|
import { BlockchainService } from './BlockchainService';
|
||||||
|
import { ipDetectionMiddleware } from '../middleware/ipDetection';
|
||||||
import { FileValidator } from './FileValidator';
|
import { FileValidator } from './FileValidator';
|
||||||
import { ReportGenerator } from './ReportGenerator'; // Adicionar import
|
import { ReportGenerator } from './ReportGenerator'; // Adicionar import
|
||||||
|
import { Request, Response } from 'express'; // Importar Request e Response
|
||||||
|
|
||||||
// Tentativa de importar o MetadataCollector com fallback
|
// Tentativa de importar o MetadataCollector com fallback
|
||||||
let MetadataCollectorClass;
|
let MetadataCollectorClass;
|
||||||
@@ -66,9 +68,12 @@ export class ProvaService {
|
|||||||
// 2. Coletar metadados avançados (com tratamento de erro)
|
// 2. Coletar metadados avançados (com tratamento de erro)
|
||||||
let enhancedMetadata;
|
let enhancedMetadata;
|
||||||
try {
|
try {
|
||||||
|
// Garantir que estamos usando o IP real do cliente
|
||||||
|
const clientIP = this.extractRealClientIP(metadata.ipAddress, metadata);
|
||||||
|
|
||||||
enhancedMetadata = await this.metadataCollector.collectMetadata({
|
enhancedMetadata = await this.metadataCollector.collectMetadata({
|
||||||
userAgent: metadata.userAgent,
|
userAgent: metadata.userAgent,
|
||||||
ipAddress: metadata.ipAddress || '0.0.0.0',
|
ipAddress: clientIP,
|
||||||
timestamp: new Date(metadata.timestamp),
|
timestamp: new Date(metadata.timestamp),
|
||||||
fileName: file.originalname,
|
fileName: file.originalname,
|
||||||
fileModified: metadata.modification_times ? new Date(parseInt(metadata.modification_times)) : undefined,
|
fileModified: metadata.modification_times ? new Date(parseInt(metadata.modification_times)) : undefined,
|
||||||
@@ -99,7 +104,7 @@ export class ProvaService {
|
|||||||
const processedFile = await this.processFileByType(file);
|
const processedFile = await this.processFileByType(file);
|
||||||
|
|
||||||
// 6. Gerar URL de verificação
|
// 6. Gerar URL de verificação
|
||||||
const verificationUrl = `${process.env.BACKEND_URL || 'http://localhost:5000'}/verificar/${checksums.sha256}`;
|
const verificationUrl = `${process.env.PUBLIC_URL || 'http://localhost:5000'}/verificar/${checksums.sha256}`;
|
||||||
|
|
||||||
// 7. Gerar relatório
|
// 7. Gerar relatório
|
||||||
const reportResult = await this.reportGenerator.generateReport({
|
const reportResult = await this.reportGenerator.generateReport({
|
||||||
@@ -147,6 +152,75 @@ export class ProvaService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extrai o endereço IP real do cliente, ignorando IPs locais quando possível
|
||||||
|
* @param ipAddress O endereço IP fornecido na requisição
|
||||||
|
* @param metadata Metadados adicionais para análise
|
||||||
|
* @returns O endereço IP real do cliente
|
||||||
|
*/
|
||||||
|
private extractRealClientIP(ipAddress: string, metadata?: any): string {
|
||||||
|
// Verificar se temos dados válidos para trabalhar
|
||||||
|
if (!metadata) {
|
||||||
|
return ipAddress || '0.0.0.0';
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Tentando extrair IP real. IP original:', ipAddress);
|
||||||
|
|
||||||
|
// Lista de IPs locais/internos que devem ser evitados
|
||||||
|
const localIPs = ['::1', '127.0.0.1', 'localhost', '::ffff:127.0.0.1', '::ffff:10.15.0.1'];
|
||||||
|
|
||||||
|
// Verificar PRIMEIRO os headers HTTP que são a fonte mais confiável em produção
|
||||||
|
if (metadata.headers) {
|
||||||
|
// Headers comuns que podem conter o IP real
|
||||||
|
if (metadata.headers['x-forwarded-for']) {
|
||||||
|
const forwardedIps = metadata.headers['x-forwarded-for'].split(',').map(ip => ip.trim());
|
||||||
|
if (forwardedIps.length > 0 && !localIPs.includes(forwardedIps[0])) {
|
||||||
|
console.log('Usando IP do x-forwarded-for:', forwardedIps[0]);
|
||||||
|
return forwardedIps[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Outros headers comuns
|
||||||
|
const otherHeaders = ['x-real-ip', 'cf-connecting-ip', 'true-client-ip'];
|
||||||
|
for (const header of otherHeaders) {
|
||||||
|
if (metadata.headers[header] && !localIPs.includes(metadata.headers[header])) {
|
||||||
|
console.log(`Usando IP do header ${header}:`, metadata.headers[header]);
|
||||||
|
return metadata.headers[header];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar nas informações de conexão
|
||||||
|
if (metadata.connectionInfo && metadata.connectionInfo.forwardedIp) {
|
||||||
|
if (!localIPs.includes(metadata.connectionInfo.forwardedIp)) {
|
||||||
|
console.log('Usando IP encaminhado da conexão:', metadata.connectionInfo.forwardedIp);
|
||||||
|
return metadata.connectionInfo.forwardedIp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se o IP não é local, usá-lo
|
||||||
|
if (ipAddress && !localIPs.includes(ipAddress)) {
|
||||||
|
console.log('Usando IP original:', ipAddress);
|
||||||
|
return ipAddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se chegamos aqui, temos apenas IPs locais. Usar o IP com a porta como identificador
|
||||||
|
const port = metadata.clientPort ||
|
||||||
|
metadata.connectionInfo?.socketPort ||
|
||||||
|
metadata.porta;
|
||||||
|
|
||||||
|
if (port) {
|
||||||
|
const ipWithPort = `${ipAddress || '127.0.0.1'}:${port}`;
|
||||||
|
console.log('Usando identificador IP:porta:', ipWithPort);
|
||||||
|
return ipWithPort;
|
||||||
|
}
|
||||||
|
|
||||||
|
// NUNCA retornar 0.0.0.0 - se nada funcionar, usar 127.0.0.1 com timestamp
|
||||||
|
const fallbackIp = `127.0.0.1:${Date.now() % 10000}`;
|
||||||
|
console.log('Usando fallback:', fallbackIp);
|
||||||
|
return fallbackIp;
|
||||||
|
}
|
||||||
|
|
||||||
private generateChecksums(buffer: Buffer) {
|
private generateChecksums(buffer: Buffer) {
|
||||||
return {
|
return {
|
||||||
sha256: createHash('sha256').update(buffer).digest('hex'),
|
sha256: createHash('sha256').update(buffer).digest('hex'),
|
||||||
@@ -166,8 +240,15 @@ export class ProvaService {
|
|||||||
// 2. Obter tempo NTP do servidor oficial para maior confiabilidade
|
// 2. Obter tempo NTP do servidor oficial para maior confiabilidade
|
||||||
let ntpTime = '';
|
let ntpTime = '';
|
||||||
try {
|
try {
|
||||||
// Usar servidores NTP confiáveis para obter tempo preciso
|
// Detectar plataforma e usar o comando apropriado
|
||||||
|
if (process.platform === 'win32') {
|
||||||
|
// Windows
|
||||||
ntpTime = execSync('w32tm /stripchart /computer:time.nist.gov /samples:1 /dataonly').toString();
|
ntpTime = execSync('w32tm /stripchart /computer:time.nist.gov /samples:1 /dataonly').toString();
|
||||||
|
} else {
|
||||||
|
// Linux/Unix/MacOS - usar implementação alternativa
|
||||||
|
// Tentar usar o comando 'date' para obter a hora do sistema
|
||||||
|
ntpTime = execSync('date -u +"%Y-%m-%dT%H:%M:%S.%3NZ"').toString().trim();
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn('Não foi possível obter tempo NTP, usando tempo local:', e);
|
console.warn('Não foi possível obter tempo NTP, usando tempo local:', e);
|
||||||
}
|
}
|
||||||
@@ -190,7 +271,16 @@ export class ProvaService {
|
|||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao criar timestamp local:', error);
|
console.error('Erro ao criar timestamp local:', error);
|
||||||
throw new Error(`Falha ao criar timestamp: ${error.message}`);
|
// Em caso de erro, retornar um timestamp básico sem interromper o processo
|
||||||
|
const basicTimestamp = {
|
||||||
|
hash,
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
ntpReference: 'Indisponível (erro)',
|
||||||
|
unixTimestamp: Math.floor(Date.now() / 1000),
|
||||||
|
error: error.message
|
||||||
|
};
|
||||||
|
|
||||||
|
return basicTimestamp;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -295,3 +385,43 @@ export class ProvaService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// No handler de upload de arquivo:
|
||||||
|
export const uploadProva = async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const file = req.file;
|
||||||
|
if (!file) {
|
||||||
|
return res.status(400).json({ error: 'Nenhum arquivo enviado' });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Coletar todas as informações possíveis sobre o cliente
|
||||||
|
const metadata = {
|
||||||
|
ipAddress: req.ip, // Express geralmente fornece isso
|
||||||
|
remoteAddress: req.socket?.remoteAddress, // Endereço IP direto do socket
|
||||||
|
porta: req.socket?.remotePort?.toString(), // Porta de conexão do cliente
|
||||||
|
userAgent: req.headers['user-agent'],
|
||||||
|
headers: req.headers, // Todos os headers HTTP
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
// Outros metadados do formulário
|
||||||
|
...req.body
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log('Metadados de conexão:', {
|
||||||
|
ip: req.ip,
|
||||||
|
remoteAddress: req.socket?.remoteAddress,
|
||||||
|
remotePort: req.socket?.remotePort,
|
||||||
|
headers: {
|
||||||
|
'x-forwarded-for': req.headers['x-forwarded-for'],
|
||||||
|
'x-real-ip': req.headers['x-real-ip']
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const provaService = new ProvaService();
|
||||||
|
const result = await provaService.processFile(file, metadata);
|
||||||
|
|
||||||
|
return res.status(200).json(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao processar upload de prova:', error);
|
||||||
|
return res.status(500).json({ error: error.message });
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -458,11 +458,12 @@ export class ReportGenerator {
|
|||||||
this.drawLabelValue(page, "Idioma:", idioma, y, helvetica, helveticaBold);
|
this.drawLabelValue(page, "Idioma:", idioma, y, helvetica, helveticaBold);
|
||||||
y -= 15;
|
y -= 15;
|
||||||
|
|
||||||
// IP - CORRIGIDO PARA EVITAR N/A
|
// IP - Usar o X-Forwarded-For ou outras fontes confiáveis, evitando IPs locais
|
||||||
const ip = data.metadata?.ipAddress ||
|
const ip = this.extractRealClientIP(
|
||||||
data.metadata?.connectionInfo?.ip ||
|
data.metadata?.ipAddress,
|
||||||
data.metadata?.connectionInfo?.socketAddress ||
|
data.metadata?.connectionInfo?.forwardedIp,
|
||||||
"::1";
|
data.metadata?.headers?.['x-forwarded-for']
|
||||||
|
);
|
||||||
this.drawLabelValue(page, "IP:", ip, y, helvetica, helveticaBold);
|
this.drawLabelValue(page, "IP:", ip, y, helvetica, helveticaBold);
|
||||||
y -= 15;
|
y -= 15;
|
||||||
|
|
||||||
@@ -991,4 +992,45 @@ export class ReportGenerator {
|
|||||||
|
|
||||||
return yPosition;
|
return yPosition;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extrai o endereço IP real do cliente de várias fontes possíveis
|
||||||
|
* @param ipAddress IP básico
|
||||||
|
* @param forwardedIp IP encaminhado
|
||||||
|
* @param xForwardedFor Header X-Forwarded-For
|
||||||
|
* @returns O IP mais confiável encontrado
|
||||||
|
*/
|
||||||
|
private extractRealClientIP(ipAddress?: string, forwardedIp?: string, xForwardedFor?: string): string {
|
||||||
|
// Lista de IPs locais/internos que devem ser evitados
|
||||||
|
const localIPs = ['::1', '127.0.0.1', 'localhost', '::ffff:127.0.0.1', '::ffff:10.15.0.1'];
|
||||||
|
|
||||||
|
// Verificar primeiro X-Forwarded-For (mais confiável em ambientes de produção)
|
||||||
|
if (xForwardedFor) {
|
||||||
|
const ips = xForwardedFor.split(',').map(ip => ip.trim());
|
||||||
|
if (ips.length > 0 && !localIPs.includes(ips[0])) {
|
||||||
|
return ips[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar IP encaminhado (usado em alguns proxies)
|
||||||
|
if (forwardedIp && !localIPs.includes(forwardedIp)) {
|
||||||
|
return forwardedIp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar IP básico
|
||||||
|
if (ipAddress && !localIPs.includes(ipAddress)) {
|
||||||
|
return ipAddress;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se chegamos aqui e temos um X-Forwarded-For, mesmo que seja um IP local, usá-lo
|
||||||
|
if (xForwardedFor) {
|
||||||
|
const ips = xForwardedFor.split(',').map(ip => ip.trim());
|
||||||
|
if (ips.length > 0) {
|
||||||
|
return ips[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retornar IP básico se não encontrar melhor
|
||||||
|
return ipAddress || '0.0.0.0';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user