games_app/prediqo_mobile/lib/features/auth/bloc/auth_bloc.dart

181 lines
6.1 KiB
Dart

/// Authentication BLoC layer: login, registration, session check, logout, and 2FA setup.
library;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import '../../../core/errors/app_exception.dart';
import '../../../domain/repositories/repositories.dart';
part 'auth_event.dart';
part 'auth_state.dart';
/// Manages authentication state and coordinates with [AuthRepository].
class AuthBloc extends Bloc<AuthEvent, AuthState> {
/// Creates an [AuthBloc] backed by [authRepo].
AuthBloc(this._authRepo) : super(const AuthState.initial()) {
on<AuthCheckRequested>(_onCheckRequested);
on<AuthLoginRequested>(_onLogin);
on<AuthRegisterRequested>(_onRegister);
on<AuthResendVerificationRequested>(_onResendVerification);
on<AuthClearFeedback>(_onClearFeedback);
on<AuthLogoutRequested>(_onLogout);
on<AuthSessionExpired>(_onSessionExpired);
on<Auth2FASetupRequested>(_on2FASetup);
on<Auth2FAEnableRequested>(_on2FAEnable);
on<Auth2FADisableRequested>(_on2FADisable);
}
final AuthRepository _authRepo;
/// Restores session from stored credentials; emits [AuthStatus.authenticated] or [AuthStatus.unauthenticated].
Future<void> _onCheckRequested(AuthCheckRequested event, Emitter<AuthState> emit) async {
emit(const AuthState.loading());
try {
final loggedIn = await _authRepo.isLoggedIn();
if (loggedIn) {
final stored = await _authRepo.getStoredUser();
emit(AuthState.authenticated(userId: stored.userId, role: stored.role));
} else {
emit(const AuthState.unauthenticated());
}
} catch (_) {
emit(const AuthState.unauthenticated());
}
}
/// Signs in with email, password, and optional TOTP; navigates via listener on success.
Future<void> _onLogin(AuthLoginRequested event, Emitter<AuthState> emit) async {
emit(const AuthState.loading());
try {
final result = await _authRepo.login(
event.email,
event.password,
totpCode: event.totpCode,
captchaToken: event.captchaToken,
);
emit(AuthState.authenticated(userId: result.userId, role: result.role));
} catch (e) {
emit(_mapError(e));
}
}
/// Registers a new account; emits [AuthStatus.registered] on success.
Future<void> _onRegister(AuthRegisterRequested event, Emitter<AuthState> emit) async {
emit(const AuthState.loading());
try {
final result = await _authRepo.register(RegisterRequest(
fullName: event.fullName,
email: event.email,
password: event.password,
countryOfResidence: event.countryOfResidence,
gender: event.gender,
phone: event.phone,
nationality: event.nationality,
referralCode: event.referralCode,
));
emit(AuthState.registered(
message: result.message,
emailVerificationRequired: result.emailVerificationRequired,
));
} catch (e) {
emit(_mapError(e));
}
}
Future<void> _onResendVerification(
AuthResendVerificationRequested event,
Emitter<AuthState> emit,
) async {
emit(const AuthState.loading());
try {
await _authRepo.resendVerificationEmail(event.email);
emit(const AuthState.verificationResent(
message: 'Verification email sent. Check your inbox.',
));
} catch (e) {
emit(_mapError(e));
}
}
void _onClearFeedback(AuthClearFeedback event, Emitter<AuthState> emit) {
if (state.isSignedIn) {
emit(AuthState.authenticated(userId: state.userId, role: state.role));
return;
}
// Keep guest on auth forms; only clear one-shot error/success feedback.
emit(const AuthState.unauthenticated());
}
/// Clears stored session and emits [AuthStatus.unauthenticated].
Future<void> _onLogout(AuthLogoutRequested event, Emitter<AuthState> emit) async {
await _authRepo.logout();
emit(const AuthState.unauthenticated());
}
/// Local session wipe after failed token refresh (tokens already cleared by ApiClient).
Future<void> _onSessionExpired(AuthSessionExpired event, Emitter<AuthState> emit) async {
try {
await _authRepo.logout();
} catch (_) {}
emit(const AuthState.unauthenticated());
}
/// Fetches TOTP setup data (QR URL) from the API for enrollment.
/// Preserves the signed-in session on both success and failure.
Future<void> _on2FASetup(Auth2FASetupRequested event, Emitter<AuthState> emit) async {
final userId = state.userId;
final role = state.role;
try {
final data = await _authRepo.setup2FA(
password: event.password,
totpCode: event.totpCode,
);
emit(AuthState.totpSetup(data, userId: userId, role: role));
} catch (e) {
emit(_mapError(e, userId: userId, role: role));
}
}
/// Verifies and enables 2FA with the user-supplied TOTP code.
/// Preserves the signed-in session on both success and failure.
Future<void> _on2FAEnable(Auth2FAEnableRequested event, Emitter<AuthState> emit) async {
final userId = state.userId;
final role = state.role;
try {
final recoveryCodes = await _authRepo.enable2FA(event.code);
emit(AuthState.authenticated(
userId: userId,
role: role,
recoveryCodes: recoveryCodes,
));
} catch (e) {
emit(_mapError(e, userId: userId, role: role));
}
}
/// Disables 2FA after password + TOTP (or recovery code) verification.
Future<void> _on2FADisable(Auth2FADisableRequested event, Emitter<AuthState> emit) async {
final userId = state.userId;
final role = state.role;
try {
await _authRepo.disable2FA(password: event.password, code: event.code);
emit(AuthState.authenticated(userId: userId, role: role));
} catch (e) {
emit(_mapError(e, userId: userId, role: role));
}
}
AuthState _mapError(Object e, {String? userId, String? role}) {
if (e is AppException) {
return AuthState.error(
e.message,
userId: userId,
role: role,
errorCode: e.code,
captcha: e.captcha,
);
}
return AuthState.error(e.toString(), userId: userId, role: role);
}
}