Skip to content

Enhance auth feature #34

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

Merged
merged 15 commits into from
Jul 28, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
29 changes: 29 additions & 0 deletions lib/authentication/bloc/authentication_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import 'package:equatable/equatable.dart';
part 'authentication_event.dart';
part 'authentication_state.dart';

const _requestCodeCooldownDuration = Duration(seconds: 60);

/// {@template authentication_bloc}
/// Bloc responsible for managing the authentication state of the application.
/// {@endtemplate}
Expand All @@ -40,6 +42,7 @@ class AuthenticationBloc
);
on<AuthenticationVerifyCodeRequested>(_onAuthenticationVerifyCodeRequested);
on<AuthenticationSignOutRequested>(_onAuthenticationSignOutRequested);
on<AuthenticationCooldownCompleted>(_onAuthenticationCooldownCompleted);
}

final AuthRepository _authenticationRepository;
Expand Down Expand Up @@ -72,18 +75,32 @@ class AuthenticationBloc
AuthenticationRequestSignInCodeRequested event,
Emitter<AuthenticationState> emit,
) async {
// Prevent request if already in cooldown
if (state.cooldownEndTime != null &&
state.cooldownEndTime!.isAfter(DateTime.now())) {
return;
}

emit(state.copyWith(status: AuthenticationStatus.requestCodeLoading));
try {
await _authenticationRepository.requestSignInCode(
event.email,
isDashboardLogin: true,
);
final cooldownEndTime = DateTime.now().add(_requestCodeCooldownDuration);
emit(
state.copyWith(
status: AuthenticationStatus.codeSentSuccess,
email: event.email,
cooldownEndTime: cooldownEndTime,
),
);

// Start a timer to transition out of cooldown
Timer(
_requestCodeCooldownDuration,
() => add(const AuthenticationCooldownCompleted()),
);
} on InvalidInputException catch (e) {
emit(state.copyWith(status: AuthenticationStatus.failure, exception: e));
} on UnauthorizedException catch (e) {
Expand Down Expand Up @@ -181,6 +198,18 @@ class AuthenticationBloc
}
}

void _onAuthenticationCooldownCompleted(
AuthenticationCooldownCompleted event,
Emitter<AuthenticationState> emit,
) {
emit(
state.copyWith(
status: AuthenticationStatus.initial,
clearCooldownEndTime: true,
),
);
}

@override
Future<void> close() {
_userAuthSubscription.cancel();
Expand Down
8 changes: 8 additions & 0 deletions lib/authentication/bloc/authentication_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,11 @@ final class _AuthenticationStatusChanged extends AuthenticationEvent {
@override
List<Object?> get props => [user];
}

/// {@template authentication_cooldown_completed}
/// Event triggered when the sign-in code request cooldown has completed.
/// {@endtemplate}
final class AuthenticationCooldownCompleted extends AuthenticationEvent {
/// {@macro authentication_cooldown_completed}
const AuthenticationCooldownCompleted();
}
10 changes: 9 additions & 1 deletion lib/authentication/bloc/authentication_state.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ final class AuthenticationState extends Equatable {
this.user,
this.email,
this.exception,
this.cooldownEndTime,
});

/// The current status of the authentication process.
Expand All @@ -50,8 +51,11 @@ final class AuthenticationState extends Equatable {
/// The error describing an authentication failure, if any.
final HttpException? exception;

/// The time when the cooldown for requesting a new code ends.
final DateTime? cooldownEndTime;

@override
List<Object?> get props => [status, user, email, exception];
List<Object?> get props => [status, user, email, exception, cooldownEndTime];

/// Creates a copy of this [AuthenticationState] with the given fields
/// replaced with the new values.
Expand All @@ -60,12 +64,16 @@ final class AuthenticationState extends Equatable {
User? user,
String? email,
HttpException? exception,
DateTime? cooldownEndTime,
bool clearCooldownEndTime = false,
}) {
return AuthenticationState(
status: status ?? this.status,
user: user ?? this.user,
email: email ?? this.email,
exception: exception ?? this.exception,
cooldownEndTime:
clearCooldownEndTime ? null : cooldownEndTime ?? this.cooldownEndTime,
);
}
}
65 changes: 38 additions & 27 deletions lib/authentication/view/email_code_verification_page.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_app_web_dashboard_full_source_code/app/bloc/app_bloc.dart';
import 'package:flutter_news_app_web_dashboard_full_source_code/app/config/config.dart';
import 'package:flutter_news_app_web_dashboard_full_source_code/authentication/bloc/authentication_bloc.dart';
import 'package:flutter_news_app_web_dashboard_full_source_code/l10n/l10n.dart';
import 'package:pinput/pinput.dart';
import 'package:ui_kit/ui_kit.dart';

/// {@template email_code_verification_page}
Expand Down Expand Up @@ -131,10 +131,12 @@ class _EmailCodeVerificationFormState
extends State<_EmailCodeVerificationForm> {
final _formKey = GlobalKey<FormState>();
final _codeController = TextEditingController();
final _focusNode = FocusNode();

@override
void dispose() {
_codeController.dispose();
_focusNode.dispose();
super.dispose();
}

Expand All @@ -153,39 +155,48 @@ class _EmailCodeVerificationFormState
Widget build(BuildContext context) {
final l10n = AppLocalizationsX(context).l10n;
final textTheme = Theme.of(context).textTheme;
final colorScheme = Theme.of(context).colorScheme;

final defaultPinTheme = PinTheme(
width: 56,
height: 60,
textStyle: textTheme.headlineSmall,
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: colorScheme.onSurface.withOpacity(0.12)),
),
);

return Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
// No horizontal padding needed if column is stretched
// padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
padding: EdgeInsets.zero,
child: TextFormField(
controller: _codeController,
decoration: InputDecoration(
labelText: l10n.emailCodeVerificationHint,
// border: const OutlineInputBorder(),
counterText: '',
Pinput(
length: 6,
controller: _codeController,
focusNode: _focusNode,
defaultPinTheme: defaultPinTheme,
onCompleted: (pin) => _submitForm(),
validator: (value) {
if (value == null || value.isEmpty) {
return l10n.emailCodeValidationEmptyError;
}
if (value.length != 6) {
return l10n.emailCodeValidationLengthError;
}
return null;
},
focusedPinTheme: defaultPinTheme.copyWith(
decoration: defaultPinTheme.decoration!.copyWith(
border: Border.all(color: colorScheme.primary),
),
),
errorPinTheme: defaultPinTheme.copyWith(
decoration: defaultPinTheme.decoration!.copyWith(
border: Border.all(color: colorScheme.error),
),
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
maxLength: 6,
textAlign: TextAlign.center,
style: textTheme.headlineSmall,
enabled: !widget.isLoading,
validator: (value) {
if (value == null || value.isEmpty) {
return l10n.emailCodeValidationEmptyError;
}
if (value.length != 6) {
return l10n.emailCodeValidationLengthError;
}
return null;
},
onFieldSubmitted: widget.isLoading ? null : (_) => _submitForm(),
),
),
const SizedBox(height: AppSpacing.xxl),
Expand Down
Loading
Loading