import fs from 'node:fs'; import { promisify } from 'node:util'; import type express from 'express'; import { asyncErr, KError } from '../helpers'; import { Access, Account, User } from '../models'; import { obfuscateEmails, obfuscateKeywords, obfuscatePasswords } from './helpers'; import type { IdentifiedRequest } from './routes'; const readFile = promisify(fs.readFile); const writeFile = promisify(fs.writeFile); export async function getLogs(req: IdentifiedRequest, res: express.Response) { try { const { id: userId } = req.user; const user = await User.find(userId); if (!user?.isAdmin) { throw new KError('Administration rights are required', 403); } let logs = await readFile(process.kresus.logFilePath, 'utf-8'); const sensitiveKeywords: Set = new Set(); const passwords: Set = new Set(); const accounts = await Account.all(userId); accounts.forEach(acc => { if (acc.accessId) { sensitiveKeywords.add(String(acc.accessId)); } if (acc.vendorAccountId) { sensitiveKeywords.add(acc.vendorAccountId); } if (acc.iban) { sensitiveKeywords.add(acc.iban); } }); const accesses = await Access.all(userId); accesses.forEach(acc => { acc.fields.forEach(field => { if (field.name === 'password') { passwords.add(field.value); } else if (field.name === 'login') { sensitiveKeywords.add(field.value); } }); }); if (process.kresus.smtpUser) { sensitiveKeywords.add(process.kresus.smtpUser); } if (process.kresus.smtpPassword) { passwords.add(process.kresus.smtpPassword); } logs = obfuscateKeywords(logs, sensitiveKeywords); logs = obfuscatePasswords(logs, passwords); logs = obfuscateEmails(logs); res.status(200).type('text/plain').send(logs); } catch (err) { asyncErr(res, err, `when reading logs from ${process.kresus.logFilePath}`); } } export async function clearLogs(req: IdentifiedRequest, res: express.Response) { try { const { id: userId } = req.user; const user = await User.find(userId); if (!user?.isAdmin) { throw new KError('Administration rights are required', 403); } await writeFile(process.kresus.logFilePath, ''); res.status(200).end(); } catch (err) { asyncErr(res, err, 'when clearing logs'); } }