feat(apps): add AuthBloc for global auth state

This commit is contained in:
qzl
2026-02-25 14:59:20 +08:00
parent 3be03d8c74
commit 9b51c8b293
4 changed files with 192 additions and 0 deletions
@@ -0,0 +1,45 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/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);
}
Future<void> _onStarted(AuthStarted event, Emitter<AuthState> emit) async {
emit(AuthLoading());
final refreshToken = await _repository.getRefreshToken();
if (refreshToken != null) {
try {
final response = await _repository.refresh(refreshToken);
emit(
AuthAuthenticated(
user: AuthUser(id: response.user.id, email: response.user.email),
),
);
return;
} catch (_) {
await _repository.logout();
}
}
emit(AuthUnauthenticated());
}
void _onLoggedIn(AuthLoggedIn event, Emitter<AuthState> emit) {
emit(AuthAuthenticated(user: event.user));
}
Future<void> _onLoggedOut(
AuthLoggedOut event,
Emitter<AuthState> emit,
) async {
await _repository.logout();
emit(AuthUnauthenticated());
}
}