Files
social-app/apps/lib/features/auth/presentation/bloc/auth_bloc.dart
T

81 lines
2.2 KiB
Dart
Raw Normal View History

import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/repositories/auth_repository.dart';
import 'auth_event.dart';
import 'auth_state.dart';
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final AuthRepository _repository;
AuthBloc(this._repository) : super(AuthInitial()) {
on<AuthStarted>(_onStarted);
on<AuthLoggedIn>(_onLoggedIn);
on<AuthLoggedOut>(_onLoggedOut);
on<AuthSessionInvalidated>(_onSessionInvalidated);
}
Future<void> _onStarted(AuthStarted event, Emitter<AuthState> emit) async {
emit(AuthLoading());
try {
final refreshToken = await _repository.getRefreshToken();
if (refreshToken != null) {
final response = await _repository.refreshSession(refreshToken);
emit(
AuthAuthenticated(
user: AuthUser(id: response.user.id, phone: response.user.phone),
),
);
return;
}
emit(
const AuthUnauthenticated(reason: AuthUnauthenticatedReason.signedOut),
);
} catch (_) {
try {
await _repository.clearSessionLocalOnly();
} catch (_) {
// Keep state convergence even when storage cleanup fails.
} finally {
emit(
const AuthUnauthenticated(
reason: AuthUnauthenticatedReason.startupRecoveryFailed,
),
);
}
}
}
void _onLoggedIn(AuthLoggedIn event, Emitter<AuthState> emit) {
emit(AuthAuthenticated(user: event.user));
}
Future<void> _onLoggedOut(
AuthLoggedOut event,
Emitter<AuthState> emit,
) async {
try {
await _repository.deleteSession();
} catch (_) {
// Keep state convergence even when logout cleanup fails.
} finally {
emit(
const AuthUnauthenticated(reason: AuthUnauthenticatedReason.signedOut),
);
}
}
Future<void> _onSessionInvalidated(
AuthSessionInvalidated event,
Emitter<AuthState> emit,
) async {
try {
await _repository.clearSessionLocalOnly();
} catch (_) {
// Keep state convergence even when local cleanup fails.
} finally {
emit(
const AuthUnauthenticated(reason: AuthUnauthenticatedReason.expired),
);
}
}
}