Fix jwt-token

This commit is contained in:
2025-09-07 09:17:28 +02:00
parent 8d9d147500
commit 16eb162cc5
3 changed files with 120 additions and 2 deletions

View File

@@ -10,6 +10,10 @@ API_BASE_URL=http://localhost:3002/api
# Base path (should match VITE_BASE_PATH) # Base path (should match VITE_BASE_PATH)
VITE_BASE_PATH=/uggla VITE_BASE_PATH=/uggla
# Test authentication credentials
TEST_USERNAME=admin
TEST_PASSWORD=admin123
# Alternative configurations: # Alternative configurations:
# For local development: # For local development:
# API_BASE_URL=http://localhost:3002/api # API_BASE_URL=http://localhost:3002/api

View File

@@ -2,7 +2,19 @@
""" """
Orlan Detection Test Script Orlan Detection Test Script
Tests the critical alert system for Orlan military drones by simulating Tests the critical alert system for Orlan military drones by simulating
a long-distance approach from undetectable range to directly overhead. a long-distan try:
response = requests.post(f"{API_BASE_URL}/detectors", json=detection_data, headers=get_auth_headers())
if response.status_code == 201:
status = "🚨 CRITICAL ALERT" if distance_km <= 5 else "⚠️ DETECTED" if is_detectable(distance_km) else "📡 MONITORING"
print(f"{status} - Step {step}/{total_steps}: Distance={distance_km:.1f}km, RSSI={rssi:.0f}dBm")
return True
else:
print(f"❌ Failed to send detection: {response.status_code}")
print(f"Response: {response.text}")
return False
except Exception as e:
print(f"❌ Error sending detection: {e}")
return Falserom undetectable range to directly overhead.
Test Scenario: Test Scenario:
- Starts 50km away (beyond detection range) - Starts 50km away (beyond detection range)
@@ -22,6 +34,10 @@ from datetime import datetime
API_BASE_URL = os.getenv('API_BASE_URL', 'http://localhost:3002/api') API_BASE_URL = os.getenv('API_BASE_URL', 'http://localhost:3002/api')
BASE_PATH = os.getenv('VITE_BASE_PATH', '').rstrip('/') BASE_PATH = os.getenv('VITE_BASE_PATH', '').rstrip('/')
# Authentication configuration
USERNAME = os.getenv('TEST_USERNAME', 'admin')
PASSWORD = os.getenv('TEST_PASSWORD', 'admin123')
# If BASE_PATH is set, construct the full URL # If BASE_PATH is set, construct the full URL
if BASE_PATH and not API_BASE_URL.endswith('/api'): if BASE_PATH and not API_BASE_URL.endswith('/api'):
# Extract domain from API_BASE_URL and add base path # Extract domain from API_BASE_URL and add base path
@@ -30,6 +46,48 @@ if BASE_PATH and not API_BASE_URL.endswith('/api'):
print(f"🔗 Using API Base URL: {API_BASE_URL}") print(f"🔗 Using API Base URL: {API_BASE_URL}")
# Global variable to store authentication token
AUTH_TOKEN = None
def authenticate():
"""Authenticate with the API and get access token"""
global AUTH_TOKEN
login_data = {
"username": USERNAME,
"password": PASSWORD
}
try:
print(f"🔐 Authenticating as user: {USERNAME}")
response = requests.post(f"{API_BASE_URL}/auth/login", json=login_data)
if response.status_code == 200:
data = response.json()
AUTH_TOKEN = data.get('token')
if AUTH_TOKEN:
print("✅ Authentication successful")
return True
else:
print("❌ No token received in response")
return False
else:
print(f"❌ Authentication failed: {response.status_code}")
print(f"Response: {response.text}")
return False
except Exception as e:
print(f"❌ Authentication error: {e}")
return False
def get_auth_headers():
"""Get headers with authentication token"""
if AUTH_TOKEN:
return {
"Authorization": f"Bearer {AUTH_TOKEN}",
"Content-Type": "application/json"
}
return {"Content-Type": "application/json"}
# Detection range parameters (approximate) # Detection range parameters (approximate)
MAX_DETECTION_RANGE_KM = 25.0 # Maximum range for drone detection MAX_DETECTION_RANGE_KM = 25.0 # Maximum range for drone detection
MIN_RSSI_THRESHOLD = -95 # Minimum RSSI for detection MIN_RSSI_THRESHOLD = -95 # Minimum RSSI for detection
@@ -69,7 +127,7 @@ def is_detectable(distance_km):
def fetch_devices(): def fetch_devices():
"""Fetch devices from API""" """Fetch devices from API"""
try: try:
response = requests.get(f"{API_BASE_URL}/devices") response = requests.get(f"{API_BASE_URL}/devices", headers=get_auth_headers())
if response.status_code == 200: if response.status_code == 200:
data = response.json() data = response.json()
return data.get('data', []) return data.get('data', [])
@@ -132,6 +190,16 @@ def run_orlan_detection_test():
print(f"🔗 API Endpoint: {API_BASE_URL}") print(f"🔗 API Endpoint: {API_BASE_URL}")
print() print()
# Authenticate first
if not authenticate():
print("❌ Authentication failed. Cannot proceed with test.")
print("Please check:")
print("1. Is the server running?")
print("2. Are the credentials correct?")
print(f" Username: {USERNAME}")
print("3. Set TEST_USERNAME and TEST_PASSWORD environment variables if needed")
return
# Test API connectivity first # Test API connectivity first
print("🔍 Testing API connectivity...") print("🔍 Testing API connectivity...")
try: try:

View File

@@ -16,6 +16,10 @@ from datetime import datetime
API_BASE_URL = os.getenv('API_BASE_URL', 'http://localhost:3002/api') API_BASE_URL = os.getenv('API_BASE_URL', 'http://localhost:3002/api')
BASE_PATH = os.getenv('VITE_BASE_PATH', '').rstrip('/') BASE_PATH = os.getenv('VITE_BASE_PATH', '').rstrip('/')
# Authentication configuration
USERNAME = os.getenv('TEST_USERNAME', 'admin')
PASSWORD = os.getenv('TEST_PASSWORD', 'admin123')
# If BASE_PATH is set, construct the full URL # If BASE_PATH is set, construct the full URL
if BASE_PATH and not API_BASE_URL.endswith('/api'): if BASE_PATH and not API_BASE_URL.endswith('/api'):
# Extract domain from API_BASE_URL and add base path # Extract domain from API_BASE_URL and add base path
@@ -24,6 +28,48 @@ if BASE_PATH and not API_BASE_URL.endswith('/api'):
print(f"🔗 Using API Base URL: {API_BASE_URL}") print(f"🔗 Using API Base URL: {API_BASE_URL}")
# Global variable to store authentication token
AUTH_TOKEN = None
def authenticate():
"""Authenticate with the API and get access token"""
global AUTH_TOKEN
login_data = {
"username": USERNAME,
"password": PASSWORD
}
try:
print(f"🔐 Authenticating as user: {USERNAME}")
response = requests.post(f"{API_BASE_URL}/auth/login", json=login_data)
if response.status_code == 200:
data = response.json()
AUTH_TOKEN = data.get('token')
if AUTH_TOKEN:
print("✅ Authentication successful")
return True
else:
print("❌ No token received in response")
return False
else:
print(f"❌ Authentication failed: {response.status_code}")
print(f"Response: {response.text}")
return False
except Exception as e:
print(f"❌ Authentication error: {e}")
return False
def get_auth_headers():
"""Get headers with authentication token"""
if AUTH_TOKEN:
return {
"Authorization": f"Bearer {AUTH_TOKEN}",
"Content-Type": "application/json"
}
return {"Content-Type": "application/json"}
def haversine_distance(lat1, lon1, lat2, lon2): def haversine_distance(lat1, lon1, lat2, lon2):
"""Calculate distance between two points in kilometers""" """Calculate distance between two points in kilometers"""
R = 6371 # Earth's radius in kilometers R = 6371 # Earth's radius in kilometers