fartstack/backend/lib/utils/environment.dart

62 lines
1.9 KiB
Dart

// load any env vars inside root of project's .env file, then looks for JWT_TOKEN_SECRET
import 'dart:io';
import 'dart:math';
import 'package:logging/logging.dart';
final log = Logger('Environment');
bool _isDevEnv = false;
void checkEnvironment({required bool isDevEnv}) {
_isDevEnv = isDevEnv;
getJWTSecret();
}
String? getJWTSecret() {
final envs = {...Platform.environment};
if (_isDevEnv) {
log.fine('Trying to load .env file...');
try {
final result = Process.runSync('git', ['rev-parse', '--show-toplevel']);
if (result.exitCode != 0) {
log.warning('Failed to get git root directory: ${result.stderr}');
throw Exception('Failed to get git root directory');
}
final rootDir = (result.stdout as String).trim();
final envFile = File('$rootDir/.env');
if (envFile.existsSync()) {
for (final line in envFile.readAsLinesSync()) {
if (line.trim().isEmpty || line.startsWith('#')) continue;
final parts = line.split('=');
if (parts.length != 2) continue;
final key = parts[0].trim();
final value = parts[1].trim();
envs[key] = value;
}
}
} catch (e) {
log.warning('Failed to load .env file: $e');
}
}
// check for secret
final secret = envs['JWT_TOKEN_SECRET'];
if (secret == null || secret.isEmpty) {
if (_isDevEnv) {
log.warning('JWT secret not configured. Define JWT_TOKEN_SECRET in environment.');
final secret = List.generate(
24,
(_) => String.fromCharCode((65 + Random().nextInt(26)) + (Random().nextInt(2) == 0 ? 0 : 32)),
).join();
log.warning('Generated random JWT secret for development: $secret');
return secret;
} else {
log.severe('Stopping prod server because JWT secret is not defined.');
throw Exception('JWT secret not configured. Define JWT_TOKEN_SECRET in environment.');
}
} else {
return secret;
}
}