selfprivacy.org.app/lib/logic/cubit/recovery_key/recovery_key_cubit.dart

80 lines
2.3 KiB
Dart
Raw Normal View History

import 'package:selfprivacy/logic/api_maps/graphql_maps/server_api/server.dart';
import 'package:selfprivacy/logic/common_enum/common_enum.dart';
2022-05-24 16:09:47 +00:00
import 'package:selfprivacy/logic/cubit/app_config_dependent/authentication_dependend_cubit.dart';
import 'package:selfprivacy/logic/models/json/recovery_token_status.dart';
part 'recovery_key_state.dart';
class RecoveryKeyCubit
extends ServerInstallationDependendCubit<RecoveryKeyState> {
2022-06-05 19:36:32 +00:00
RecoveryKeyCubit(final ServerInstallationCubit serverInstallationCubit)
2022-05-24 18:55:39 +00:00
: super(serverInstallationCubit, const RecoveryKeyState.initial());
2022-05-24 16:09:47 +00:00
2022-06-05 19:36:32 +00:00
final ServerApi api = ServerApi();
2022-05-24 16:09:47 +00:00
@override
void load() async {
if (serverInstallationCubit.state is ServerInstallationFinished) {
2022-06-05 19:36:32 +00:00
final RecoveryKeyStatus? status = await _getRecoveryKeyStatus();
2022-05-24 16:09:47 +00:00
if (status == null) {
emit(state.copyWith(loadingStatus: LoadingStatus.error));
} else {
2022-06-09 21:13:06 +00:00
emit(
state.copyWith(
status: status,
loadingStatus: LoadingStatus.success,
),
);
2022-05-24 16:09:47 +00:00
}
} else {
emit(state.copyWith(loadingStatus: LoadingStatus.uninitialized));
}
}
Future<RecoveryKeyStatus?> _getRecoveryKeyStatus() async {
final ApiResponse<RecoveryKeyStatus?> response =
2022-05-24 16:09:47 +00:00
await api.getRecoveryTokenStatus();
if (response.success) {
2022-05-24 16:09:47 +00:00
return response.data;
} else {
return null;
}
}
Future<void> refresh() async {
emit(state.copyWith(loadingStatus: LoadingStatus.refreshing));
2022-06-05 19:36:32 +00:00
final RecoveryKeyStatus? status = await _getRecoveryKeyStatus();
2022-05-24 16:09:47 +00:00
if (status == null) {
emit(state.copyWith(loadingStatus: LoadingStatus.error));
} else {
emit(
2022-06-09 21:13:06 +00:00
state.copyWith(status: status, loadingStatus: LoadingStatus.success),
);
2022-05-24 16:09:47 +00:00
}
}
Future<String> generateRecoveryKey({
2022-06-05 19:36:32 +00:00
final DateTime? expirationDate,
final int? numberOfUses,
2022-05-24 16:09:47 +00:00
}) async {
final ApiResponse<String> response =
await api.generateRecoveryToken(expirationDate, numberOfUses);
if (response.success) {
2022-05-24 16:09:47 +00:00
refresh();
return response.data;
} else {
throw GenerationError(response.message ?? 'Unknown error');
2022-05-24 16:09:47 +00:00
}
}
@override
void clear() {
emit(state.copyWith(loadingStatus: LoadingStatus.uninitialized));
}
}
class GenerationError extends Error {
GenerationError(this.message);
2022-06-05 19:36:32 +00:00
final String message;
2022-05-24 16:09:47 +00:00
}