Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.7 KiB

import 'dart:convert';
import 'package:Envelope/utils/encryption/aes_helper.dart';
import 'package:Envelope/utils/encryption/crypto_utils.dart';
import 'package:pointycastle/impl.dart';
import 'package:shared_preferences/shared_preferences.dart';
class MyProfile {
String id;
String username;
RSAPrivateKey privateKey;
RSAPublicKey publicKey;
DateTime loggedInAt;
MyProfile({
required this.id,
required this.username,
required this.privateKey,
required this.publicKey,
required this.loggedInAt,
});
factory MyProfile._fromJson(Map<String, dynamic> json) {
DateTime loggedInAt = DateTime.now();
if (json.containsKey('logged_in_at')) {
loggedInAt = DateTime.parse(json['logged_in_at']);
}
return MyProfile(
id: json['user_id'],
username: json['username'],
privateKey: CryptoUtils.rsaPrivateKeyFromPem(json['asymmetric_private_key']),
publicKey: CryptoUtils.rsaPublicKeyFromPem(json['asymmetric_public_key']),
loggedInAt: loggedInAt,
);
}
@override
String toString() {
return '''
user_id: $id
username: $username
logged_in_at: $loggedInAt
public_key: $publicKey
private_key: $privateKey
''';
}
String toJson() {
return jsonEncode(<String, dynamic>{
'user_id': id,
'username': username,
'asymmetric_private_key': CryptoUtils.encodeRSAPrivateKeyToPem(privateKey),
'asymmetric_public_key': CryptoUtils.encodeRSAPublicKeyToPem(publicKey),
'logged_in_at': loggedInAt.toIso8601String(),
});
}
static Future<MyProfile> login(Map<String, dynamic> json, String password) async {
json['asymmetric_private_key'] = AesHelper.aesDecrypt(
password,
base64.decode(json['asymmetric_private_key'])
);
MyProfile profile = MyProfile._fromJson(json);
final preferences = await SharedPreferences.getInstance();
print(profile.toJson());
preferences.setString('profile', profile.toJson());
return profile;
}
static Future<void> logout() async {
final preferences = await SharedPreferences.getInstance();
preferences.remove('profile');
}
static Future<MyProfile> getProfile() async {
final preferences = await SharedPreferences.getInstance();
String? profileJson = preferences.getString('profile');
if (profileJson == null) {
throw Exception('No profile');
}
return MyProfile._fromJson(json.decode(profileJson));
}
static Future<bool> isLoggedIn() async {
MyProfile profile = await MyProfile.getProfile();
return profile.loggedInAt.isBefore((DateTime.now()).add(const Duration(hours: 12)));
}
Future<RSAPrivateKey> getPrivateKey() async {
MyProfile profile = await MyProfile.getProfile();
return profile.privateKey;
}
}