Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adds delete account functionality to template #1152

Merged
merged 16 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions flutter_news_example/lib/app/bloc/app_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class AppBloc extends Bloc<AppEvent, AppState> {
on<AppUserChanged>(_onUserChanged);
on<AppOnboardingCompleted>(_onOnboardingCompleted);
on<AppLogoutRequested>(_onLogoutRequested);
on<AppDeleteAccountRequested>(_onDeleteAccountRequested);
on<AppOpened>(_onAppOpened);

_userSubscription = _userRepository.user.listen(_userChanged);
Expand Down Expand Up @@ -74,6 +75,22 @@ class AppBloc extends Bloc<AppEvent, AppState> {
unawaited(_userRepository.logOut());
}

Future<void> _onDeleteAccountRequested(
AppDeleteAccountRequested event,
Emitter<AppState> emit,
) async {
try {
// We are disabling notifications when a user deletes their account
// because the user should not receive any notifications after their
// account is deleted.
unawaited(_notificationsRepository.toggleNotifications(enable: false));
await _userRepository.deleteAccount();
} catch (error, stackTrace) {
await _userRepository.logOut();
elianortega marked this conversation as resolved.
Show resolved Hide resolved
addError(error, stackTrace);
}
}

Future<void> _onAppOpened(AppOpened event, Emitter<AppState> emit) async {
if (state.user.isAnonymous) {
final appOpenedCount = await _userRepository.fetchAppOpenedCount();
Expand Down
4 changes: 4 additions & 0 deletions flutter_news_example/lib/app/bloc/app_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ class AppLogoutRequested extends AppEvent {
const AppLogoutRequested();
}

class AppDeleteAccountRequested extends AppEvent {
const AppDeleteAccountRequested();
}

class AppUserChanged extends AppEvent {
const AppUserChanged(this.user);

Expand Down
24 changes: 24 additions & 0 deletions flutter_news_example/lib/l10n/arb/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -616,5 +616,29 @@
"description": "Text displayed on the refresh button when a network error occurs.",
"type": "String",
"placeholders": {}
},
"deleteAccountDialogCancelButtonText": "Cancel",
"@deleteAccountDialogCancelButtonText": {
"description": "Delete account dialog cancel button text",
"type": "String",
"placeholders": {}
},
"deleteAccountDialogSubtitle": "ADD YOUR DELETE DIALOG SUBTITLE",
"@deleteAccountDialogSubtitle": {
"description": "Delete account dialog subtitle",
"type": "String",
"placeholders": {}
},
"deleteAccountDialogTitle": "ADD YOUR DELETE DIALOG TITLE",
"@deleteAccountDialogTitle": {
"description": "Delete account dialog title",
"type": "String",
"placeholders": {}
},
"userProfileDeleteAccountButton": "Delete account",
"@userProfileDeleteAccountButton": {
"description": "User profile delete account button title",
"type": "String",
"placeholders": {}
}
}
16 changes: 16 additions & 0 deletions flutter_news_example/lib/user_profile/view/user_profile_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,22 @@ class _UserProfileViewState extends State<UserProfileView>
leading: Assets.icons.aboutIcon.svg(),
title: l10n.userProfileLegalAboutTitle,
),
Align(
child: AppButton.smallTransparent(
key: const Key('userProfilePage_deleteAccountButton'),
onPressed: () {
showDialog<void>(
context: context,
builder: (_) =>
const UserProfileDeleteAccountDialog(),
);
},
child: Text(
l10n.userProfileDeleteAccountButton,
),
),
),
const SizedBox(height: AppSpacing.lg),
],
),
),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import 'package:app_ui/app_ui.dart';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_example/app/app.dart';
import 'package:flutter_news_example/l10n/l10n.dart';

class UserProfileDeleteAccountDialog extends StatelessWidget {
const UserProfileDeleteAccountDialog({super.key});

@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return AlertDialog(
title: Text(
l10n.deleteAccountDialogTitle,
style: Theme.of(context).textTheme.titleLarge,
),
content: Text(
l10n.deleteAccountDialogSubtitle,
style: Theme.of(context).textTheme.bodyMedium,
),
actions: <Widget>[
AppButton.smallDarkAqua(
key: const Key('userProfilePage_cancelDeleteAccountButton'),
onPressed: () {
Navigator.of(context).pop();
},
child: Text(l10n.deleteAccountDialogCancelButtonText),
),
AppButton.smallRedWine(
key: const Key('userProfilePage_deleteAccountButton'),
onPressed: () {
context.read<AppBloc>().add(const AppDeleteAccountRequested());
Navigator.of(context).pop();
},
child: Text(l10n.userProfileDeleteAccountButton),
),
],
);
}
}
1 change: 1 addition & 0 deletions flutter_news_example/lib/user_profile/widgets/widgets.dart
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export 'user_profile_button.dart';
export 'user_profile_delete_account_dialog.dart';
export 'user_profile_subscribe_box.dart';
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ class LogOutFailure extends AuthenticationException {
const LogOutFailure(super.error);
}

/// {@template delete_account_failure}
/// Thrown during the delete account process if a failure occurs.
/// {@endtemplate}
class DeleteAccountFailure extends AuthenticationException {
/// {@macro delete_account_failure}
const DeleteAccountFailure(super.error);
}

/// A generic Authentication Client Interface.
abstract class AuthenticationClient {
/// Stream of [AuthenticationUser] which will emit the current user when
Expand Down Expand Up @@ -160,4 +168,9 @@ abstract class AuthenticationClient {
///
/// Throws a [LogOutFailure] if an exception occurs.
Future<void> logOut();

/// Deletes the current user account.
///
/// Throws a [DeleteAccountFailure] if an exception occurs.
Future<void> deleteAccount();
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,11 @@ void main() {
returnsNormally,
);
});

test('exports DeleteAccountFailure', () {
expect(
() => DeleteAccountFailure('oops'),
returnsNormally,
);
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,23 @@ class FirebaseAuthenticationClient implements AuthenticationClient {
}
}

/// Deletes and signs out the user.
@override
Future<void> deleteAccount() async {
try {
final user = _firebaseAuth.currentUser;
if (user == null) {
throw DeleteAccountFailure(
Exception('User is not authenticated'),
);
}

await user.delete();
} catch (error, stackTrace) {
Error.throwWithStackTrace(DeleteAccountFailure(error), stackTrace);
}
}

/// Updates the user token in [TokenStorage] if the user is authenticated.
Future<void> _onUserChanged(AuthenticationUser user) async {
if (!user.isAnonymous) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,38 @@ void main() {
});
});

group('deleteAccount', () {
test('calls deleteAccount', () async {
final firebaseUser = MockFirebaseUser();
when(firebaseUser.delete).thenAnswer((_) async {});
when(() => firebaseAuth.currentUser).thenReturn(firebaseUser);

await firebaseAuthenticationClient.deleteAccount();
verify(() => firebaseAuth.currentUser).called(1);
verify(firebaseUser.delete).called(1);
});

test('throws DeleteAccountFailure if current user is null', () async {
when(() => firebaseAuth.currentUser).thenReturn(null);

expect(
firebaseAuthenticationClient.deleteAccount(),
throwsA(isA<DeleteAccountFailure>()),
);
});

test('throws DeleteAccountFailure when deleteAccount throws', () async {
final firebaseUser = MockFirebaseUser();
when(firebaseUser.delete).thenThrow(Exception());
when(() => firebaseAuth.currentUser).thenReturn(firebaseUser);

expect(
firebaseAuthenticationClient.deleteAccount(),
throwsA(isA<DeleteAccountFailure>()),
);
});
});

group('user', () {
const userId = 'mock-uid';
const email = 'mock-email';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,17 @@ class UserRepository {
}
}

/// Deletes the current user account.
Future<void> deleteAccount() async {
try {
await _authenticationClient.deleteAccount();
} on DeleteAccountFailure {
rethrow;
} catch (error, stackTrace) {
Error.throwWithStackTrace(DeleteAccountFailure(error), stackTrace);
}
}

/// Returns the number of times the app was opened.
Future<int> fetchAppOpenedCount() async {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ class FakeLogInWithFacebookCanceled extends Fake

class FakeLogOutFailure extends Fake implements LogOutFailure {}

class FakeDeleteAccountFailure extends Fake implements DeleteAccountFailure {}

class FakeSendLoginEmailLinkFailure extends Fake
implements SendLoginEmailLinkFailure {}

Expand Down Expand Up @@ -419,6 +421,29 @@ void main() {
});
});

group('deleteAccount', () {
test('calls logOut on AuthenticationClient', () async {
when(() => authenticationClient.deleteAccount())
.thenAnswer((_) async {});
await userRepository.deleteAccount();
verify(() => authenticationClient.deleteAccount()).called(1);
});

test('rethrows DeleteAccountFailure', () async {
final exception = FakeDeleteAccountFailure();
when(() => authenticationClient.deleteAccount()).thenThrow(exception);
expect(() => userRepository.deleteAccount(), throwsA(exception));
});

test('throws DeleteAccountFailure on generic exception', () async {
when(() => authenticationClient.deleteAccount()).thenThrow(Exception());
expect(
() => userRepository.deleteAccount(),
throwsA(isA<DeleteAccountFailure>()),
);
});
});

group('UserFailure', () {
final error = Exception('errorMessage');

Expand Down
Loading
Loading