Fix jwt-token

This commit is contained in:
2025-09-01 07:24:36 +02:00
parent 8c4fc4f62b
commit e312c61b56
6 changed files with 507 additions and 3 deletions

View File

@@ -9,6 +9,7 @@ import MapView from './pages/MapView';
import Devices from './pages/Devices'; import Devices from './pages/Devices';
import Detections from './pages/Detections'; import Detections from './pages/Detections';
import Alerts from './pages/Alerts'; import Alerts from './pages/Alerts';
import Debug from './pages/Debug';
import Login from './pages/Login'; import Login from './pages/Login';
import ProtectedRoute from './components/ProtectedRoute'; import ProtectedRoute from './components/ProtectedRoute';
@@ -68,6 +69,7 @@ function App() {
<Route path="devices" element={<Devices />} /> <Route path="devices" element={<Devices />} />
<Route path="detections" element={<Detections />} /> <Route path="detections" element={<Detections />} />
<Route path="alerts" element={<Alerts />} /> <Route path="alerts" element={<Alerts />} />
<Route path="debug" element={<Debug />} />
</Route> </Route>
</Routes> </Routes>
</div> </div>

View File

@@ -12,11 +12,12 @@ import {
Bars3Icon, Bars3Icon,
XMarkIcon, XMarkIcon,
SignalIcon, SignalIcon,
WifiIcon WifiIcon,
BugAntIcon
} from '@heroicons/react/24/outline'; } from '@heroicons/react/24/outline';
import classNames from 'classnames'; import classNames from 'classnames';
const navigation = [ const baseNavigation = [
{ name: 'Dashboard', href: '/', icon: HomeIcon }, { name: 'Dashboard', href: '/', icon: HomeIcon },
{ name: 'Map View', href: '/map', icon: MapIcon }, { name: 'Map View', href: '/map', icon: MapIcon },
{ name: 'Devices', href: '/devices', icon: ServerIcon }, { name: 'Devices', href: '/devices', icon: ServerIcon },
@@ -24,12 +25,21 @@ const navigation = [
{ name: 'Alerts', href: '/alerts', icon: BellIcon }, { name: 'Alerts', href: '/alerts', icon: BellIcon },
]; ];
const adminNavigation = [
{ name: 'Debug', href: '/debug', icon: BugAntIcon },
];
const Layout = () => { const Layout = () => {
const [sidebarOpen, setSidebarOpen] = useState(false); const [sidebarOpen, setSidebarOpen] = useState(false);
const { user, logout } = useAuth(); const { user, logout } = useAuth();
const { connected, recentDetections } = useSocket(); const { connected, recentDetections } = useSocket();
const location = useLocation(); const location = useLocation();
// Build navigation based on user role
const navigation = user?.role === 'admin'
? [...baseNavigation, ...adminNavigation]
: baseNavigation;
return ( return (
<div className="min-h-screen flex bg-gray-100"> <div className="min-h-screen flex bg-gray-100">
{/* Mobile sidebar */} {/* Mobile sidebar */}

354
client/src/pages/Debug.jsx Normal file
View File

@@ -0,0 +1,354 @@
import React, { useState, useEffect } from 'react';
import api from '../services/api';
import { format } from 'date-fns';
import {
BugAntIcon,
ExclamationTriangleIcon,
InformationCircleIcon,
EyeIcon,
TrashIcon
} from '@heroicons/react/24/outline';
const Debug = () => {
const [debugData, setDebugData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [pagination, setPagination] = useState({});
const [debugInfo, setDebugInfo] = useState({});
const [filters, setFilters] = useState({
drone_type: '',
device_id: '',
page: 1,
limit: 50
});
useEffect(() => {
fetchDebugData();
}, [filters]);
const fetchDebugData = async () => {
try {
setLoading(true);
const params = new URLSearchParams();
Object.entries(filters).forEach(([key, value]) => {
if (value) params.append(key, value);
});
const response = await api.get(`/detections/debug?${params}`);
if (response.data.success) {
setDebugData(response.data.data);
setPagination(response.data.pagination);
setDebugInfo(response.data.debug_info);
} else {
setError(response.data.message || 'Failed to fetch debug data');
}
} catch (err) {
console.error('Error fetching debug data:', err);
setError(err.response?.data?.message || 'Failed to fetch debug data');
} finally {
setLoading(false);
}
};
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 getDroneTypeColor = (droneType) => {
if (droneType === 0) return 'bg-gray-100 text-gray-800';
return 'bg-blue-100 text-blue-800';
};
const getThreatLevelColor = (threatLevel) => {
switch (threatLevel?.toLowerCase()) {
case 'critical':
return 'bg-red-100 text-red-800';
case 'high':
return 'bg-orange-100 text-orange-800';
case 'medium':
return 'bg-yellow-100 text-yellow-800';
case 'low':
return 'bg-green-100 text-green-800';
default:
return 'bg-gray-100 text-gray-800';
}
};
if (loading) {
return (
<div className="flex items-center justify-center min-h-96">
<div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary-500"></div>
</div>
);
}
if (error) {
return (
<div className="bg-red-50 border border-red-200 rounded-md p-4">
<div className="flex">
<ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
<div className="ml-3">
<h3 className="text-sm font-medium text-red-800">Error</h3>
<div className="mt-2 text-sm text-red-700">{error}</div>
</div>
</div>
</div>
);
}
return (
<div className="space-y-6">
{/* Header */}
<div className="bg-white shadow rounded-lg p-6">
<div className="flex items-center">
<BugAntIcon className="h-8 w-8 text-orange-500 mr-3" />
<div>
<h1 className="text-2xl font-bold text-gray-900">Debug Console</h1>
<p className="text-sm text-gray-500">
Admin-only access to all detection data including drone type 0 (None)
</p>
</div>
</div>
</div>
{/* Debug Info */}
{debugInfo && (
<div className="bg-yellow-50 border border-yellow-200 rounded-md p-4">
<div className="flex">
<InformationCircleIcon className="h-5 w-5 text-yellow-400" />
<div className="ml-3">
<h3 className="text-sm font-medium text-yellow-800">Debug Information</h3>
<div className="mt-2 text-sm text-yellow-700">
<p>{debugInfo.message}</p>
<p className="mt-1">Total None detections: <strong>{debugInfo.total_none_detections}</strong></p>
</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">Filters</h3>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Drone Type
</label>
<select
value={filters.drone_type}
onChange={(e) => handleFilterChange('drone_type', e.target.value)}
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
>
<option value="">All Types</option>
<option value="0">0 - None (Debug)</option>
<option value="1">1 - Unknown</option>
<option value="2">2 - Orlan</option>
<option value="3">3 - Zala</option>
<option value="4">4 - Eleron</option>
<option value="5">5 - Zala Lancet</option>
<option value="6">6 - Lancet</option>
<option value="7">7 - FPV CrossFire</option>
<option value="8">8 - FPV ELRS</option>
<option value="9">9 - Maybe Orlan</option>
<option value="10">10 - Maybe Zala</option>
<option value="11">11 - Maybe Lancet</option>
<option value="12">12 - Maybe Eleron</option>
<option value="13">13 - DJI</option>
<option value="14">14 - Supercam</option>
<option value="15">15 - Maybe Supercam</option>
<option value="16">16 - REB</option>
<option value="17">17 - Crypto Orlan</option>
<option value="18">18 - DJI Enterprise</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Device ID
</label>
<input
type="number"
value={filters.device_id}
onChange={(e) => handleFilterChange('device_id', e.target.value)}
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
placeholder="Filter by device ID"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Results per page
</label>
<select
value={filters.limit}
onChange={(e) => handleFilterChange('limit', e.target.value)}
className="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-primary-500 focus:border-primary-500"
>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
</div>
</div>
{/* Debug Data Table */}
<div className="bg-white shadow rounded-lg overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200">
<h3 className="text-lg font-medium text-gray-900">
Debug Detections ({pagination.total || 0})
</h3>
</div>
{debugData.length === 0 ? (
<div className="text-center py-12">
<BugAntIcon className="mx-auto h-12 w-12 text-gray-400" />
<h3 className="mt-2 text-sm font-medium text-gray-900">No debug data</h3>
<p className="mt-1 text-sm text-gray-500">
No detections found matching the current filters.
</p>
</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">
ID / Time
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Device
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Drone Type
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
RSSI / Freq
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Threat Level
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Debug
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{debugData.map((detection) => (
<tr key={detection.id} className={detection.is_debug_data ? 'bg-gray-50' : ''}>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900">#{detection.id}</div>
<div className="text-sm text-gray-500">
{format(new Date(detection.server_timestamp), 'MMM dd, HH:mm:ss')}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900">
{detection.device?.name || `Device ${detection.device_id}`}
</div>
<div className="text-sm text-gray-500">ID: {detection.device_id}</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getDroneTypeColor(detection.drone_type)}`}>
{detection.drone_type_info?.name || `Type ${detection.drone_type}`}
</span>
<div className="text-xs text-gray-500 mt-1">
ID: {detection.drone_type}
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<div className="text-sm text-gray-900">{detection.rssi} dBm</div>
<div className="text-sm text-gray-500">{detection.freq} MHz</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
{detection.threat_level ? (
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getThreatLevelColor(detection.threat_level)}`}>
{detection.threat_level}
</span>
) : (
<span className="text-gray-400 text-sm">N/A</span>
)}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{detection.is_debug_data && (
<span className="px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
Debug Data
</span>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Pagination */}
{pagination.pages > 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(Math.max(1, pagination.page - 1))}
disabled={pagination.page === 1}
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"
>
Previous
</button>
<button
onClick={() => handlePageChange(Math.min(pagination.pages, pagination.page + 1))}
disabled={pagination.page === pagination.pages}
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"
>
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">
Showing <span className="font-medium">{((pagination.page - 1) * pagination.limit) + 1}</span> to{' '}
<span className="font-medium">
{Math.min(pagination.page * pagination.limit, pagination.total)}
</span>{' '}
of <span className="font-medium">{pagination.total}</span> results
</p>
</div>
<div>
<nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
<button
onClick={() => handlePageChange(Math.max(1, pagination.page - 1))}
disabled={pagination.page === 1}
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"
>
Previous
</button>
<button
onClick={() => handlePageChange(Math.min(pagination.pages, pagination.page + 1))}
disabled={pagination.page === pagination.pages}
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"
>
Next
</button>
</nav>
</div>
</div>
</div>
)}
</>
)}
</div>
</div>
);
};
export default Debug;

View File

@@ -23,7 +23,10 @@ router.get('/', authenticateToken, async (req, res) => {
} = req.query; } = req.query;
// Build where clause for filtering // Build where clause for filtering
const whereClause = {}; const whereClause = {
// Exclude drone type 0 (None) from normal detection queries
drone_type: { [Op.ne]: 0 }
};
if (device_id) { if (device_id) {
whereClause.device_id = device_id; whereClause.device_id = device_id;
@@ -165,4 +168,107 @@ router.delete('/:id', authenticateToken, async (req, res) => {
} }
}); });
/**
* GET /api/detections/debug
* Get all detections including drone type 0 (None) for debugging purposes
* Admin access only
*/
router.get('/debug', authenticateToken, async (req, res) => {
try {
// Check if user is admin
if (req.user.role !== 'admin') {
return res.status(403).json({
success: false,
error: 'Access denied',
message: 'Admin access required for debug data'
});
}
const {
device_id,
drone_id,
drone_type,
start_date,
end_date,
page = 1,
limit = 100,
sort = 'server_timestamp',
order = 'desc'
} = req.query;
// Build where clause for debugging (includes all drone types)
const whereClause = {};
if (device_id) {
whereClause.device_id = device_id;
}
if (drone_id) {
whereClause.drone_id = drone_id;
}
if (drone_type !== undefined) {
whereClause.drone_type = parseInt(drone_type);
}
if (start_date) {
whereClause.server_timestamp = { ...whereClause.server_timestamp, [Op.gte]: new Date(start_date) };
}
if (end_date) {
whereClause.server_timestamp = { ...whereClause.server_timestamp, [Op.lte]: new Date(end_date) };
}
// Calculate offset for pagination
const offset = (parseInt(page) - 1) * parseInt(limit);
// Query ALL detections including type 0 for debugging
const detections = await DroneDetection.findAndCountAll({
where: whereClause,
include: [{
model: Device,
as: 'device',
attributes: ['id', 'name', 'location', 'geo_lat', 'geo_lon']
}],
limit: parseInt(limit),
offset: offset,
order: [[sort, order.toUpperCase()]]
});
// Add drone type information to each detection
const enhancedDetections = detections.rows.map(detection => {
const droneTypeInfo = getDroneTypeInfo(detection.drone_type);
return {
...detection.toJSON(),
drone_type_info: droneTypeInfo,
is_debug_data: detection.drone_type === 0
};
});
res.json({
success: true,
data: enhancedDetections,
pagination: {
total: detections.count,
page: parseInt(page),
limit: parseInt(limit),
pages: Math.ceil(detections.count / parseInt(limit))
},
debug_info: {
includes_none_detections: true,
total_none_detections: await DroneDetection.count({ where: { drone_type: 0 } }),
message: "Debug data includes drone type 0 (None) detections"
}
});
} catch (error) {
console.error('Error fetching debug detections:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch debug detections',
details: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
});
}
});
module.exports = router; module.exports = router;

View File

@@ -7,6 +7,12 @@ const AlertService = require('../services/alertService');
const DroneTrackingService = require('../services/droneTrackingService'); const DroneTrackingService = require('../services/droneTrackingService');
const { getDroneTypeInfo, getDroneTypeName } = require('../utils/droneTypes'); const { getDroneTypeInfo, getDroneTypeName } = require('../utils/droneTypes');
// Configuration for debugging and data storage
const DEBUG_CONFIG = {
storeNoneDetections: process.env.STORE_NONE_DETECTIONS === 'true', // Store drone_type 0 for debugging
logAllDetections: process.env.LOG_ALL_DETECTIONS === 'true' // Log all detections including type 0
};
// Initialize services // Initialize services
const alertService = new AlertService(); const alertService = new AlertService();
const droneTracker = new DroneTrackingService(); const droneTracker = new DroneTrackingService();
@@ -250,6 +256,26 @@ async function handleDetection(req, res) {
}); });
} }
// Handle drone type 0 (None) - should not trigger alarms or be stored as detection
if (detectionData.drone_type === 0) {
if (DEBUG_CONFIG.logAllDetections) {
console.log(`🔍 Debug: Drone type 0 (None) received from device ${detectionData.device_id}`);
}
if (!DEBUG_CONFIG.storeNoneDetections) {
// Don't store in database, just acknowledge receipt
return res.status(200).json({
success: true,
message: 'Heartbeat received (no detection)',
stored: false,
debug: DEBUG_CONFIG.logAllDetections
});
}
// If debugging enabled, store but mark as debug data
console.log(`🐛 Debug mode: Storing drone type 0 detection for debugging`);
}
// Create detection record // Create detection record
const detection = await DroneDetection.create({ const detection = await DroneDetection.create({
...detectionData, ...detectionData,

View File

@@ -136,6 +136,12 @@ class AlertService {
async processAlert(detection) { async processAlert(detection) {
try { try {
// Skip alert processing for drone type 0 (None) - no actual detection
if (detection.drone_type === 0) {
console.log(`🔍 Skipping alert processing for drone type 0 (None) - detection ${detection.id}`);
return;
}
console.log(`🔍 Processing alert for detection ${detection.id}`); console.log(`🔍 Processing alert for detection ${detection.id}`);
// Assess threat level based on RSSI and drone type // Assess threat level based on RSSI and drone type