63 lines
1.7 KiB
Dart
63 lines
1.7 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:encrypt/encrypt.dart';
|
|
import 'package:manager_app/Models/session.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
|
|
class SessionHelper {
|
|
final key = Key.fromUtf8('aVs:ZMe3EK-yS<y:;k>vCGrj3T8]yG6E');
|
|
final iv = IV.fromLength(16);
|
|
|
|
|
|
Future<String> get _localPath async {
|
|
final directory = await getApplicationDocumentsDirectory();
|
|
|
|
return directory.path;
|
|
}
|
|
|
|
Future<File> get _localFile async {
|
|
final path = await _localPath;
|
|
return File('$path/session.json');
|
|
}
|
|
|
|
Future<File> writeSession(Session session) async {
|
|
final file = await _localFile;
|
|
|
|
if (session.password != null) {
|
|
var encrypter = Encrypter(AES(key));
|
|
var encrypted = encrypter.encrypt(session.password, iv: iv);
|
|
|
|
session.password = encrypted.base64;
|
|
}
|
|
// Write the file
|
|
return file.writeAsString(jsonEncode(session.toMap()));
|
|
}
|
|
|
|
Future<Session> readSession() async {
|
|
try {
|
|
final file = await _localFile;
|
|
// Read the file
|
|
final contents = await file.readAsString();
|
|
|
|
Session session = Session.fromJson(jsonDecode(contents));
|
|
|
|
var encrypter = Encrypter(AES(key));
|
|
|
|
if (session.password != null) {
|
|
session.password = encrypter.decrypt64(session.password, iv: iv);
|
|
}
|
|
|
|
return session;
|
|
} catch (e) {
|
|
if (e.toString().contains("cannot find the file")) {
|
|
final path = await _localPath;
|
|
new File('$path/session.json').createSync(recursive: true);
|
|
print("file created");
|
|
await writeSession(new Session(rememberMe: false));
|
|
}
|
|
// If encountering an error, return 0
|
|
return Session(rememberMe: false);
|
|
}
|
|
}
|
|
} |