ente/lib/services/user_service.dart

1190 lines
36 KiB
Dart
Raw Normal View History

2022-11-06 10:36:33 +00:00
import 'dart:async';
2023-07-15 11:04:44 +00:00
import "dart:convert";
2023-07-17 08:04:52 +00:00
import "dart:math";
2021-06-29 15:03:54 +00:00
2023-03-14 01:40:54 +00:00
import 'package:bip39/bip39.dart' as bip39;
2020-04-30 15:09:41 +00:00
import 'package:dio/dio.dart';
2023-07-18 02:47:29 +00:00
import "package:flutter/foundation.dart";
2020-08-25 06:00:19 +00:00
import 'package:flutter/material.dart';
2020-05-02 16:28:54 +00:00
import 'package:logging/logging.dart';
import 'package:photos/core/configuration.dart';
2023-03-14 01:40:54 +00:00
import 'package:photos/core/constants.dart';
2023-07-18 02:47:29 +00:00
import "package:photos/core/errors.dart";
2021-06-29 09:48:01 +00:00
import 'package:photos/core/event_bus.dart';
2023-02-03 07:39:04 +00:00
import 'package:photos/core/network/network.dart';
2020-10-17 18:16:30 +00:00
import 'package:photos/db/public_keys_db.dart';
import "package:photos/events/account_configured_event.dart";
2021-06-29 09:48:01 +00:00
import 'package:photos/events/two_factor_status_change_event.dart';
import 'package:photos/events/user_details_changed_event.dart';
2023-04-07 06:33:40 +00:00
import "package:photos/generated/l10n.dart";
2023-07-15 11:04:44 +00:00
import "package:photos/models/api/user/srp.dart";
2022-07-08 08:50:19 +00:00
import 'package:photos/models/delete_account.dart';
import 'package:photos/models/key_attributes.dart';
2021-03-29 15:09:12 +00:00
import 'package:photos/models/key_gen_result.dart';
2023-07-17 08:04:52 +00:00
import 'package:photos/models/public_key.dart' as ePublicKey;
2021-11-23 19:40:33 +00:00
import 'package:photos/models/sessions.dart';
2021-03-28 12:43:44 +00:00
import 'package:photos/models/set_keys_request.dart';
import 'package:photos/models/set_recovery_key_request.dart';
2021-07-28 14:08:27 +00:00
import 'package:photos/models/user_details.dart';
import 'package:photos/ui/account/login_page.dart';
import 'package:photos/ui/account/ott_verification_page.dart';
import 'package:photos/ui/account/password_entry_page.dart';
import 'package:photos/ui/account/password_reentry_page.dart';
2023-07-18 12:28:45 +00:00
import "package:photos/ui/account/recovery_page.dart";
import 'package:photos/ui/account/two_factor_authentication_page.dart';
2023-03-14 01:40:54 +00:00
import 'package:photos/ui/account/two_factor_recovery_page.dart';
import 'package:photos/ui/account/two_factor_setup_page.dart';
import "package:photos/ui/components/buttons/button_widget.dart";
2023-08-14 08:28:42 +00:00
import "package:photos/ui/tabs/home_widget.dart";
2023-03-14 01:40:54 +00:00
import 'package:photos/utils/crypto_util.dart';
2020-08-25 06:00:19 +00:00
import 'package:photos/utils/dialog_util.dart';
import "package:photos/utils/email_util.dart";
2021-06-29 09:48:01 +00:00
import 'package:photos/utils/navigation_util.dart';
import 'package:photos/utils/toast_util.dart';
2023-07-18 05:26:57 +00:00
import "package:pointycastle/export.dart";
2023-07-17 08:04:52 +00:00
import "package:pointycastle/srp/srp6_client.dart";
import "package:pointycastle/srp/srp6_standard_groups.dart";
import "package:pointycastle/srp/srp6_util.dart";
import "package:pointycastle/srp/srp6_verifier_generator.dart";
import 'package:shared_preferences/shared_preferences.dart';
2023-07-15 11:04:44 +00:00
import "package:uuid/uuid.dart";
2020-10-03 17:56:18 +00:00
class UserService {
static const keyHasEnabledTwoFactor = "has_enabled_two_factor";
static const keyUserDetails = "user_details";
2023-11-06 12:03:33 +00:00
static const kReferralSource = "referral_source";
2023-08-04 04:24:54 +00:00
final SRP6GroupParameters kDefaultSrpGroup = SRP6StandardGroups.rfc5054_4096;
2023-02-03 07:39:04 +00:00
final _dio = NetworkClient.instance.getDio();
final _enteDio = NetworkClient.instance.enteDio;
2022-06-03 01:43:45 +00:00
final _logger = Logger((UserService).toString());
final _config = Configuration.instance;
2022-12-30 10:03:50 +00:00
late SharedPreferences _preferences;
2022-12-30 10:03:50 +00:00
late ValueNotifier<String?> emailValueNotifier;
2020-04-30 15:09:41 +00:00
2020-10-03 17:56:18 +00:00
UserService._privateConstructor();
2022-11-06 10:36:33 +00:00
2020-10-03 17:56:18 +00:00
static final UserService instance = UserService._privateConstructor();
2020-04-30 15:09:41 +00:00
Future<void> init() async {
emailValueNotifier =
2022-12-30 10:03:50 +00:00
ValueNotifier<String?>(Configuration.instance.getEmail());
_preferences = await SharedPreferences.getInstance();
if (Configuration.instance.isLoggedIn()) {
// add artificial delay in refreshing 2FA status
Future.delayed(
const Duration(seconds: 5),
() => {setTwoFactor(fetchTwoFactorStatus: true).ignore()},
);
}
Bus.instance.on<TwoFactorStatusChangeEvent>().listen((event) {
setTwoFactor(value: event.status);
});
}
Future<void> sendOtt(
2021-07-28 18:06:30 +00:00
BuildContext context,
String email, {
bool isChangeEmail = false,
2022-06-23 12:12:19 +00:00
bool isCreateAccountScreen = false,
2023-07-18 12:05:30 +00:00
bool isResetPasswordScreen = false,
2021-07-28 18:06:30 +00:00
}) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).pleaseWait);
2020-08-25 06:00:19 +00:00
await dialog.show();
2021-07-28 18:41:46 +00:00
try {
final response = await _dio.post(
2021-07-28 18:41:46 +00:00
_config.getHttpEndpoint() + "/users/ott",
data: {"email": email, "purpose": isChangeEmail ? "change" : ""},
2021-07-28 18:41:46 +00:00
);
2020-08-25 06:00:19 +00:00
await dialog.hide();
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
2022-11-06 10:36:33 +00:00
unawaited(
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) {
return OTTVerificationPage(
email,
isChangeEmail: isChangeEmail,
isCreateAccountScreen: isCreateAccountScreen,
2023-07-18 12:05:30 +00:00
isResetPasswordScreen: isResetPasswordScreen,
2022-11-06 10:36:33 +00:00
);
},
),
2021-07-28 18:06:30 +00:00
),
);
2021-07-28 18:41:46 +00:00
return;
}
unawaited(showGenericErrorDialog(context: context));
2021-07-28 18:41:46 +00:00
} on DioError catch (e) {
await dialog.hide();
_logger.info(e);
2022-12-30 10:03:50 +00:00
if (e.response != null && e.response!.statusCode == 403) {
2022-11-06 10:36:33 +00:00
unawaited(
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).oops,
S.of(context).thisEmailIsAlreadyInUse,
2022-11-06 10:36:33 +00:00
),
);
2020-08-25 06:00:19 +00:00
} else {
unawaited(showGenericErrorDialog(context: context));
2020-08-25 06:00:19 +00:00
}
2021-07-28 18:41:46 +00:00
} catch (e) {
await dialog.hide();
_logger.severe(e);
unawaited(showGenericErrorDialog(context: context));
2021-07-28 18:41:46 +00:00
}
2020-08-25 06:00:19 +00:00
}
Future<void> sendFeedback(
BuildContext context,
String feedback, {
String type = "SubCancellation",
}) async {
await _dio.post(
_config.getHttpEndpoint() + "/anonymous/feedback",
data: {"feedback": feedback, "type": "type"},
);
}
// getPublicKey returns null value if email id is not
// associated with another ente account
2022-12-30 10:03:50 +00:00
Future<String?> getPublicKey(String email) async {
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.get(
"/users/public-key",
queryParameters: {"email": email},
);
2020-10-18 21:39:55 +00:00
final publicKey = response.data["publicKey"];
2023-07-17 08:04:52 +00:00
await PublicKeysDB.instance.setKey(
ePublicKey.PublicKey(
email,
publicKey,
),
);
2020-10-17 18:16:30 +00:00
return publicKey;
} on DioError catch (e) {
if (e.response != null && e.response?.statusCode == 404) {
return null;
}
rethrow;
}
}
2022-12-30 10:03:50 +00:00
UserDetails? getCachedUserDetails() {
if (_preferences.containsKey(keyUserDetails)) {
2022-12-30 10:03:50 +00:00
return UserDetails.fromJson(_preferences.getString(keyUserDetails)!);
}
return null;
}
Future<UserDetails> getUserDetailsV2({
bool memoryCount = true,
bool shouldCache = false,
}) async {
2022-12-27 11:54:25 +00:00
_logger.info("Fetching user details");
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.get(
2022-12-13 12:29:55 +00:00
"/users/details/v2",
2022-05-30 09:23:55 +00:00
queryParameters: {
"memoryCount": memoryCount,
},
);
final userDetails = UserDetails.fromMap(response.data);
if (shouldCache) {
await _preferences.setString(keyUserDetails, userDetails.toJson());
// handle email change from different client
if (userDetails.email != _config.getEmail()) {
setEmail(userDetails.email);
}
}
return userDetails;
} on DioError catch (e) {
_logger.info(e);
rethrow;
}
}
2021-11-23 19:40:33 +00:00
Future<Sessions> getActiveSessions() async {
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.get("/users/sessions");
2021-11-23 19:40:33 +00:00
return Sessions.fromMap(response.data);
} on DioError catch (e) {
_logger.info(e);
rethrow;
}
}
2021-11-23 19:48:24 +00:00
Future<void> terminateSession(String token) async {
try {
2022-10-14 09:32:51 +00:00
await _enteDio.delete(
"/users/session",
2022-06-11 08:23:52 +00:00
queryParameters: {
"token": token,
},
);
2021-11-23 19:48:24 +00:00
} on DioError catch (e) {
_logger.info(e);
rethrow;
}
}
Future<void> leaveFamilyPlan() async {
try {
2022-10-14 09:32:51 +00:00
await _enteDio.delete("/family/leave");
} on DioError catch (e) {
_logger.warning('failed to leave family plan', e);
rethrow;
}
}
Future<void> logout(BuildContext context) async {
2021-07-05 09:31:03 +00:00
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.post("/users/logout");
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
await Configuration.instance.logout();
Navigator.of(context).popUntil((route) => route.isFirst);
} else {
2022-06-03 01:49:05 +00:00
throw Exception("Log out action failed");
}
} catch (e) {
// check if token is already invalid
if (e is DioError && e.response?.statusCode == 401) {
await Configuration.instance.logout();
Navigator.of(context).popUntil((route) => route.isFirst);
return;
}
_logger.severe("Failed to logout", e);
2023-01-27 13:00:32 +00:00
//This future is for waiting for the dialog from which logout() is called
//to close and only then to show the error dialog.
2023-01-27 10:23:31 +00:00
Future.delayed(
const Duration(milliseconds: 150),
() => showGenericErrorDialog(context: context),
);
2021-07-05 09:31:03 +00:00
}
}
2022-12-30 10:03:50 +00:00
Future<DeleteChallengeResponse?> getDeleteChallenge(
2022-07-08 08:50:19 +00:00
BuildContext context,
) async {
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.get("/users/delete-challenge");
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
2022-07-08 08:50:19 +00:00
return DeleteChallengeResponse(
allowDelete: response.data["allowDelete"] as bool,
encryptedChallenge: response.data["encryptedChallenge"],
);
} else {
throw Exception("delete action failed");
}
} catch (e) {
_logger.severe(e);
await showGenericErrorDialog(context: context);
2022-07-08 08:50:19 +00:00
return null;
}
}
Future<void> deleteAccount(
BuildContext context,
String challengeResponse, {
required String reasonCategory,
required String feedback,
}) async {
2022-07-07 08:09:38 +00:00
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.delete(
"/users/delete",
2022-07-08 08:50:19 +00:00
data: {
"challenge": challengeResponse,
"reasonCategory": reasonCategory,
"feedback": feedback,
2022-07-08 08:50:19 +00:00
},
2022-07-07 08:09:38 +00:00
);
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
2022-07-07 08:09:38 +00:00
// clear data
await Configuration.instance.logout();
} else {
throw Exception("delete action failed");
}
} catch (e) {
_logger.severe(e);
2022-12-22 13:38:39 +00:00
rethrow;
2022-07-07 08:09:38 +00:00
}
}
Future<void> verifyEmail(
BuildContext context,
String ott, {
bool isResettingPasswordScreen = false,
}) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).pleaseWait);
2020-08-25 06:00:19 +00:00
await dialog.show();
2023-11-06 12:03:33 +00:00
final verifyData = {
"email": _config.getEmail(),
"ott": ott,
};
if (!_config.isLoggedIn()) {
verifyData["source"] = _getRefSource();
}
try {
final response = await _dio.post(
_config.getHttpEndpoint() + "/users/verify-email",
2023-11-06 12:03:33 +00:00
data: verifyData,
);
2020-08-25 06:00:19 +00:00
await dialog.hide();
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
2021-07-22 18:41:58 +00:00
Widget page;
2021-06-26 10:37:17 +00:00
final String twoFASessionID = response.data["twoFactorSessionID"];
2022-12-30 10:03:50 +00:00
if (twoFASessionID.isNotEmpty) {
setTwoFactor(value: true);
2021-06-26 10:37:17 +00:00
page = TwoFactorAuthenticationPage(twoFASessionID);
} else {
2021-06-26 10:37:17 +00:00
await _saveConfiguration(response);
if (Configuration.instance.getEncryptedToken() != null) {
if (isResettingPasswordScreen) {
2023-07-18 12:28:45 +00:00
page = const RecoveryPage();
} else {
page = const PasswordReentryPage();
}
2021-06-26 10:37:17 +00:00
} else {
page = const PasswordEntryPage(
mode: PasswordEntryMode.set,
);
2021-06-26 10:37:17 +00:00
}
}
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return page;
},
),
(route) => route.isFirst,
);
2020-08-25 06:00:19 +00:00
} else {
// should never reach here
throw Exception("unexpected response during email verification");
2020-08-25 06:00:19 +00:00
}
} on DioError catch (e) {
_logger.info(e);
await dialog.hide();
2022-12-30 10:03:50 +00:00
if (e.response != null && e.response!.statusCode == 410) {
2022-02-04 05:31:07 +00:00
await showErrorDialog(
2022-06-11 08:23:52 +00:00
context,
2023-04-07 06:33:40 +00:00
S.of(context).oops,
S.of(context).yourVerificationCodeHasExpired,
2022-06-11 08:23:52 +00:00
);
Navigator.of(context).pop();
} else {
2022-06-11 08:23:52 +00:00
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).incorrectCode,
S.of(context).sorryTheCodeYouveEnteredIsIncorrect,
2022-06-11 08:23:52 +00:00
);
}
2021-09-04 11:32:39 +00:00
} catch (e) {
await dialog.hide();
_logger.severe(e);
2023-04-08 04:17:44 +00:00
showErrorDialog(
context,
S.of(context).oops,
S.of(context).verificationFailedPleaseTryAgain,
);
}
2020-08-25 06:00:19 +00:00
}
2022-06-23 13:06:35 +00:00
Future<void> setEmail(String email) async {
await _config.setEmail(email);
2022-12-30 10:03:50 +00:00
emailValueNotifier.value = email;
2022-06-23 13:06:35 +00:00
}
2023-11-06 12:03:33 +00:00
Future<void> setRefSource(String refSource) async {
await _preferences.setString(kReferralSource, refSource);
}
String _getRefSource() {
return _preferences.getString(kReferralSource) ?? "";
}
2021-07-28 18:06:30 +00:00
Future<void> changeEmail(
BuildContext context,
String email,
String ott,
) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).pleaseWait);
2021-07-28 18:06:30 +00:00
await dialog.show();
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.post(
"/users/change-email",
2021-07-28 18:06:30 +00:00
data: {
"email": email,
"ott": ott,
},
);
await dialog.hide();
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
2023-04-07 06:33:40 +00:00
showShortToast(context, S.of(context).emailChangedTo(email));
2022-06-23 13:06:35 +00:00
await setEmail(email);
2021-07-28 18:06:30 +00:00
Navigator.of(context).popUntil((route) => route.isFirst);
Bus.instance.fire(UserDetailsChangedEvent());
2021-07-28 18:06:30 +00:00
return;
}
2023-04-08 04:17:44 +00:00
showErrorDialog(
context,
S.of(context).oops,
S.of(context).verificationFailedPleaseTryAgain,
);
2021-07-28 18:06:30 +00:00
} on DioError catch (e) {
await dialog.hide();
2022-12-30 10:03:50 +00:00
if (e.response != null && e.response!.statusCode == 403) {
2023-04-07 06:33:40 +00:00
showErrorDialog(
2023-04-08 04:17:44 +00:00
context,
S.of(context).oops,
S.of(context).thisEmailIsAlreadyInUse,
);
2021-07-28 18:06:30 +00:00
} else {
2022-06-11 08:23:52 +00:00
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).incorrectCode,
S.of(context).authenticationFailedPleaseTryAgain,
2022-06-11 08:23:52 +00:00
);
2021-07-28 18:06:30 +00:00
}
} catch (e) {
await dialog.hide();
_logger.severe(e);
2023-04-08 04:17:44 +00:00
showErrorDialog(
context,
S.of(context).oops,
S.of(context).verificationFailedPleaseTryAgain,
);
2021-07-28 18:06:30 +00:00
}
}
2021-04-01 14:26:08 +00:00
Future<void> setAttributes(KeyGenResult result) async {
2021-03-26 16:13:32 +00:00
try {
2023-07-18 16:01:45 +00:00
await registerOrUpdateSrp(result.loginKey);
2022-10-14 09:32:51 +00:00
await _enteDio.put(
"/users/attributes",
2021-03-26 16:13:32 +00:00
data: {
"keyAttributes": result.keyAttributes.toMap(),
},
2021-03-26 16:13:32 +00:00
);
2021-03-29 18:35:46 +00:00
await _config.setKey(result.privateKeyAttributes.key);
await _config.setSecretKey(result.privateKeyAttributes.secretKey);
await _config.setKeyAttributes(result.keyAttributes);
2021-03-26 16:13:32 +00:00
} catch (e) {
_logger.severe(e);
2021-07-22 18:41:58 +00:00
rethrow;
2021-03-26 16:13:32 +00:00
}
}
2023-07-18 02:47:29 +00:00
Future<SrpAttributes> getSrpAttributes(String email) async {
try {
final response = await _dio.get(
_config.getHttpEndpoint() + "/users/srp/attributes",
queryParameters: {
"email": email,
},
);
if (response.statusCode == 200) {
return SrpAttributes.fromMap(response.data);
} else {
throw Exception("get-srp-attributes action failed");
}
} on DioError catch (e) {
if (e.response != null && e.response!.statusCode == 404) {
throw SrpSetupNotCompleteError();
}
rethrow;
} catch (e) {
rethrow;
2023-07-18 02:47:29 +00:00
}
}
2023-07-18 16:01:45 +00:00
Future<void> registerOrUpdateSrp(
Uint8List loginKey, {
SetKeysRequest? setKeysRequest,
}) async {
2023-07-15 11:04:44 +00:00
try {
2023-07-18 02:47:29 +00:00
final String username = const Uuid().v4().toString();
2023-07-18 03:28:32 +00:00
final SecureRandom random = _getSecureRandom();
final Uint8List identity = Uint8List.fromList(utf8.encode(username));
2023-07-17 08:04:52 +00:00
final Uint8List password = loginKey;
final Uint8List salt = random.nextBytes(16);
final gen = SRP6VerifierGenerator(
2023-07-18 05:26:57 +00:00
group: kDefaultSrpGroup,
2023-07-17 08:04:52 +00:00
digest: Digest('SHA-256'),
);
final v = gen.generateVerifier(salt, identity, password);
final client = SRP6Client(
2023-07-18 05:26:57 +00:00
group: kDefaultSrpGroup,
2023-07-17 08:04:52 +00:00
digest: Digest('SHA-256'),
random: random,
);
final A = client.generateClientCredentials(salt, identity, password);
final request = SetupSRPRequest(
2023-07-18 02:47:29 +00:00
srpUserID: username,
2023-07-17 08:04:52 +00:00
srpSalt: base64Encode(salt),
srpVerifier: base64Encode(SRP6Util.encodeBigInt(v)),
srpA: base64Encode(SRP6Util.encodeBigInt(A!)),
isUpdate: false,
2023-07-15 11:04:44 +00:00
);
final response = await _enteDio.post(
"/users/srp/setup",
data: request.toMap(),
);
if (response.statusCode == 200) {
2023-07-17 08:04:52 +00:00
final SetupSRPResponse setupSRPResponse =
SetupSRPResponse.fromJson(response.data);
final serverB =
SRP6Util.decodeBigInt(base64Decode(setupSRPResponse.srpB));
2023-07-18 02:47:29 +00:00
// ignore: need to calculate secret to get M1, unused_local_variable
2023-07-17 08:04:52 +00:00
final clientS = client.calculateSecret(serverB);
final clientM = client.calculateClientEvidenceMessage();
2023-09-22 07:00:23 +00:00
// ignore: unused_local_variable
2023-07-18 16:01:45 +00:00
late Response srpCompleteResponse;
if (setKeysRequest == null) {
2023-07-18 16:01:45 +00:00
srpCompleteResponse = await _enteDio.post(
"/users/srp/complete",
data: {
'setupID': setupSRPResponse.setupID,
'srpM1': base64Encode(SRP6Util.encodeBigInt(clientM!)),
},
);
} else {
srpCompleteResponse = await _enteDio.post(
"/users/srp/update",
data: {
'setupID': setupSRPResponse.setupID,
'srpM1': base64Encode(SRP6Util.encodeBigInt(clientM!)),
'updatedKeyAttr': setKeysRequest.toMap(),
},
);
}
2023-07-15 11:04:44 +00:00
} else {
throw Exception("register-srp action failed");
}
} catch (e, s) {
_logger.severe("failed to register srp", e, s);
2023-07-15 11:04:44 +00:00
rethrow;
}
}
2023-07-18 03:28:32 +00:00
SecureRandom _getSecureRandom() {
2023-07-18 05:26:57 +00:00
final List<int> seeds = [];
final random = Random.secure();
for (int i = 0; i < 32; i++) {
seeds.add(random.nextInt(255));
}
final secureRandom = FortunaRandom();
secureRandom.seed(KeyParameter(Uint8List.fromList(seeds)));
return secureRandom;
2023-07-18 03:28:32 +00:00
}
Future<void> verifyEmailViaPassword(
BuildContext context,
SrpAttributes srpAttributes,
String userPassword,
) async {
final dialog = createProgressDialog(
context,
S.of(context).pleaseWait,
isDismissible: true,
);
2023-07-18 02:47:29 +00:00
await dialog.show();
2023-08-14 08:28:42 +00:00
late Uint8List keyEncryptionKey;
2023-07-18 02:47:29 +00:00
try {
2023-08-14 08:28:42 +00:00
keyEncryptionKey = await CryptoUtil.deriveKey(
2023-07-18 02:47:29 +00:00
utf8.encode(userPassword) as Uint8List,
CryptoUtil.base642bin(srpAttributes.kekSalt),
srpAttributes.memLimit,
srpAttributes.opsLimit,
2023-07-19 06:52:19 +00:00
);
2023-08-14 08:28:42 +00:00
final loginKey = await CryptoUtil.deriveLoginKey(keyEncryptionKey);
final Uint8List identity = Uint8List.fromList(
utf8.encode(srpAttributes.srpUserID),
);
2023-07-18 02:47:29 +00:00
final Uint8List salt = base64Decode(srpAttributes.srpSalt);
final Uint8List password = loginKey;
2023-07-18 05:26:57 +00:00
final SecureRandom random = _getSecureRandom();
2023-07-18 02:47:29 +00:00
final client = SRP6Client(
2023-07-18 05:26:57 +00:00
group: kDefaultSrpGroup,
2023-07-18 02:47:29 +00:00
digest: Digest('SHA-256'),
random: random,
);
final A = client.generateClientCredentials(salt, identity, password);
final createSessionResponse = await _dio.post(
_config.getHttpEndpoint() + "/users/srp/create-session",
data: {
"srpUserID": srpAttributes.srpUserID,
"srpA": base64Encode(SRP6Util.encodeBigInt(A!)),
},
);
final String sessionID = createSessionResponse.data["sessionID"];
final String srpB = createSessionResponse.data["srpB"];
final serverB = SRP6Util.decodeBigInt(base64Decode(srpB));
// ignore: need to calculate secret to get M1, unused_local_variable
final clientS = client.calculateSecret(serverB);
final clientM = client.calculateClientEvidenceMessage();
final response = await _dio.post(
_config.getHttpEndpoint() + "/users/srp/verify-session",
2023-07-18 02:47:29 +00:00
data: {
"sessionID": sessionID,
"srpUserID": srpAttributes.srpUserID,
"srpM1": base64Encode(SRP6Util.encodeBigInt(clientM!)),
},
);
if (response.statusCode == 200) {
Widget page;
final String twoFASessionID = response.data["twoFactorSessionID"];
Configuration.instance.setVolatilePassword(userPassword);
if (twoFASessionID.isNotEmpty) {
setTwoFactor(value: true);
page = TwoFactorAuthenticationPage(twoFASessionID);
} else {
await _saveConfiguration(response);
if (Configuration.instance.getEncryptedToken() != null) {
2023-08-14 08:28:42 +00:00
await Configuration.instance.decryptSecretsAndGetKeyEncKey(
userPassword,
Configuration.instance.getKeyAttributes()!,
keyEncryptionKey: keyEncryptionKey,
);
page = const HomeWidget();
2023-07-18 02:47:29 +00:00
} else {
throw Exception("unexpected response during email verification");
2023-07-18 02:47:29 +00:00
}
}
2023-08-14 08:28:42 +00:00
await dialog.hide();
if (page is HomeWidget) {
Navigator.of(context).popUntil((route) => route.isFirst);
Bus.instance.fire(AccountConfiguredEvent());
} else {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return page;
},
),
(route) => route.isFirst,
);
}
2023-07-18 02:47:29 +00:00
} else {
// should never reach here
throw Exception("unexpected response during email verification");
}
} on DioError catch (e, s) {
2023-07-18 02:47:29 +00:00
await dialog.hide();
2023-07-18 04:03:44 +00:00
if (e.response != null && e.response!.statusCode == 401) {
await _showContactSupportDialog(
2023-07-18 02:47:29 +00:00
context,
S.of(context).incorrectPasswordTitle,
S.of(context).pleaseTryAgain,
2023-07-18 02:47:29 +00:00
);
} else {
_logger.severe('failed to verify password', e, s);
await _showContactSupportDialog(
2023-07-18 02:47:29 +00:00
context,
2023-07-18 04:03:44 +00:00
S.of(context).oops,
S.of(context).verificationFailedPleaseTryAgain,
2023-07-18 02:47:29 +00:00
);
}
} catch (e, s) {
_logger.severe('failed to verify password', e, s);
2023-07-18 02:47:29 +00:00
await dialog.hide();
await _showContactSupportDialog(
2023-07-18 02:47:29 +00:00
context,
S.of(context).oops,
S.of(context).verificationFailedPleaseTryAgain,
);
}
}
Future<void> updateKeyAttributes(
KeyAttributes keyAttributes,
Uint8List loginKey,
) async {
2021-03-26 16:13:32 +00:00
try {
2021-03-28 12:43:44 +00:00
final setKeyRequest = SetKeysRequest(
kekSalt: keyAttributes.kekSalt,
encryptedKey: keyAttributes.encryptedKey,
keyDecryptionNonce: keyAttributes.keyDecryptionNonce,
memLimit: keyAttributes.memLimit!,
opsLimit: keyAttributes.opsLimit!,
2021-03-28 12:43:44 +00:00
);
2023-07-18 16:01:45 +00:00
await registerOrUpdateSrp(loginKey, setKeysRequest: setKeyRequest);
2021-04-01 14:26:08 +00:00
await _config.setKeyAttributes(keyAttributes);
2021-03-26 16:13:32 +00:00
} catch (e) {
_logger.severe(e);
2021-07-22 18:41:58 +00:00
rethrow;
2021-03-26 16:13:32 +00:00
}
}
Future<void> setRecoveryKey(KeyAttributes keyAttributes) async {
try {
final setRecoveryKeyRequest = SetRecoveryKeyRequest(
keyAttributes.masterKeyEncryptedWithRecoveryKey!,
keyAttributes.masterKeyDecryptionNonce!,
2022-12-30 10:03:50 +00:00
keyAttributes.recoveryKeyEncryptedWithMasterKey!,
keyAttributes.recoveryKeyDecryptionNonce!,
);
2022-10-14 09:54:57 +00:00
await _enteDio.put(
"/users/recovery-key",
data: setRecoveryKeyRequest.toMap(),
);
await _config.setKeyAttributes(keyAttributes);
} catch (e) {
_logger.severe(e);
2021-07-22 18:41:58 +00:00
rethrow;
}
}
2021-06-26 10:37:17 +00:00
Future<void> verifyTwoFactor(
2022-06-11 08:23:52 +00:00
BuildContext context,
String sessionID,
String code,
) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).authenticating);
2021-06-26 10:37:17 +00:00
await dialog.show();
try {
final response = await _dio.post(
_config.getHttpEndpoint() + "/users/two-factor/verify",
data: {
"sessionID": sessionID,
"code": code,
},
);
await dialog.hide();
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
2023-04-07 06:33:40 +00:00
showShortToast(context, S.of(context).authenticationSuccessful);
2021-06-26 10:37:17 +00:00
await _saveConfiguration(response);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return const PasswordReentryPage();
2021-06-26 10:37:17 +00:00
},
),
(route) => route.isFirst,
);
}
2021-06-26 10:56:52 +00:00
} on DioError catch (e) {
await dialog.hide();
_logger.severe(e);
2022-12-30 10:03:50 +00:00
if (e.response != null && e.response!.statusCode == 404) {
2022-06-10 14:29:56 +00:00
showToast(context, "Session expired");
2021-06-26 10:56:52 +00:00
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return const LoginPage();
2021-06-26 10:56:52 +00:00
},
),
(route) => route.isFirst,
);
} else {
2022-06-11 08:23:52 +00:00
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).incorrectCode,
S.of(context).authenticationFailedPleaseTryAgain,
2022-06-11 08:23:52 +00:00
);
2021-06-26 10:56:52 +00:00
}
2021-06-26 10:37:17 +00:00
} catch (e) {
await dialog.hide();
_logger.severe(e);
2022-02-04 05:31:07 +00:00
showErrorDialog(
2022-06-11 08:23:52 +00:00
context,
2023-04-07 06:33:40 +00:00
S.of(context).oops,
S.of(context).authenticationFailedPleaseTryAgain,
2022-06-11 08:23:52 +00:00
);
2021-06-26 10:37:17 +00:00
}
}
2023-03-14 01:40:54 +00:00
Future<void> recoverTwoFactor(BuildContext context, String sessionID) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).pleaseWait);
2023-03-14 01:40:54 +00:00
await dialog.show();
try {
final response = await _dio.get(
_config.getHttpEndpoint() + "/users/two-factor/recover",
queryParameters: {
"sessionID": sessionID,
},
);
if (response.statusCode == 200) {
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return TwoFactorRecoveryPage(
sessionID,
response.data["encryptedSecret"],
response.data["secretDecryptionNonce"],
);
},
),
(route) => route.isFirst,
);
}
} on DioError catch (e) {
_logger.severe(e);
if (e.response != null && e.response!.statusCode == 404) {
2023-04-07 06:33:40 +00:00
showToast(context, S.of(context).sessionExpired);
2023-03-14 01:40:54 +00:00
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return const LoginPage();
},
),
(route) => route.isFirst,
);
} else {
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).oops,
S.of(context).somethingWentWrongPleaseTryAgain,
2023-03-14 01:40:54 +00:00
);
}
} catch (e) {
_logger.severe(e);
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).oops,
S.of(context).somethingWentWrongPleaseTryAgain,
2023-03-14 01:40:54 +00:00
);
} finally {
await dialog.hide();
}
}
Future<void> removeTwoFactor(
BuildContext context,
String sessionID,
String recoveryKey,
String encryptedSecret,
String secretDecryptionNonce,
) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).pleaseWait);
2023-03-14 01:40:54 +00:00
await dialog.show();
String secret;
try {
if (recoveryKey.contains(' ')) {
if (recoveryKey.split(' ').length != mnemonicKeyWordCount) {
throw AssertionError(
'recovery code should have $mnemonicKeyWordCount words',
);
}
recoveryKey = bip39.mnemonicToEntropy(recoveryKey);
}
secret = CryptoUtil.bin2base64(
await CryptoUtil.decrypt(
CryptoUtil.base642bin(encryptedSecret),
CryptoUtil.hex2bin(recoveryKey.trim()),
CryptoUtil.base642bin(secretDecryptionNonce),
),
);
} catch (e) {
await dialog.hide();
await showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).incorrectRecoveryKey,
S.of(context).theRecoveryKeyYouEnteredIsIncorrect,
2023-03-14 01:40:54 +00:00
);
return;
}
try {
final response = await _dio.post(
_config.getHttpEndpoint() + "/users/two-factor/remove",
data: {
"sessionID": sessionID,
"secret": secret,
},
);
if (response.statusCode == 200) {
2023-04-07 06:33:40 +00:00
showShortToast(
2023-04-08 04:17:44 +00:00
context,
S.of(context).twofactorAuthenticationSuccessfullyReset,
);
2023-03-14 01:40:54 +00:00
await _saveConfiguration(response);
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return const PasswordReentryPage();
},
),
(route) => route.isFirst,
);
}
} on DioError catch (e) {
_logger.severe(e);
if (e.response != null && e.response!.statusCode == 404) {
showToast(context, "Session expired");
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(
builder: (BuildContext context) {
return const LoginPage();
},
),
(route) => route.isFirst,
);
} else {
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).oops,
S.of(context).somethingWentWrongPleaseTryAgain,
2023-03-14 01:40:54 +00:00
);
}
} catch (e) {
_logger.severe(e);
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).oops,
S.of(context).somethingWentWrongPleaseTryAgain,
2023-03-14 01:40:54 +00:00
);
} finally {
await dialog.hide();
}
}
Future<void> setupTwoFactor(BuildContext context, Completer completer) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).pleaseWait);
2021-06-29 09:48:01 +00:00
await dialog.show();
try {
2022-10-14 09:54:57 +00:00
final response = await _enteDio.post("/users/two-factor/setup");
2021-06-29 09:48:01 +00:00
await dialog.hide();
2022-11-06 10:36:33 +00:00
unawaited(
routeToPage(
context,
TwoFactorSetupPage(
response.data["secretCode"],
response.data["qrCode"],
completer,
2022-11-06 10:36:33 +00:00
),
2022-06-11 08:23:52 +00:00
),
);
2022-07-13 03:42:37 +00:00
} catch (e) {
2021-06-29 09:48:01 +00:00
await dialog.hide();
2022-07-13 03:42:37 +00:00
_logger.severe("Failed to setup tfa", e);
completer.complete();
2021-07-22 18:41:58 +00:00
rethrow;
2021-06-29 09:48:01 +00:00
}
}
Future<bool> enableTwoFactor(
2022-06-11 08:23:52 +00:00
BuildContext context,
String secret,
String code,
) async {
2023-03-14 01:40:54 +00:00
Uint8List recoveryKey;
try {
recoveryKey = await getOrCreateRecoveryKey(context);
} catch (e) {
showGenericErrorDialog(context: context);
return false;
}
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).verifying);
2021-06-29 15:03:54 +00:00
await dialog.show();
2023-03-14 01:40:54 +00:00
final encryptionResult =
CryptoUtil.encryptSync(CryptoUtil.base642bin(secret), recoveryKey);
2021-06-29 09:48:01 +00:00
try {
2022-10-14 09:54:57 +00:00
await _enteDio.post(
"/users/two-factor/enable",
2023-03-14 01:40:54 +00:00
data: {
"code": code,
"encryptedTwoFactorSecret":
CryptoUtil.bin2base64(encryptionResult.encryptedData!),
"twoFactorSecretDecryptionNonce":
CryptoUtil.bin2base64(encryptionResult.nonce!),
},
2021-06-29 09:48:01 +00:00
);
await dialog.hide();
Navigator.pop(context);
Bus.instance.fire(TwoFactorStatusChangeEvent(true));
return true;
2021-06-29 09:48:01 +00:00
} catch (e, s) {
await dialog.hide();
_logger.severe(e, s);
if (e is DioError) {
2022-12-30 10:03:50 +00:00
if (e.response != null && e.response!.statusCode == 401) {
2022-06-11 08:23:52 +00:00
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).incorrectCode,
S.of(context).pleaseVerifyTheCodeYouHaveEntered,
2022-06-11 08:23:52 +00:00
);
return false;
2021-06-29 09:48:01 +00:00
}
}
2022-06-11 08:23:52 +00:00
showErrorDialog(
context,
2023-04-07 06:33:40 +00:00
S.of(context).somethingWentWrong,
S.of(context).pleaseContactSupportIfTheProblemPersists,
2022-06-11 08:23:52 +00:00
);
2021-06-29 09:48:01 +00:00
}
return false;
2021-06-29 09:48:01 +00:00
}
Future<void> disableTwoFactor(BuildContext context) async {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(
2023-04-08 04:17:44 +00:00
context,
S.of(context).disablingTwofactorAuthentication,
);
2021-06-29 09:48:01 +00:00
await dialog.show();
try {
2022-10-14 09:54:57 +00:00
await _enteDio.post(
"/users/two-factor/disable",
2021-06-29 09:48:01 +00:00
);
await dialog.hide();
Bus.instance.fire(TwoFactorStatusChangeEvent(false));
2022-11-06 10:36:33 +00:00
unawaited(
showShortToast(
2022-11-06 10:36:33 +00:00
context,
2023-04-07 06:33:40 +00:00
S.of(context).twofactorAuthenticationHasBeenDisabled,
2022-11-06 10:36:33 +00:00
),
);
2022-07-13 03:42:37 +00:00
} catch (e) {
2021-06-29 09:48:01 +00:00
await dialog.hide();
2022-07-13 03:42:37 +00:00
_logger.severe("Failed to disabled 2FA", e);
2022-11-06 10:36:33 +00:00
await showErrorDialog(
2022-06-11 08:23:52 +00:00
context,
2023-04-07 06:33:40 +00:00
S.of(context).somethingWentWrong,
S.of(context).pleaseContactSupportIfTheProblemPersists,
2022-06-11 08:23:52 +00:00
);
2021-06-29 09:48:01 +00:00
}
}
Future<bool> fetchTwoFactorStatus() async {
try {
2022-10-14 09:54:57 +00:00
final response = await _enteDio.get("/users/two-factor/status");
setTwoFactor(value: response.data["status"]);
2021-06-29 09:48:01 +00:00
return response.data["status"];
2022-07-13 03:42:37 +00:00
} catch (e) {
_logger.severe("Failed to fetch 2FA status", e);
2021-07-22 18:41:58 +00:00
rethrow;
2021-06-29 09:48:01 +00:00
}
}
2021-06-29 15:03:54 +00:00
Future<Uint8List> getOrCreateRecoveryKey(BuildContext context) async {
2022-12-30 10:03:50 +00:00
final String? encryptedRecoveryKey =
_config.getKeyAttributes()!.recoveryKeyEncryptedWithMasterKey;
2021-06-29 15:03:54 +00:00
if (encryptedRecoveryKey == null || encryptedRecoveryKey.isEmpty) {
2023-04-07 06:33:40 +00:00
final dialog = createProgressDialog(context, S.of(context).pleaseWait);
2021-06-29 15:03:54 +00:00
await dialog.show();
try {
final keyAttributes = await _config.createNewRecoveryKey();
await setRecoveryKey(keyAttributes);
await dialog.hide();
} catch (e, s) {
await dialog.hide();
_logger.severe(e, s);
2021-07-22 18:41:58 +00:00
rethrow;
2021-06-29 15:03:54 +00:00
}
}
final recoveryKey = _config.getRecoveryKey();
return recoveryKey;
}
2022-12-30 10:03:50 +00:00
Future<String?> getPaymentToken() async {
try {
2022-10-14 09:54:57 +00:00
final response = await _enteDio.get("/users/payment-token");
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
return response.data["paymentToken"];
} else {
throw Exception("non 200 ok response");
}
2022-07-13 03:42:37 +00:00
} catch (e) {
_logger.severe("Failed to get payment token", e);
return null;
}
}
Future<String> getFamiliesToken() async {
try {
2022-10-14 09:32:51 +00:00
final response = await _enteDio.get("/users/families-token");
2022-12-30 10:03:50 +00:00
if (response.statusCode == 200) {
return response.data["familiesToken"];
} else {
throw Exception("non 200 ok response");
}
} catch (e, s) {
_logger.severe("failed to fetch families token", e, s);
rethrow;
}
}
Future<void> _saveConfiguration(Response response) async {
await Configuration.instance.setUserID(response.data["id"]);
if (response.data["encryptedToken"] != null) {
await Configuration.instance
.setEncryptedToken(response.data["encryptedToken"]);
await Configuration.instance.setKeyAttributes(
2022-06-11 08:23:52 +00:00
KeyAttributes.fromMap(response.data["keyAttributes"]),
);
} else {
await Configuration.instance.setToken(response.data["token"]);
2020-08-15 01:22:14 +00:00
}
}
Future<void> setTwoFactor({
bool value = false,
bool fetchTwoFactorStatus = false,
}) async {
if (fetchTwoFactorStatus) {
value = await UserService.instance.fetchTwoFactorStatus();
}
_preferences.setBool(keyHasEnabledTwoFactor, value);
}
bool hasEnabledTwoFactor() {
2022-12-30 10:03:50 +00:00
return _preferences.getBool(keyHasEnabledTwoFactor) ?? false;
}
2023-08-04 04:24:54 +00:00
bool hasEmailMFAEnabled() {
final UserDetails? profile = getCachedUserDetails();
if (profile != null && profile.profileData != null) {
return profile.profileData!.isEmailMFAEnabled;
}
return true;
}
2023-08-04 04:24:54 +00:00
Future<void> updateEmailMFA(bool isEnabled) async {
try {
await _enteDio.put(
"/users/email-mfa",
data: {
"isEnabled": isEnabled,
},
);
final UserDetails? profile = getCachedUserDetails();
if (profile != null && profile.profileData != null) {
profile.profileData!.isEmailMFAEnabled = isEnabled;
await _preferences.setString(keyUserDetails, profile.toJson());
}
} catch (e) {
_logger.severe("Failed to update email mfa", e);
2023-08-04 04:24:54 +00:00
rethrow;
}
}
Future<void> _showContactSupportDialog(
BuildContext context,
String title,
String message,
) async {
final dialogChoice = await showChoiceDialog(
context,
title: title,
body: message,
firstButtonLabel: S.of(context).contactSupport,
secondButtonLabel: S.of(context).ok,
);
if (dialogChoice!.action == ButtonAction.first) {
await sendLogs(
context,
S.of(context).contactSupport,
"support@ente.io",
postShare: () {},
);
}
}
2020-04-30 15:09:41 +00:00
}