Implement authentication middleware and rolling codes service for secure API access

This commit is contained in:
ImBenji
2025-08-19 20:30:43 +01:00
parent f829bd5fe1
commit 17091bcc95
4 changed files with 380 additions and 44 deletions

View File

@@ -1,37 +1,67 @@
import 'dart:io';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:waylume_server/config/supabase_config.dart';
import 'package:waylume_server/core/utils.dart';
import 'package:waylume_server/services/rolling_codes_service.dart';
class ServerService {
static Future<void> registerServer() async {
await RollingCodesService.initialize();
// If already registered and has operational seed, skip registration
if (RollingCodesService.isRegistered) {
print('Server already registered with operational seed');
return;
}
GeolocationData geolocationData = await getGeolocationData();
String ip = "${geolocationData.ip}:${fromEnivronment("EXTERNAL_PORT") ?? "3000"}";
var existsCheck = await SUPABASE_CLIENT
.from("waylume_servers")
.select()
.eq("id", fromEnivronment('SERVER_ID'))
.eq("host_ip", ip);
if (existsCheck.isEmpty) {
await SUPABASE_CLIENT
.from("waylume_servers")
.insert({
"id": fromEnivronment('SERVER_ID')!,
"last_heartbeat": DateTime.now().toUtc().toIso8601String(),
"host_ip": ip,
"geolocation": {
"country": geolocationData.countryName,
"country_code": geolocationData.countryCode,
"city": geolocationData.city,
"coords": [
geolocationData.latitude,
geolocationData.longitude
],
// Generate registration rolling code
String registrationAuth = RollingCodesService.generateRegistrationCode();
// Call server-manager registration endpoint
String serverManagerUrl = '${fromEnivronment("SUPABASE_URL")}/functions/v1/server-manager/register';
Map<String, dynamic> requestBody = {
'server_id': fromEnivronment('SERVER_ID')!,
'registration_auth': registrationAuth,
'geolocation_data': {
"country": geolocationData.countryName,
"country_code": geolocationData.countryCode,
"city": geolocationData.city,
"coords": [
geolocationData.latitude,
geolocationData.longitude
],
}
};
try {
final response = await http.post(
Uri.parse(serverManagerUrl),
headers: {
'Content-Type': 'application/json',
'apikey': fromEnivronment('SUPABASE_ANON_KEY')!,
},
body: jsonEncode(requestBody),
);
if (response.statusCode == 200) {
final responseData = jsonDecode(response.body);
if (responseData['success']) {
// Store operational seed
await RollingCodesService.setOperationalSeed(responseData['operational_seed']);
print('Server registered successfully with server-manager');
} else {
throw Exception('Registration failed: ${responseData['error']}');
}
});
} else {
throw Exception('Registration request failed: ${response.statusCode}');
}
} catch (e) {
print('Error registering server: $e');
throw Exception('Failed to register server: $e');
}
}