Skip to content

Commit

Permalink
Merge pull request #51 from enrique-lozano/fix/backup-secure
Browse files Browse the repository at this point in the history
Catch errors when reseting a database
  • Loading branch information
enrique-lozano authored Oct 10, 2023
2 parents e58758b + 7cda6d8 commit d0592cb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
3 changes: 3 additions & 0 deletions lib/app/settings/backup_settings_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class BackupSettings extends StatelessWidget {
SnackBar(
content: Text(t.backup.import.cancelled)),
);

return;
}

Expand All @@ -59,6 +60,8 @@ class BackupSettings extends StatelessWidget {
content: Text(t.backup.import.success)),
);
}).catchError((err) {
Navigator.pop(context);

ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(err.toString())));
});
Expand Down
29 changes: 24 additions & 5 deletions lib/core/database/backup/backup_database_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:monekin/core/database/app_db.dart';
import 'package:monekin/core/database/services/app-data/app_data_service.dart';
import 'package:monekin/core/models/transaction/transaction.dart';
import 'package:monekin/core/utils/get_download_path.dart';
import 'package:path/path.dart' as path;
Expand Down Expand Up @@ -129,16 +130,34 @@ class BackupDatabaseService {
}

if (result != null) {
File file = File(result.files.single.path!);
File selectedFile = File(result.files.single.path!);

// Delete the previous database
String path = await db.databasePath;
String dbPath = await db.databasePath;

final currentDBContent = await File(dbPath).readAsBytes();

// Load the new database
await File(path)
.writeAsBytes(await file.readAsBytes(), mode: FileMode.write);
await File(dbPath)
.writeAsBytes(await selectedFile.readAsBytes(), mode: FileMode.write);

try {
final dbVersion = int.parse((await AppDataService.instance
.getAppDataItem(AppDataKey.dbVersion)
.first)!);

if (dbVersion < db.schemaVersion) {
// TODO: Migrate
}

db.markTablesUpdated(db.allTables);
db.markTablesUpdated(db.allTables);
} catch (e) {
// Reset the DB as it was
await File(dbPath).writeAsBytes(currentDBContent, mode: FileMode.write);
db.markTablesUpdated(db.allTables);

throw Exception('The database is invalid or could not be readed');
}

return true;
}
Expand Down

0 comments on commit d0592cb

Please sign in to comment.