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

@@ -0,0 +1,519 @@
import React, { useState, useEffect } from 'react';
import { useTranslation } from '../../utils/tempTranslations';
const AuditLogs = () => {
const { t } = useTranslation();
const [auditLogs, setAuditLogs] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [filters, setFilters] = useState({
page: 1,
limit: 50,
level: '',
action: '',
tenantId: '',
userId: '',
startDate: '',
endDate: '',
search: ''
});
const [pagination, setPagination] = useState({});
const [availableActions, setAvailableActions] = useState([]);
const [summary, setSummary] = useState({});
useEffect(() => {
fetchAuditLogs();
fetchAvailableActions();
fetchSummary();
}, [filters]);
const fetchAuditLogs = async () => {
try {
setLoading(true);
const queryParams = new URLSearchParams();
Object.keys(filters).forEach(key => {
if (filters[key]) {
queryParams.append(key, filters[key]);
}
});
const token = localStorage.getItem('managementToken');
const response = await fetch(`/api/management/audit-logs?${queryParams}`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch audit logs');
}
const data = await response.json();
setAuditLogs(data.data.auditLogs);
setPagination(data.data.pagination);
setError(null);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
const fetchAvailableActions = async () => {
try {
const token = localStorage.getItem('managementToken');
const response = await fetch('/api/management/audit-logs/actions', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
setAvailableActions(data.data);
}
} catch (err) {
console.error('Failed to fetch available actions:', err);
}
};
const fetchSummary = async () => {
try {
const token = localStorage.getItem('managementToken');
const response = await fetch('/api/management/audit-logs/summary', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
setSummary(data.data);
}
} catch (err) {
console.error('Failed to fetch summary:', err);
}
};
const handleFilterChange = (key, value) => {
setFilters(prev => ({
...prev,
[key]: value,
page: 1 // Reset to first page when filtering
}));
};
const handlePageChange = (newPage) => {
setFilters(prev => ({
...prev,
page: newPage
}));
};
const formatTimestamp = (timestamp) => {
return new Date(timestamp).toLocaleString();
};
const getLevelBadgeClass = (level) => {
switch (level) {
case 'INFO':
return 'bg-blue-100 text-blue-800';
case 'WARNING':
return 'bg-yellow-100 text-yellow-800';
case 'ERROR':
return 'bg-red-100 text-red-800';
case 'CRITICAL':
return 'bg-red-200 text-red-900 font-bold';
default:
return 'bg-gray-100 text-gray-800';
}
};
const getSuccessIndicator = (success) => {
if (success === true) {
return <span className="text-green-600"></span>;
} else if (success === false) {
return <span className="text-red-600"></span>;
}
return <span className="text-gray-400">-</span>;
};
const clearFilters = () => {
setFilters({
page: 1,
limit: 50,
level: '',
action: '',
tenantId: '',
userId: '',
startDate: '',
endDate: '',
search: ''
});
};
return (
<div className="space-y-6">
{/* Header */}
<div className="flex justify-between items-center">
<h1 className="text-3xl font-bold text-gray-900">
{t('management.auditLogs') || 'Security Audit Logs'}
</h1>
<button
onClick={() => window.location.reload()}
className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md"
>
{t('common.refresh') || 'Refresh'}
</button>
</div>
{/* Summary Statistics */}
{summary.summary && (
<div className="grid grid-cols-1 md:grid-cols-5 gap-4">
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="p-5">
<div className="flex items-center">
<div className="w-0 flex-1">
<dl>
<dt className="text-sm font-medium text-gray-500 truncate">
{t('management.totalLogs') || 'Total Logs'}
</dt>
<dd className="text-lg font-medium text-gray-900">
{summary.summary.totalLogs}
</dd>
</dl>
</div>
</div>
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="p-5">
<div className="flex items-center">
<div className="w-0 flex-1">
<dl>
<dt className="text-sm font-medium text-gray-500 truncate">
{t('management.successfulActions') || 'Successful'}
</dt>
<dd className="text-lg font-medium text-green-600">
{summary.summary.successfulActions}
</dd>
</dl>
</div>
</div>
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="p-5">
<div className="flex items-center">
<div className="w-0 flex-1">
<dl>
<dt className="text-sm font-medium text-gray-500 truncate">
{t('management.failedActions') || 'Failed'}
</dt>
<dd className="text-lg font-medium text-red-600">
{summary.summary.failedActions}
</dd>
</dl>
</div>
</div>
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="p-5">
<div className="flex items-center">
<div className="w-0 flex-1">
<dl>
<dt className="text-sm font-medium text-gray-500 truncate">
{t('management.warnings') || 'Warnings'}
</dt>
<dd className="text-lg font-medium text-yellow-600">
{summary.summary.warningActions}
</dd>
</dl>
</div>
</div>
</div>
</div>
<div className="bg-white overflow-hidden shadow rounded-lg">
<div className="p-5">
<div className="flex items-center">
<div className="w-0 flex-1">
<dl>
<dt className="text-sm font-medium text-gray-500 truncate">
{t('management.critical') || 'Critical'}
</dt>
<dd className="text-lg font-medium text-red-800">
{summary.summary.criticalActions}
</dd>
</dl>
</div>
</div>
</div>
</div>
</div>
)}
{/* Filters */}
<div className="bg-white shadow rounded-lg p-6">
<h3 className="text-lg font-medium text-gray-900 mb-4">
{t('common.filters') || 'Filters'}
</h3>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
{/* Search */}
<div>
<label className="block text-sm font-medium text-gray-700">
{t('common.search') || 'Search'}
</label>
<input
type="text"
value={filters.search}
onChange={(e) => handleFilterChange('search', e.target.value)}
placeholder={t('management.searchPlaceholder') || 'Search logs...'}
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
/>
</div>
{/* Level */}
<div>
<label className="block text-sm font-medium text-gray-700">
{t('management.level') || 'Level'}
</label>
<select
value={filters.level}
onChange={(e) => handleFilterChange('level', e.target.value)}
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
>
<option value="">{t('common.all') || 'All'}</option>
<option value="INFO">INFO</option>
<option value="WARNING">WARNING</option>
<option value="ERROR">ERROR</option>
<option value="CRITICAL">CRITICAL</option>
</select>
</div>
{/* Action */}
<div>
<label className="block text-sm font-medium text-gray-700">
{t('management.action') || 'Action'}
</label>
<select
value={filters.action}
onChange={(e) => handleFilterChange('action', e.target.value)}
className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
>
<option value="">{t('common.all') || 'All'}</option>
{availableActions.map(action => (
<option key={action} value={action}>{action}</option>
))}
</select>
</div>
{/* Date Range */}
<div>
<label className="block text-sm font-medium text-gray-700">
{t('management.dateRange') || 'Date Range'}
</label>
<div className="flex space-x-2">
<input
type="date"
value={filters.startDate}
onChange={(e) => handleFilterChange('startDate', e.target.value)}
className="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
/>
<input
type="date"
value={filters.endDate}
onChange={(e) => handleFilterChange('endDate', e.target.value)}
className="flex-1 border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
/>
</div>
</div>
</div>
<div className="mt-4 flex justify-between">
<button
onClick={clearFilters}
className="text-sm text-gray-600 hover:text-gray-900"
>
{t('common.clearFilters') || 'Clear Filters'}
</button>
<span className="text-sm text-gray-500">
{pagination.totalCount} {t('management.totalEntries') || 'total entries'}
</span>
</div>
</div>
{/* Audit Logs Table */}
<div className="bg-white shadow overflow-hidden sm:rounded-md">
{loading ? (
<div className="p-6 text-center">
<div className="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
<span className="ml-2">{t('common.loading') || 'Loading...'}</span>
</div>
) : error ? (
<div className="p-6 text-center text-red-600">
{t('common.error') || 'Error'}: {error}
</div>
) : auditLogs.length === 0 ? (
<div className="p-6 text-center text-gray-500">
{t('management.noAuditLogs') || 'No audit logs found'}
</div>
) : (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.timestamp') || 'Timestamp'}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.level') || 'Level'}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.action') || 'Action'}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.user') || 'User'}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.tenant') || 'Tenant'}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.message') || 'Message'}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.success') || 'Success'}
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
{t('management.ipAddress') || 'IP Address'}
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{auditLogs.map((log) => (
<tr key={log.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{formatTimestamp(log.timestamp)}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getLevelBadgeClass(log.level)}`}>
{log.level}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{log.action}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{log.username || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{log.tenant_slug || '-'}
</td>
<td className="px-6 py-4 text-sm text-gray-900 max-w-xs truncate">
<span title={log.message}>{log.message}</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-center">
{getSuccessIndicator(log.success)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{log.ip_address || '-'}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Pagination */}
{pagination.totalPages > 1 && (
<div className="bg-white px-4 py-3 flex items-center justify-between border-t border-gray-200 sm:px-6">
<div className="flex-1 flex justify-between sm:hidden">
<button
onClick={() => handlePageChange(pagination.currentPage - 1)}
disabled={!pagination.hasPrevPage}
className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
>
{t('common.previous') || 'Previous'}
</button>
<button
onClick={() => handlePageChange(pagination.currentPage + 1)}
disabled={!pagination.hasNextPage}
className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
>
{t('common.next') || 'Next'}
</button>
</div>
<div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
<div>
<p className="text-sm text-gray-700">
{t('common.showing') || 'Showing'}{' '}
<span className="font-medium">{((pagination.currentPage - 1) * pagination.limit) + 1}</span>
{' '}{t('common.to') || 'to'}{' '}
<span className="font-medium">
{Math.min(pagination.currentPage * pagination.limit, pagination.totalCount)}
</span>
{' '}{t('common.of') || 'of'}{' '}
<span className="font-medium">{pagination.totalCount}</span>
{' '}{t('common.results') || 'results'}
</p>
</div>
<div>
<nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
<button
onClick={() => handlePageChange(pagination.currentPage - 1)}
disabled={!pagination.hasPrevPage}
className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50"
>
<span className="sr-only">{t('common.previous') || 'Previous'}</span>
&#8249;
</button>
{/* Page numbers */}
{Array.from({ length: Math.min(5, pagination.totalPages) }, (_, i) => {
const page = i + Math.max(1, pagination.currentPage - 2);
if (page > pagination.totalPages) return null;
return (
<button
key={page}
onClick={() => handlePageChange(page)}
className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium ${
page === pagination.currentPage
? 'z-10 bg-blue-50 border-blue-500 text-blue-600'
: 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'
}`}
>
{page}
</button>
);
})}
<button
onClick={() => handlePageChange(pagination.currentPage + 1)}
disabled={!pagination.hasNextPage}
className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50"
>
<span className="sr-only">{t('common.next') || 'Next'}</span>
&#8250;
</button>
</nav>
</div>
</div>
</div>
)}
</div>
);
};
export default AuditLogs;

View File

@@ -448,6 +448,38 @@ const translations = {
type: 'Type',
name: 'Name',
description: 'Description',
filters: 'Filters',
clearFilters: 'Clear Filters',
refresh: 'Refresh',
search: 'Search',
loading: 'Loading...',
error: 'Error',
showing: 'Showing',
to: 'to',
results: 'results'
},
management: {
auditLogs: 'Security Audit Logs',
totalLogs: 'Total Logs',
successfulActions: 'Successful Actions',
failedActions: 'Failed Actions',
warnings: 'Warnings',
critical: 'Critical Events',
level: 'Level',
action: 'Action',
user: 'User',
tenant: 'Tenant',
message: 'Message',
success: 'Success',
ipAddress: 'IP Address',
timestamp: 'Timestamp',
dateRange: 'Date Range',
searchPlaceholder: 'Search logs, users, or tenants...',
noAuditLogs: 'No audit logs found',
totalEntries: 'total entries',
logoManagement: 'Logo Management Events',
securityEvents: 'Security Events',
auditTrail: 'Audit Trail',
actions: 'Actions'
}
},
@@ -867,6 +899,69 @@ const translations = {
delete: 'Ta bort',
edit: 'Redigera',
view: 'Visa',
add: 'Lägg till',
update: 'Uppdatera',
create: 'Skapa',
remove: 'Ta bort',
close: 'Stäng',
open: 'Öppna',
back: 'Tillbaka',
continue: 'Fortsätt',
submit: 'Skicka',
confirm: 'Bekräfta',
yes: 'Ja',
no: 'Nej',
ok: 'OK',
apply: 'Tillämpa',
reset: 'Återställ',
clear: 'Rensa',
all: 'Alla',
none: 'Ingen',
selected: 'Vald',
total: 'Totalt',
page: 'Sida',
of: 'av',
previous: 'Föregående',
next: 'Nästa',
first: 'Första',
last: 'Sista',
date: 'Datum',
time: 'Tid',
status: 'Status',
type: 'Typ',
name: 'Namn',
description: 'Beskrivning',
filters: 'Filter',
clearFilters: 'Rensa filter',
refresh: 'Uppdatera',
search: 'Sök',
showing: 'Visar',
to: 'till',
results: 'resultat'
},
management: {
auditLogs: 'Säkerhetsgranskningsloggar',
totalLogs: 'Totala loggar',
successfulActions: 'Lyckade åtgärder',
failedActions: 'Misslyckade åtgärder',
warnings: 'Varningar',
critical: 'Kritiska händelser',
level: 'Nivå',
action: 'Åtgärd',
user: 'Användare',
tenant: 'Klient',
message: 'Meddelande',
success: 'Framgång',
ipAddress: 'IP-adress',
timestamp: 'Tidsstämpel',
dateRange: 'Datumintervall',
searchPlaceholder: 'Sök loggar, användare eller klienter...',
noAuditLogs: 'Inga granskningsloggar hittades',
totalEntries: 'totala poster',
logoManagement: 'Logotyphanteringshändelser',
securityEvents: 'Säkerhetshändelser',
auditTrail: 'Granskningsspår',
view: 'Visa',
close: 'Stäng',
refresh: 'Uppdatera',
search: 'Sök',

View File

@@ -9,6 +9,14 @@ class SecurityLogger {
// Ensure log directory exists
this.ensureLogDirectory();
// Initialize models reference (will be set when needed)
this.models = null;
}
// Set models reference for database logging
setModels(models) {
this.models = models;
}
ensureLogDirectory() {
@@ -23,7 +31,7 @@ class SecurityLogger {
}
}
logSecurityEvent(level, message, metadata = {}) {
async logSecurityEvent(level, message, metadata = {}) {
const timestamp = new Date().toISOString();
const logEntry = {
timestamp,
@@ -44,6 +52,49 @@ class SecurityLogger {
console.error('Failed to write to security log file:', error.message);
}
}
// Store in database if models are available
if (this.models && this.models.AuditLog) {
try {
await this.models.AuditLog.create({
timestamp: new Date(),
level: level.toUpperCase(),
action: metadata.action || 'unknown',
message,
user_id: metadata.userId || null,
username: metadata.username || null,
tenant_id: metadata.tenantId || null,
tenant_slug: metadata.tenantSlug || null,
ip_address: metadata.ip || null,
user_agent: metadata.userAgent || null,
path: metadata.path || null,
metadata: metadata,
success: this.determineSuccess(level, metadata)
});
} catch (error) {
console.error('Failed to store audit log in database:', error.message);
}
}
}
determineSuccess(level, metadata) {
// Determine if the action was successful based on level and metadata
if (metadata.hasOwnProperty('success')) {
return metadata.success;
}
// Assume success for info level, failure for error/critical
switch (level.toUpperCase()) {
case 'INFO':
return true;
case 'WARNING':
return null; // Neutral
case 'ERROR':
case 'CRITICAL':
return false;
default:
return null;
}
}
logIPRestriction(ip, tenant, userAgent, denied = true) {

View File

@@ -0,0 +1,103 @@
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('audit_logs', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
timestamp: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.NOW
},
level: {
type: Sequelize.ENUM('INFO', 'WARNING', 'ERROR', 'CRITICAL'),
allowNull: false
},
action: {
type: Sequelize.STRING(100),
allowNull: false,
comment: 'The action performed (e.g., logo_upload, logo_removal)'
},
message: {
type: Sequelize.TEXT,
allowNull: false,
comment: 'Human-readable description of the event'
},
user_id: {
type: Sequelize.INTEGER,
allowNull: true,
comment: 'ID of the user who performed the action',
references: {
model: 'users',
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL'
},
username: {
type: Sequelize.STRING(255),
allowNull: true,
comment: 'Username of the user who performed the action'
},
tenant_id: {
type: Sequelize.INTEGER,
allowNull: true,
comment: 'ID of the tenant affected by the action',
references: {
model: 'tenants',
key: 'id'
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL'
},
tenant_slug: {
type: Sequelize.STRING(255),
allowNull: true,
comment: 'Slug of the tenant affected by the action'
},
ip_address: {
type: Sequelize.STRING(45),
allowNull: true,
comment: 'IP address of the user (supports IPv6)'
},
user_agent: {
type: Sequelize.TEXT,
allowNull: true,
comment: 'User agent string from the request'
},
path: {
type: Sequelize.STRING(500),
allowNull: true,
comment: 'Request path that triggered the action'
},
metadata: {
type: Sequelize.JSON,
allowNull: true,
comment: 'Additional metadata about the event'
},
success: {
type: Sequelize.BOOLEAN,
allowNull: true,
comment: 'Whether the action was successful'
}
});
// Add indexes for performance
await queryInterface.addIndex('audit_logs', ['timestamp']);
await queryInterface.addIndex('audit_logs', ['action']);
await queryInterface.addIndex('audit_logs', ['user_id']);
await queryInterface.addIndex('audit_logs', ['tenant_id']);
await queryInterface.addIndex('audit_logs', ['level']);
await queryInterface.addIndex('audit_logs', ['timestamp', 'action']);
await queryInterface.addIndex('audit_logs', ['tenant_id', 'timestamp']);
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('audit_logs');
}
};

118
server/models/AuditLog.js Normal file
View File

@@ -0,0 +1,118 @@
const { DataTypes } = require('sequelize');
module.exports = (sequelize) => {
const AuditLog = sequelize.define('AuditLog', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
timestamp: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
level: {
type: DataTypes.ENUM('INFO', 'WARNING', 'ERROR', 'CRITICAL'),
allowNull: false
},
action: {
type: DataTypes.STRING(100),
allowNull: false,
comment: 'The action performed (e.g., logo_upload, logo_removal)'
},
message: {
type: DataTypes.TEXT,
allowNull: false,
comment: 'Human-readable description of the event'
},
user_id: {
type: DataTypes.INTEGER,
allowNull: true,
comment: 'ID of the user who performed the action'
},
username: {
type: DataTypes.STRING(255),
allowNull: true,
comment: 'Username of the user who performed the action'
},
tenant_id: {
type: DataTypes.INTEGER,
allowNull: true,
comment: 'ID of the tenant affected by the action'
},
tenant_slug: {
type: DataTypes.STRING(255),
allowNull: true,
comment: 'Slug of the tenant affected by the action'
},
ip_address: {
type: DataTypes.STRING(45),
allowNull: true,
comment: 'IP address of the user (supports IPv6)'
},
user_agent: {
type: DataTypes.TEXT,
allowNull: true,
comment: 'User agent string from the request'
},
path: {
type: DataTypes.STRING(500),
allowNull: true,
comment: 'Request path that triggered the action'
},
metadata: {
type: DataTypes.JSON,
allowNull: true,
comment: 'Additional metadata about the event'
},
success: {
type: DataTypes.BOOLEAN,
allowNull: true,
comment: 'Whether the action was successful'
}
}, {
tableName: 'audit_logs',
timestamps: false, // We use our own timestamp field
indexes: [
{
fields: ['timestamp']
},
{
fields: ['action']
},
{
fields: ['user_id']
},
{
fields: ['tenant_id']
},
{
fields: ['level']
},
{
fields: ['timestamp', 'action']
},
{
fields: ['tenant_id', 'timestamp']
}
]
});
// Define associations
AuditLog.associate = function(models) {
// Association with User
AuditLog.belongsTo(models.User, {
foreignKey: 'user_id',
as: 'user'
});
// Association with Tenant
AuditLog.belongsTo(models.Tenant, {
foreignKey: 'tenant_id',
as: 'tenant'
});
};
return AuditLog;
};

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) {