Fix jwt-token

This commit is contained in:
2025-09-20 20:41:30 +02:00
parent 11b460dc07
commit 8ed1c141eb
7 changed files with 1148 additions and 1 deletions

View File

@@ -1304,4 +1304,261 @@ router.post('/tenants/:tenantId/deactivate', async (req, res) => {
}
});
/**
* GET /management/audit-logs
* Retrieve security audit logs with filtering and pagination
*/
router.get('/audit-logs', requireManagementAuth, async (req, res) => {
try {
const {
page = 1,
limit = 50,
level,
action,
tenantId,
userId,
startDate,
endDate,
search
} = req.query;
// Build where clause for filtering
const where = {};
if (level) {
where.level = level.toUpperCase();
}
if (action) {
where.action = { [Op.like]: `%${action}%` };
}
if (tenantId) {
where.tenant_id = tenantId;
}
if (userId) {
where.user_id = userId;
}
if (startDate || endDate) {
where.timestamp = {};
if (startDate) {
where.timestamp[Op.gte] = new Date(startDate);
}
if (endDate) {
where.timestamp[Op.lte] = new Date(endDate);
}
}
if (search) {
where[Op.or] = [
{ message: { [Op.like]: `%${search}%` } },
{ username: { [Op.like]: `%${search}%` } },
{ tenant_slug: { [Op.like]: `%${search}%` } }
];
}
// Calculate offset for pagination
const offset = (parseInt(page) - 1) * parseInt(limit);
// Get audit logs with associated data
const { AuditLog } = require('../models');
const { count, rows: auditLogs } = await AuditLog.findAndCountAll({
where,
include: [
{
model: User,
as: 'user',
attributes: ['id', 'username', 'email'],
required: false
},
{
model: Tenant,
as: 'tenant',
attributes: ['id', 'name', 'slug'],
required: false
}
],
order: [['timestamp', 'DESC']],
limit: parseInt(limit),
offset: offset
});
// Calculate pagination info
const totalPages = Math.ceil(count / parseInt(limit));
const hasNextPage = parseInt(page) < totalPages;
const hasPrevPage = parseInt(page) > 1;
// Log the management access
console.log(`[MANAGEMENT AUDIT] ${new Date().toISOString()} - Admin ${req.managementUser.username} accessed audit logs`);
res.json({
success: true,
data: {
auditLogs,
pagination: {
currentPage: parseInt(page),
totalPages,
totalCount: count,
limit: parseInt(limit),
hasNextPage,
hasPrevPage
},
filters: {
level,
action,
tenantId,
userId,
startDate,
endDate,
search
}
}
});
} catch (error) {
console.error('Management: Error retrieving audit logs:', error);
res.status(500).json({
success: false,
message: 'Failed to retrieve audit logs'
});
}
});
/**
* GET /management/audit-logs/actions
* Get list of available audit log actions for filtering
*/
router.get('/audit-logs/actions', requireManagementAuth, async (req, res) => {
try {
const { AuditLog } = require('../models');
const actions = await AuditLog.findAll({
attributes: [[AuditLog.sequelize.fn('DISTINCT', AuditLog.sequelize.col('action')), 'action']],
where: {
action: { [Op.ne]: null }
},
raw: true
});
res.json({
success: true,
data: actions.map(item => item.action).filter(Boolean).sort()
});
} catch (error) {
console.error('Management: Error retrieving audit log actions:', error);
res.status(500).json({
success: false,
message: 'Failed to retrieve audit log actions'
});
}
});
/**
* GET /management/audit-logs/summary
* Get audit log summary statistics
*/
router.get('/audit-logs/summary', requireManagementAuth, async (req, res) => {
try {
const { timeframe = '24h' } = req.query;
// Calculate time range
const now = new Date();
let startTime;
switch (timeframe) {
case '1h':
startTime = new Date(now.getTime() - 60 * 60 * 1000);
break;
case '24h':
startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000);
break;
case '7d':
startTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
break;
case '30d':
startTime = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
break;
default:
startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000);
}
const { AuditLog } = require('../models');
// Get summary statistics
const [totalLogs, successfulActions, failedActions, warningActions, criticalActions] = await Promise.all([
AuditLog.count({
where: { timestamp: { [Op.gte]: startTime } }
}),
AuditLog.count({
where: {
timestamp: { [Op.gte]: startTime },
success: true
}
}),
AuditLog.count({
where: {
timestamp: { [Op.gte]: startTime },
success: false
}
}),
AuditLog.count({
where: {
timestamp: { [Op.gte]: startTime },
level: 'WARNING'
}
}),
AuditLog.count({
where: {
timestamp: { [Op.gte]: startTime },
level: 'CRITICAL'
}
})
]);
// Get top actions
const topActions = await AuditLog.findAll({
attributes: [
'action',
[AuditLog.sequelize.fn('COUNT', AuditLog.sequelize.col('action')), 'count']
],
where: {
timestamp: { [Op.gte]: startTime },
action: { [Op.ne]: null }
},
group: ['action'],
order: [[AuditLog.sequelize.literal('count'), 'DESC']],
limit: 10,
raw: true
});
res.json({
success: true,
data: {
timeframe,
period: {
start: startTime.toISOString(),
end: now.toISOString()
},
summary: {
totalLogs,
successfulActions,
failedActions,
warningActions,
criticalActions
},
topActions
}
});
} catch (error) {
console.error('Management: Error retrieving audit log summary:', error);
res.status(500).json({
success: false,
message: 'Failed to retrieve audit log summary'
});
}
});
module.exports = router;

View File

@@ -17,6 +17,10 @@ const { securityLogger } = require('../middleware/logger');
// Initialize multi-tenant auth
const multiAuth = new MultiTenantAuth();
// Initialize SecurityLogger with models
const models = require('../models');
securityLogger.setModels(models);
// Configure multer for logo uploads
const storage = multer.diskStorage({
destination: function (req, file, cb) {