Fix jwt-token

This commit is contained in:
2025-09-10 06:13:47 +02:00
parent b0a700a6cf
commit 7877902698
6 changed files with 165 additions and 5 deletions

1
.env
View File

@@ -34,6 +34,7 @@ STORE_HEARTBEATS=true
STORE_DRONE_TYPE0=true STORE_DRONE_TYPE0=true
LOG_ALL_DETECTIONS=true LOG_ALL_DETECTIONS=true
API_DEBUG=true API_DEBUG=true
STORE_RAW_PAYLOAD=true
# Health Probe Simulator Configuration # Health Probe Simulator Configuration
PROBE_FAILRATE=30 PROBE_FAILRATE=30

View File

@@ -230,6 +230,13 @@ TWILIO_PHONE_NUMBER=your_twilio_phone
PORT=3001 PORT=3001
NODE_ENV=development NODE_ENV=development
CORS_ORIGIN=http://localhost:3000 CORS_ORIGIN=http://localhost:3000
# Debug Configuration
STORE_HEARTBEATS=true # Store heartbeat data for debugging
STORE_DRONE_TYPE0=true # Store drone_type 0 detections for debugging
LOG_ALL_DETECTIONS=true # Log all detection data to console
API_DEBUG=true # Enable API debug logging
STORE_RAW_PAYLOAD=true # Store complete raw payload from detectors
``` ```
## API Documentation ## API Documentation
@@ -281,6 +288,20 @@ Content-Type: application/json
- `POST /api/alerts/rules` - Create new alert rule - `POST /api/alerts/rules` - Create new alert rule
- `GET /api/alerts/logs` - Get alert history - `GET /api/alerts/logs` - Get alert history
### Debug Endpoints (Authentication Required)
- `GET /api/debug/config` - Get debug configuration status
- `GET /api/debug/detection-payloads` - Get recent detection payloads with raw data
- `GET /api/debug/heartbeat-payloads` - Get recent heartbeat payloads with raw data
- `GET /api/debug/debug-test` - Test debug endpoint
#### Debug Query Parameters
```http
GET /api/debug/detection-payloads?limit=50&offset=0&device_id=1941875381
GET /api/debug/heartbeat-payloads?limit=50&offset=0&device_id=1941875381
```
The debug endpoints return the complete raw payload received from detectors when `STORE_RAW_PAYLOAD=true` is enabled. This is useful for troubleshooting detector communication issues and understanding the exact data format being sent.
## Hardware Integration ## Hardware Integration
### Expected Data Format ### Expected Data Format

View File

@@ -91,6 +91,11 @@ module.exports = (sequelize) => {
defaultValue: false, defaultValue: false,
comment: 'Whether this detection requires immediate security action' comment: 'Whether this detection requires immediate security action'
}, },
raw_payload: {
type: DataTypes.JSON,
allowNull: true,
comment: 'Complete raw payload received from detector (for debugging)'
},
created_at: { created_at: {
type: DataTypes.DATE, type: DataTypes.DATE,
defaultValue: DataTypes.NOW defaultValue: DataTypes.NOW

View File

@@ -56,6 +56,11 @@ module.exports = (sequelize) => {
defaultValue: DataTypes.NOW, defaultValue: DataTypes.NOW,
comment: 'When heartbeat was received by server' comment: 'When heartbeat was received by server'
}, },
raw_payload: {
type: DataTypes.JSON,
allowNull: true,
comment: 'Complete raw payload received from detector (for debugging)'
},
created_at: { created_at: {
type: DataTypes.DATE, type: DataTypes.DATE,
defaultValue: DataTypes.NOW defaultValue: DataTypes.NOW

View File

@@ -1,5 +1,8 @@
const express = require('express'); const express = require('express');
const { ApiDebugLogger } = require('../utils/apiDebugLogger'); const { ApiDebugLogger } = require('../utils/apiDebugLogger');
const { DroneDetection, Heartbeat } = require('../models');
const { Op } = require('sequelize');
const { authenticateToken } = require('../middleware/auth');
const router = express.Router(); const router = express.Router();
const logger = new ApiDebugLogger(); const logger = new ApiDebugLogger();
@@ -21,4 +24,108 @@ router.get('/debug-test', (req, res) => {
res.json(response); res.json(response);
}); });
// Get recent detection payloads with raw data
router.get('/detection-payloads', authenticateToken, async (req, res) => {
try {
const { limit = 50, offset = 0, device_id } = req.query;
const whereClause = {
raw_payload: { [Op.ne]: null }
};
if (device_id) {
whereClause.device_id = device_id;
}
const detections = await DroneDetection.findAll({
where: whereClause,
order: [['server_timestamp', 'DESC']],
limit: parseInt(limit),
offset: parseInt(offset),
attributes: [
'id', 'device_id', 'drone_id', 'drone_type', 'rssi', 'freq',
'server_timestamp', 'device_timestamp', 'raw_payload'
]
});
console.log(`🔍 Retrieved ${detections.length} detection payloads for debugging`);
res.json({
success: true,
data: detections,
total: detections.length,
filters: { device_id, limit, offset }
});
} catch (error) {
console.error('Error fetching detection payloads:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch detection payloads'
});
}
});
// Get recent heartbeat payloads with raw data
router.get('/heartbeat-payloads', authenticateToken, async (req, res) => {
try {
const { limit = 50, offset = 0, device_id } = req.query;
const whereClause = {
raw_payload: { [Op.ne]: null }
};
if (device_id) {
whereClause.device_id = device_id;
}
const heartbeats = await Heartbeat.findAll({
where: whereClause,
order: [['received_at', 'DESC']],
limit: parseInt(limit),
offset: parseInt(offset),
attributes: [
'id', 'device_id', 'device_key', 'signal_strength', 'battery_level',
'temperature', 'received_at', 'raw_payload'
]
});
console.log(`🔍 Retrieved ${heartbeats.length} heartbeat payloads for debugging`);
res.json({
success: true,
data: heartbeats,
total: heartbeats.length,
filters: { device_id, limit, offset }
});
} catch (error) {
console.error('Error fetching heartbeat payloads:', error);
res.status(500).json({
success: false,
error: 'Failed to fetch heartbeat payloads'
});
}
});
// Get debug configuration status
router.get('/config', authenticateToken, (req, res) => {
const config = {
STORE_HEARTBEATS: process.env.STORE_HEARTBEATS === 'true',
STORE_DRONE_TYPE0: process.env.STORE_DRONE_TYPE0 === 'true',
LOG_ALL_DETECTIONS: process.env.LOG_ALL_DETECTIONS === 'true',
API_DEBUG: process.env.API_DEBUG === 'true',
STORE_RAW_PAYLOAD: process.env.STORE_RAW_PAYLOAD === 'true',
NODE_ENV: process.env.NODE_ENV
};
console.log('🔍 Debug configuration requested');
res.json({
success: true,
config,
timestamp: new Date().toISOString()
});
});
module.exports = router; module.exports = router;

View File

@@ -11,7 +11,8 @@ const { getDroneTypeInfo, getDroneTypeName } = require('../utils/droneTypes');
const DEBUG_CONFIG = { const DEBUG_CONFIG = {
storeHeartbeats: process.env.STORE_HEARTBEATS === 'true', // Store heartbeat data for debugging storeHeartbeats: process.env.STORE_HEARTBEATS === 'true', // Store heartbeat data for debugging
storeNoneDetections: process.env.STORE_DRONE_TYPE0 === 'true', // Store drone_type 0 for debugging storeNoneDetections: process.env.STORE_DRONE_TYPE0 === 'true', // Store drone_type 0 for debugging
logAllDetections: process.env.LOG_ALL_DETECTIONS === 'true' // Log all detection data logAllDetections: process.env.LOG_ALL_DETECTIONS === 'true', // Log all detection data
storeRawPayload: process.env.STORE_RAW_PAYLOAD === 'true' // Store complete raw payload for debugging
}; };
// Initialize services // Initialize services
@@ -192,12 +193,22 @@ async function handleHeartbeat(req, res) {
await device.update({ last_heartbeat: new Date() }); await device.update({ last_heartbeat: new Date() });
// Create heartbeat record with all optional fields // Create heartbeat record with all optional fields
const heartbeat = await Heartbeat.create({ const heartbeatRecord = {
device_id: deviceId, device_id: deviceId,
device_key: key, device_key: key,
...heartbeatData, ...heartbeatData,
received_at: new Date() received_at: new Date()
}); };
// Add raw payload if debugging is enabled
if (DEBUG_CONFIG.storeRawPayload) {
heartbeatRecord.raw_payload = req.body;
if (DEBUG_CONFIG.logAllDetections) {
console.log(`🔍 Storing heartbeat raw payload for debugging: ${JSON.stringify(req.body)}`);
}
}
const heartbeat = await Heartbeat.create(heartbeatRecord);
// Emit real-time update via Socket.IO (from original heartbeat route) // Emit real-time update via Socket.IO (from original heartbeat route)
req.io.emit('device_heartbeat', { req.io.emit('device_heartbeat', {
@@ -290,10 +301,20 @@ async function handleDetection(req, res) {
} }
// Create detection record // Create detection record
const detection = await DroneDetection.create({ const detectionRecord = {
...detectionData, ...detectionData,
server_timestamp: new Date() server_timestamp: new Date()
}); };
// Add raw payload if debugging is enabled
if (DEBUG_CONFIG.storeRawPayload) {
detectionRecord.raw_payload = req.body;
if (DEBUG_CONFIG.logAllDetections) {
console.log(`🔍 Storing raw payload for debugging: ${JSON.stringify(req.body)}`);
}
}
const detection = await DroneDetection.create(detectionRecord);
// Process detection through tracking service for movement analysis (from original) // Process detection through tracking service for movement analysis (from original)
const movementAnalysis = droneTracker.processDetection({ const movementAnalysis = droneTracker.processDetection({