Skip to content

Enhance auth feature #63

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 7 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
27 changes: 27 additions & 0 deletions lib/authentication/bloc/authentication_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,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 @@ -31,6 +33,7 @@ class AuthenticationBloc
_onAuthenticationAnonymousSignInRequested,
);
on<AuthenticationSignOutRequested>(_onAuthenticationSignOutRequested);
on<AuthenticationCooldownCompleted>(_onAuthenticationCooldownCompleted);
}

final AuthRepository _authenticationRepository;
Expand Down Expand Up @@ -63,15 +66,27 @@ class AuthenticationBloc
AuthenticationRequestSignInCodeRequested event,
Emitter<AuthenticationState> emit,
) async {
if (state.cooldownEndTime != null &&
state.cooldownEndTime!.isAfter(DateTime.now())) {
return;
}

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

Timer(
_requestCodeCooldownDuration,
() => add(const AuthenticationCooldownCompleted()),
);
} on HttpException catch (e) {
emit(state.copyWith(status: AuthenticationStatus.failure, exception: e));
} catch (e) {
Expand Down Expand Up @@ -155,4 +170,16 @@ class AuthenticationBloc
_userAuthSubscription.cancel();
return super.close();
}

void _onAuthenticationCooldownCompleted(
AuthenticationCooldownCompleted event,
Emitter<AuthenticationState> emit,
) {
emit(
state.copyWith(
status: AuthenticationStatus.initial,
clearCooldownEndTime: true,
),
);
}
}
8 changes: 8 additions & 0 deletions lib/authentication/bloc/authentication_event.dart
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,11 @@ final class _AuthenticationUserChanged 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 @@ -39,6 +39,7 @@ class AuthenticationState extends Equatable {
this.user,
this.email,
this.exception,
this.cooldownEndTime,
});

/// The current status of the authentication process.
Expand All @@ -53,21 +54,28 @@ class AuthenticationState extends Equatable {
/// The exception that occurred, if any.
final HttpException? exception;

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

/// Creates a copy of the current [AuthenticationState] with updated values.
AuthenticationState copyWith({
AuthenticationStatus? status,
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,
);
}

@override
List<Object?> get props => [status, user, email, exception];
List<Object?> get props => [status, user, email, exception, 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_mobile_client_full_source_code/app/bloc/app_bloc.dart';
import 'package:flutter_news_app_mobile_client_full_source_code/app/config/config.dart';
import 'package:flutter_news_app_mobile_client_full_source_code/authentication/bloc/authentication_bloc.dart';
import 'package:flutter_news_app_mobile_client_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 @@ -130,10 +130,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 @@ -152,39 +154,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
148 changes: 103 additions & 45 deletions lib/authentication/view/request_code_page.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//
// ignore_for_file: lines_longer_than_80_chars

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_news_app_mobile_client_full_source_code/authentication/bloc/authentication_bloc.dart';
Expand Down Expand Up @@ -161,20 +163,58 @@ class _EmailLinkForm extends StatefulWidget {
class _EmailLinkFormState extends State<_EmailLinkForm> {
final _emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();
Timer? _cooldownTimer;
int _cooldownSeconds = 0;

@override
void initState() {
super.initState();
final authState = context.read<AuthenticationBloc>().state;
if (authState.cooldownEndTime != null &&
authState.cooldownEndTime!.isAfter(DateTime.now())) {
_startCooldownTimer(authState.cooldownEndTime!);
}
}

@override
void dispose() {
_emailController.dispose();
_cooldownTimer?.cancel();
super.dispose();
}

void _startCooldownTimer(DateTime endTime) {
final now = DateTime.now();
if (now.isBefore(endTime)) {
setState(() {
_cooldownSeconds = endTime.difference(now).inSeconds;
});
_cooldownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
final remaining = endTime.difference(DateTime.now()).inSeconds;
if (remaining > 0) {
setState(() {
_cooldownSeconds = remaining;
});
} else {
timer.cancel();
setState(() {
_cooldownSeconds = 0;
});
context
.read<AuthenticationBloc>()
.add(const AuthenticationCooldownCompleted());
}
});
}
}

void _submitForm() {
if (_formKey.currentState!.validate()) {
context.read<AuthenticationBloc>().add(
AuthenticationRequestSignInCodeRequested(
email: _emailController.text.trim(),
),
);
AuthenticationRequestSignInCodeRequested(
email: _emailController.text.trim(),
),
);
}
}

Expand All @@ -184,49 +224,67 @@ class _EmailLinkFormState extends State<_EmailLinkForm> {
final textTheme = Theme.of(context).textTheme;
final colorScheme = Theme.of(context).colorScheme;

return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: l10n.requestCodeEmailLabel,
hintText: l10n.requestCodeEmailHint,
// border: const OutlineInputBorder(),
return BlocListener<AuthenticationBloc, AuthenticationState>(
listenWhen: (previous, current) =>
previous.cooldownEndTime != current.cooldownEndTime,
listener: (context, state) {
if (state.cooldownEndTime != null &&
state.cooldownEndTime!.isAfter(DateTime.now())) {
_cooldownTimer?.cancel();
_startCooldownTimer(state.cooldownEndTime!);
}
},
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: _emailController,
decoration: InputDecoration(
labelText: l10n.requestCodeEmailLabel,
hintText: l10n.requestCodeEmailHint,
),
keyboardType: TextInputType.emailAddress,
autocorrect: false,
textInputAction: TextInputAction.done,
enabled: !widget.isLoading && _cooldownSeconds == 0,
validator: (value) {
if (value == null || value.isEmpty || !value.contains('@')) {
return l10n.accountLinkingEmailValidationError;
}
return null;
},
onFieldSubmitted:
widget.isLoading || _cooldownSeconds > 0 ? null : (_) => _submitForm(),
),
keyboardType: TextInputType.emailAddress,
autocorrect: false,
textInputAction: TextInputAction.done,
enabled: !widget.isLoading,
validator: (value) {
if (value == null || value.isEmpty || !value.contains('@')) {
return l10n.accountLinkingEmailValidationError;
}
return null;
},
onFieldSubmitted: (_) => _submitForm(),
),
const SizedBox(height: AppSpacing.lg),
ElevatedButton(
onPressed: widget.isLoading ? null : _submitForm,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.md),
textStyle: textTheme.labelLarge,
const SizedBox(height: AppSpacing.lg),
ElevatedButton(
onPressed:
widget.isLoading || _cooldownSeconds > 0 ? null : _submitForm,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: AppSpacing.md),
textStyle: textTheme.labelLarge,
),
child: widget.isLoading
? SizedBox(
height: AppSpacing.xl,
width: AppSpacing.xl,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.onPrimary,
),
)
: _cooldownSeconds > 0
? Text(
l10n.requestCodeResendButtonCooldown(
_cooldownSeconds,
),
)
: Text(l10n.requestCodeSendCodeButton),
),
child: widget.isLoading
? SizedBox(
height: AppSpacing.xl,
width: AppSpacing.xl,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.onPrimary,
),
)
: Text(l10n.requestCodeSendCodeButton),
),
],
],
),
),
);
}
Expand Down
Loading
Loading