Fix jwt-token

This commit is contained in:
2025-08-17 05:25:15 +02:00
parent 22d52b84b5
commit ce87df0eb5
4 changed files with 172 additions and 31 deletions

37
.env.development Normal file
View File

@@ -0,0 +1,37 @@
# Development Environment Configuration
# SMS alerts are disabled by default in development
# Database Configuration
DB_HOST=localhost
DB_PORT=5433
DB_NAME=drone_detection
DB_USER=postgres
DB_PASSWORD=your_secure_password_here
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6380
# JWT Configuration
JWT_SECRET=dev_jwt_secret_change_in_production
# Server Configuration
PORT=3002
NODE_ENV=development
# CORS Configuration
CORS_ORIGIN=http://localhost:3001
# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
# Twilio SMS Configuration (Disabled for development)
# Uncomment and fill these to enable SMS alerts:
# TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# TWILIO_AUTH_TOKEN=your_auth_token
# TWILIO_PHONE_NUMBER=+1234567890
# Frontend Configuration
VITE_API_URL=http://localhost:3002/api
VITE_WS_URL=ws://localhost:3002

View File

@@ -1,22 +1,44 @@
# Docker Environment Configuration # Docker Environment Configuration
# Copy this file to .env and update with your actual values # Copy this file to .env and update with your actual values
# Database Configuration (automatically set by docker-compose)
DB_HOST=drone-detection-db
DB_PORT=5432
DB_NAME=drone_detection
DB_USER=postgres
DB_PASSWORD=your_secure_password_here
# Redis Configuration (automatically set by docker-compose)
REDIS_HOST=drone-detection-redis
REDIS_PORT=6379
# JWT Configuration # JWT Configuration
JWT_SECRET=your-super-secret-jwt-key-change-in-production-make-it-long-and-random JWT_SECRET=your-super-secret-jwt-key-change-in-production-make-it-long-and-random
# Server Configuration
PORT=3002
NODE_ENV=development NODE_ENV=development
# Twilio Configuration (for SMS alerts) # CORS Configuration
CORS_ORIGIN=http://localhost:3001
# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100
# Twilio SMS Configuration (Optional - leave empty to disable SMS)
# Get these from https://console.twilio.com/
TWILIO_ACCOUNT_SID= TWILIO_ACCOUNT_SID=
TWILIO_AUTH_TOKEN= TWILIO_AUTH_TOKEN=
TWILIO_PHONE_NUMBER= TWILIO_PHONE_NUMBER=
# Email Configuration (Optional - for future implementation)
SMTP_HOST= SMTP_HOST=
SMTP_PORT=587 SMTP_PORT=587
SMTP_USER= SMTP_USER=
SMTP_PASSWORD= SMTP_PASSWORD=
SMTP_FROM= SMTP_FROM=
# Optional: Override default settings # Frontend Configuration
# NODE_ENV=production VITE_API_URL=http://localhost:3002/api
# CORS_ORIGIN=http://localhost:3000 VITE_WS_URL=ws://localhost:3002

View File

@@ -11,6 +11,7 @@ require('dotenv').config();
const { sequelize } = require('./models'); const { sequelize } = require('./models');
const routes = require('./routes'); const routes = require('./routes');
const { initializeSocketHandlers } = require('./services/socketService'); const { initializeSocketHandlers } = require('./services/socketService');
const AlertService = require('./services/alertService');
const errorHandler = require('./middleware/errorHandler'); const errorHandler = require('./middleware/errorHandler');
const app = express(); const app = express();
@@ -81,8 +82,24 @@ async function startServer() {
} }
server.listen(PORT, () => { server.listen(PORT, () => {
console.log(`Server running on port ${PORT}`); console.log('\n🚀 Drone Detection System Started Successfully!');
console.log(`Environment: ${process.env.NODE_ENV}`); console.log('================================================');
console.log(`📊 Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`🌐 Server Port: ${PORT}`);
console.log(`💾 Database: ${process.env.DB_HOST}:${process.env.DB_PORT}`);
console.log(`🔴 Redis: ${process.env.REDIS_HOST || 'localhost'}:${process.env.REDIS_PORT || 6379}`);
// Initialize AlertService to check SMS status
const alertService = new AlertService();
if (alertService.twilioEnabled) {
console.log('📱 SMS Alerts: ✅ Enabled');
} else {
console.log('📱 SMS Alerts: ⚠️ Disabled (no Twilio credentials)');
}
console.log(`📊 Health check: http://localhost:${PORT}/health`);
console.log(`🌐 API endpoint: http://localhost:${PORT}/api`);
console.log('================================================\n');
}); });
} catch (error) { } catch (error) {
console.error('Unable to start server:', error); console.error('Unable to start server:', error);

View File

@@ -5,6 +5,8 @@ const { Op } = require('sequelize');
class AlertService { class AlertService {
constructor() { constructor() {
this.twilioClient = null; this.twilioClient = null;
this.twilioPhone = null;
this.twilioEnabled = false;
this.initializeTwilio(); this.initializeTwilio();
} }
@@ -89,13 +91,40 @@ class AlertService {
} }
initializeTwilio() { initializeTwilio() {
if (process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN) { // Check if Twilio credentials are provided
this.twilioClient = twilio( const accountSid = process.env.TWILIO_ACCOUNT_SID;
process.env.TWILIO_ACCOUNT_SID, const authToken = process.env.TWILIO_AUTH_TOKEN;
process.env.TWILIO_AUTH_TOKEN const phoneNumber = process.env.TWILIO_PHONE_NUMBER;
);
} else { // If any Twilio credential is missing, disable SMS functionality
console.warn('Twilio credentials not configured. SMS alerts will be disabled.'); if (!accountSid || !authToken || !phoneNumber ||
accountSid.trim() === '' || authToken.trim() === '' || phoneNumber.trim() === '') {
console.log('📱 Twilio credentials not configured - SMS alerts disabled');
console.log(' To enable SMS alerts, set TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_PHONE_NUMBER');
this.twilioEnabled = false;
this.twilioClient = null;
return;
}
// Validate Twilio Account SID format
if (!accountSid.startsWith('AC')) {
console.log('⚠️ Invalid Twilio Account SID format - SMS alerts disabled');
console.log(' Account SID must start with "AC"');
this.twilioEnabled = false;
this.twilioClient = null;
return;
}
try {
this.twilioClient = twilio(accountSid, authToken);
this.twilioPhone = phoneNumber;
this.twilioEnabled = true;
console.log('📱 Twilio SMS service initialized successfully');
} catch (error) {
console.error('❌ Failed to initialize Twilio:', error.message);
console.log('📱 SMS alerts disabled due to Twilio initialization error');
this.twilioEnabled = false;
this.twilioClient = null;
} }
} }
@@ -343,27 +372,63 @@ class AlertService {
} }
async sendSMSAlert(phoneNumber, message, rule, detection) { async sendSMSAlert(phoneNumber, message, rule, detection) {
if (!this.twilioClient) { // Check if Twilio is enabled
throw new Error('Twilio not configured'); if (!this.twilioEnabled || !this.twilioClient) {
console.log('📱 SMS alert skipped - Twilio not configured');
console.log(`📱 Would have sent to ${phoneNumber}: ${message}`);
return await AlertLog.create({
alert_rule_id: rule.id,
detection_id: detection.id,
alert_type: 'sms',
recipient: phoneNumber,
message: message,
status: 'failed',
sent_at: new Date(),
external_id: null,
priority: rule.priority,
error_message: 'SMS service not configured'
});
} }
const twilioMessage = await this.twilioClient.messages.create({ try {
body: message, console.log(`📱 Sending SMS alert to ${phoneNumber}`);
from: process.env.TWILIO_PHONE_NUMBER,
to: phoneNumber const twilioMessage = await this.twilioClient.messages.create({
}); body: message,
from: this.twilioPhone,
to: phoneNumber
});
return await AlertLog.create({ console.log(`✅ SMS sent successfully: ${twilioMessage.sid}`);
alert_rule_id: rule.id,
detection_id: detection.id, return await AlertLog.create({
alert_type: 'sms', alert_rule_id: rule.id,
recipient: phoneNumber, detection_id: detection.id,
message: message, alert_type: 'sms',
status: 'sent', recipient: phoneNumber,
sent_at: new Date(), message: message,
external_id: twilioMessage.sid, status: 'sent',
priority: rule.priority sent_at: new Date(),
}); external_id: twilioMessage.sid,
priority: rule.priority
});
} catch (error) {
console.error('❌ Failed to send SMS:', error.message);
return await AlertLog.create({
alert_rule_id: rule.id,
detection_id: detection.id,
alert_type: 'sms',
recipient: phoneNumber,
message: message,
status: 'failed',
sent_at: new Date(),
external_id: null,
priority: rule.priority,
error_message: error.message
});
}
} }
async sendEmailAlert(email, message, rule, detection) { async sendEmailAlert(email, message, rule, detection) {