diff --git a/server/routes/alert.js b/server/routes/alert.js index be5395a..d259dee 100644 --- a/server/routes/alert.js +++ b/server/routes/alert.js @@ -1,9 +1,10 @@ const express = require('express'); const router = express.Router(); const Joi = require('joi'); -const { AlertRule, AlertLog, User, sequelize } = require('../models'); +const { AlertRule, AlertLog, User, Device, Tenant, sequelize } = require('../models'); const { validateRequest } = require('../middleware/validation'); const { authenticateToken, requireRole } = require('../middleware/auth'); +const { MultiTenantAuth } = require('../middleware/multiTenantAuth'); const { Op } = require('sequelize'); // Validation schemas @@ -32,11 +33,29 @@ router.get('/rules', authenticateToken, async (req, res) => { try { const { limit = 50, offset = 0, is_active } = req.query; - const whereClause = { user_id: req.user.id }; + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + + // Filter alert rules by users in the same tenant + const whereClause = {}; if (is_active !== undefined) whereClause.is_active = is_active === 'true'; const alertRules = await AlertRule.findAndCountAll({ where: whereClause, + include: [{ + model: User, + as: 'user', + where: { tenant_id: tenantId }, + attributes: ['id', 'username', 'email'] + }], limit: Math.min(parseInt(limit), 100), offset: parseInt(offset), order: [['created_at', 'DESC']] @@ -105,11 +124,27 @@ router.post('/rules', authenticateToken, validateRequest(alertRuleSchema), async // PUT /api/alerts/rules/:id - Update alert rule router.put('/rules/:id', authenticateToken, validateRequest(alertRuleSchema), async (req, res) => { try { + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + const alertRule = await AlertRule.findOne({ where: { - id: req.params.id, - user_id: req.user.id - } + id: req.params.id + }, + include: [{ + model: User, + as: 'user', + where: { tenant_id: tenantId }, + attributes: ['id'] + }] }); if (!alertRule) { @@ -140,11 +175,27 @@ router.put('/rules/:id', authenticateToken, validateRequest(alertRuleSchema), as // DELETE /api/alerts/rules/:id - Delete alert rule router.delete('/rules/:id', authenticateToken, async (req, res) => { try { + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + const alertRule = await AlertRule.findOne({ where: { - id: req.params.id, - user_id: req.user.id - } + id: req.params.id + }, + include: [{ + model: User, + as: 'user', + where: { tenant_id: tenantId }, + attributes: ['id'] + }] }); if (!alertRule) { @@ -183,6 +234,17 @@ router.get('/logs', authenticateToken, async (req, res) => { end_date } = req.query; + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + const whereClause = {}; if (status) whereClause.status = status; if (alert_type) whereClause.alert_type = alert_type; @@ -198,7 +260,12 @@ router.get('/logs', authenticateToken, async (req, res) => { include: [{ model: AlertRule, as: 'rule', - where: { user_id: req.user.id }, + include: [{ + model: User, + as: 'user', + where: { tenant_id: tenantId }, + attributes: ['id', 'username'] + }], attributes: ['id', 'name', 'priority'] }], limit: Math.min(parseInt(limit), 200), @@ -233,9 +300,25 @@ router.get('/stats', authenticateToken, async (req, res) => { const { hours = 24 } = req.query; const timeWindow = new Date(Date.now() - hours * 60 * 60 * 1000); - // Get user's alert rules + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + + // Get tenant's alert rules through user relationships const userRuleIds = await AlertRule.findAll({ - where: { user_id: req.user.id }, + include: [{ + model: User, + as: 'user', + where: { tenant_id: tenantId }, + attributes: [] + }], attributes: ['id'] }).then(rules => rules.map(rule => rule.id)); diff --git a/server/routes/dashboard.js b/server/routes/dashboard.js index 9a9e715..d3c5f04 100644 --- a/server/routes/dashboard.js +++ b/server/routes/dashboard.js @@ -1,9 +1,10 @@ const express = require('express'); const router = express.Router(); -const { DroneDetection, Device, Heartbeat } = require('../models'); +const { DroneDetection, Device, Heartbeat, Tenant } = require('../models'); const { Op } = require('sequelize'); const { sequelize } = require('../models'); const { authenticateToken } = require('../middleware/auth'); +const { MultiTenantAuth } = require('../middleware/multiTenantAuth'); // GET /api/dashboard/overview - Get dashboard overview statistics router.get('/overview', authenticateToken, async (req, res) => { @@ -11,7 +12,21 @@ router.get('/overview', authenticateToken, async (req, res) => { const { hours = 24 } = req.query; const timeWindow = new Date(Date.now() - hours * 60 * 60 * 1000); - // Get basic statistics + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + + // Create base filter for tenant devices + const tenantDeviceFilter = { tenant_id: tenantId }; + + // Get basic statistics - filtered by tenant const [ totalDevices, activeDevices, @@ -19,16 +34,33 @@ router.get('/overview', authenticateToken, async (req, res) => { recentDetections, uniqueDronesDetected ] = await Promise.all([ - Device.count(), - Device.count({ where: { is_active: true } }), - DroneDetection.count({ where: { drone_type: { [Op.ne]: 0 } } }), + Device.count({ where: tenantDeviceFilter }), + Device.count({ where: { ...tenantDeviceFilter, is_active: true } }), + DroneDetection.count({ + include: [{ + model: Device, + where: tenantDeviceFilter, + attributes: [] + }], + where: { drone_type: { [Op.ne]: 0 } } + }), DroneDetection.count({ + include: [{ + model: Device, + where: tenantDeviceFilter, + attributes: [] + }], where: { server_timestamp: { [Op.gte]: timeWindow }, drone_type: { [Op.ne]: 0 } } }), DroneDetection.count({ + include: [{ + model: Device, + where: tenantDeviceFilter, + attributes: [] + }], where: { server_timestamp: { [Op.gte]: timeWindow }, drone_type: { [Op.ne]: 0 } @@ -38,8 +70,9 @@ router.get('/overview', authenticateToken, async (req, res) => { }) ]); - // Get device status breakdown + // Get device status breakdown - filtered by tenant const devices = await Device.findAll({ + where: tenantDeviceFilter, attributes: ['id', 'last_heartbeat', 'heartbeat_interval', 'is_active'] }); @@ -110,7 +143,18 @@ router.get('/activity', authenticateToken, async (req, res) => { const { limit = 50, hours = 24 } = req.query; const timeWindow = new Date(Date.now() - hours * 60 * 60 * 1000); - // Get recent detections with device info + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + + // Get recent detections with device info - filtered by tenant const recentDetections = await DroneDetection.findAll({ where: { server_timestamp: { [Op.gte]: timeWindow }, @@ -119,18 +163,20 @@ router.get('/activity', authenticateToken, async (req, res) => { include: [{ model: Device, as: 'device', + where: { tenant_id: tenantId }, attributes: ['id', 'name', 'geo_lat', 'geo_lon', 'location_description'] }], limit: Math.min(parseInt(limit), 200), order: [['server_timestamp', 'DESC']] }); - // Get recent heartbeats + // Get recent heartbeats - filtered by tenant const recentHeartbeats = await Heartbeat.findAll({ where: { received_at: { [Op.gte]: timeWindow } }, include: [{ model: Device, as: 'device', + where: { tenant_id: tenantId }, attributes: ['id', 'name', 'geo_lat', 'geo_lon'] }], limit: Math.min(parseInt(limit), 50), @@ -191,6 +237,17 @@ router.get('/charts/detections', authenticateToken, async (req, res) => { const { hours = 24, interval = 'hour' } = req.query; const timeWindow = new Date(Date.now() - hours * 60 * 60 * 1000); + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + let groupBy; switch (interval) { case 'minute': @@ -207,6 +264,11 @@ router.get('/charts/detections', authenticateToken, async (req, res) => { } const detectionCounts = await DroneDetection.findAll({ + include: [{ + model: Device, + where: { tenant_id: tenantId }, + attributes: [] + }], where: { server_timestamp: { [Op.gte]: timeWindow }, drone_type: { [Op.ne]: 0 } @@ -244,6 +306,17 @@ router.get('/charts/devices', authenticateToken, async (req, res) => { const { hours = 24 } = req.query; const timeWindow = new Date(Date.now() - hours * 60 * 60 * 1000); + // Initialize multi-tenant auth to determine tenant + const multiTenantAuth = new MultiTenantAuth(); + const tenantId = await multiTenantAuth.determineTenant(req); + + if (!tenantId) { + return res.status(403).json({ + success: false, + message: 'Access denied: No tenant context' + }); + } + const deviceActivity = await DroneDetection.findAll({ where: { server_timestamp: { [Op.gte]: timeWindow }, @@ -256,6 +329,7 @@ router.get('/charts/devices', authenticateToken, async (req, res) => { include: [{ model: Device, as: 'device', + where: { tenant_id: tenantId }, attributes: ['name', 'location_description'] }], group: ['device_id', 'device.id', 'device.name', 'device.location_description'], diff --git a/server/routes/detections.js b/server/routes/detections.js index 0d535b3..38459fb 100644 --- a/server/routes/detections.js +++ b/server/routes/detections.js @@ -1,16 +1,37 @@ const express = require('express'); const { Op } = require('sequelize'); -const { DroneDetection, Device } = require('../models'); +const { DroneDetection, Device, Tenant } = require('../models'); const { authenticateToken } = require('../middleware/auth'); const { getDroneTypeInfo } = require('../utils/droneTypes'); +const MultiTenantAuth = require('../middleware/multi-tenant-auth'); const router = express.Router(); +// Initialize multi-tenant auth +const multiAuth = new MultiTenantAuth(); + /** * GET /api/detections - * Get all drone detections with filtering and pagination + * Get all drone detections with filtering and pagination (tenant-filtered) */ router.get('/', authenticateToken, async (req, res) => { try { + // Determine tenant from request + const tenantId = await multiAuth.determineTenant(req); + if (!tenantId) { + return res.status(400).json({ + success: false, + message: 'Unable to determine tenant' + }); + } + + const tenant = await Tenant.findOne({ where: { slug: tenantId } }); + if (!tenant) { + return res.status(404).json({ + success: false, + message: 'Tenant not found' + }); + } + const { device_id, drone_id, @@ -47,12 +68,13 @@ router.get('/', authenticateToken, async (req, res) => { // Calculate offset for pagination const offset = (parseInt(page) - 1) * parseInt(limit); - // Query detections with device information + // Query detections with device information (filtered by tenant) const detections = await DroneDetection.findAll({ where: whereClause, include: [{ model: Device, as: 'device', + where: { tenant_id: tenant.id }, // Filter by tenant attributes: ['id', 'name', 'geo_lat', 'geo_lon', 'location_description', 'is_approved'] }], order: [[sort, order.toUpperCase()]], @@ -60,9 +82,14 @@ router.get('/', authenticateToken, async (req, res) => { offset: offset }); - // Get total count for pagination + // Get total count for pagination (also filtered by tenant) const totalCount = await DroneDetection.count({ - where: whereClause + where: whereClause, + include: [{ + model: Device, + as: 'device', + where: { tenant_id: tenant.id } + }] }); // Calculate pagination info @@ -154,13 +181,13 @@ router.get('/debug', authenticateToken, async (req, res) => { // Calculate offset for pagination const offset = (parseInt(page) - 1) * parseInt(limit); - // Query ALL detections including type 0 for debugging + // Query ALL detections including type 0 for debugging (with tenant filtering) const detections = await DroneDetection.findAndCountAll({ where: whereClause, include: [{ model: Device, as: 'device', - attributes: ['id', 'name', 'location_description', 'geo_lat', 'geo_lon'] + attributes: ['id', 'name', 'location_description', 'geo_lat', 'geo_lon', 'tenant_id'] }], limit: parseInt(limit), offset: offset, @@ -205,22 +232,40 @@ router.get('/debug', authenticateToken, async (req, res) => { /** * GET /api/detections/:id - * Get a specific detection by ID + * Get a specific detection by ID (tenant-filtered) */ router.get('/:id', authenticateToken, async (req, res) => { try { + // Determine tenant from request + const tenantId = await multiAuth.determineTenant(req); + if (!tenantId) { + return res.status(400).json({ + success: false, + message: 'Unable to determine tenant' + }); + } + + const tenant = await Tenant.findOne({ where: { slug: tenantId } }); + if (!tenant) { + return res.status(404).json({ + success: false, + message: 'Tenant not found' + }); + } + const { id } = req.params; const detection = await DroneDetection.findByPk(id, { include: [{ model: Device, as: 'device', + where: { tenant_id: tenant.id }, // Filter by tenant attributes: ['id', 'name', 'geo_lat', 'geo_lon', 'location_description', 'is_approved'] }] }); if (!detection) { - return res.status(404).json({ error: 'Detection not found' }); + return res.status(404).json({ error: 'Detection not found in your tenant' }); } // Enhance detection with drone type information @@ -271,93 +316,4 @@ router.delete('/:id', authenticateToken, async (req, res) => { } }); -/** - * GET /api/detections/debug - * Get all drone detections including drone_type 0 for debugging - */ -router.get('/debug', authenticateToken, async (req, res) => { - try { - const { - device_id, - start_date, - end_date, - page = 1, - limit = 100, - sort = 'server_timestamp', - order = 'desc' - } = req.query; - - // Build where clause for filtering (includes drone_type 0) - const whereClause = {}; - - if (device_id) { - whereClause.device_id = device_id; - } - - 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 drone_type 0 - const { count, rows: detections } = await DroneDetection.findAndCountAll({ - where: whereClause, - include: [{ - model: Device, - attributes: ['id', 'name', 'geo_lat', 'geo_lon', 'location_description'] - }], - order: [[sort, order.toUpperCase()]], - limit: parseInt(limit), - offset: offset - }); - - const totalPages = Math.ceil(count / parseInt(limit)); - const hasNextPage = parseInt(page) < totalPages; - const hasPrevPage = parseInt(page) > 1; - - // Enhance detections with drone type information and debug flags - const enhancedDetections = detections.map(detection => { - const droneTypeInfo = getDroneTypeInfo(detection.drone_type); - const isDebugDetection = detection.drone_type === 0; - - return { - ...detection.toJSON(), - drone_type_info: droneTypeInfo, - is_debug_detection: isDebugDetection, - debug_note: isDebugDetection ? 'Debug detection (drone_type 0) - no alerts triggered' : null - }; - }); - - res.json({ - detections: enhancedDetections, - pagination: { - currentPage: parseInt(page), - totalPages, - totalCount: count, - limit: parseInt(limit), - hasNextPage, - hasPrevPage - }, - debug_info: { - includes_drone_type_0: true, - total_detections: count, - debug_detections: enhancedDetections.filter(d => d.is_debug_detection).length - } - }); - - } catch (error) { - console.error('Error fetching debug detections:', error); - res.status(500).json({ - error: 'Failed to fetch debug detections', - details: error.message - }); - } -}); - module.exports = router; diff --git a/server/routes/device.js b/server/routes/device.js index 4ab67d2..0685e97 100644 --- a/server/routes/device.js +++ b/server/routes/device.js @@ -159,10 +159,28 @@ router.get('/', authenticateToken, async (req, res) => { // GET /api/devices/map - Get devices with location data for map display router.get('/map', authenticateToken, async (req, res) => { try { - // Get all active devices, including those without coordinates + // Determine tenant from request + const tenantId = await multiAuth.determineTenant(req); + if (!tenantId) { + return res.status(400).json({ + success: false, + message: 'Unable to determine tenant' + }); + } + + const tenant = await Tenant.findOne({ where: { slug: tenantId } }); + if (!tenant) { + return res.status(404).json({ + success: false, + message: 'Tenant not found' + }); + } + + // Get active devices for this tenant only const devices = await Device.findAll({ where: { - is_active: true + is_active: true, + tenant_id: tenant.id }, attributes: [ 'id',