62 lines
2.0 KiB
Dart
62 lines
2.0 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:finlytic_app/core/network/api_client.dart';
|
|
import 'package:finlytic_app/core/services/secure_storage_service.dart';
|
|
import 'package:finlytic_app/features/auth/repositories/auth_repository.dart';
|
|
import 'auth_event.dart';
|
|
import 'auth_state.dart';
|
|
|
|
export 'auth_event.dart';
|
|
export 'auth_state.dart';
|
|
|
|
class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
|
final AuthRepository repository;
|
|
|
|
AuthBloc({
|
|
required ApiClient apiClient,
|
|
required SecureStorageService storageService,
|
|
AuthRepository? repository,
|
|
}) : repository = repository ?? AuthRepository(apiClient: apiClient, storageService: storageService),
|
|
super(AuthInitial()) {
|
|
on<CheckAuthStatus>(_onCheckAuthStatus);
|
|
on<LoginRequested>(_onLoginRequested);
|
|
on<RegisterRequested>(_onRegisterRequested);
|
|
on<LogoutRequested>(_onLogoutRequested);
|
|
}
|
|
|
|
Future<void> _onCheckAuthStatus(CheckAuthStatus event, Emitter<AuthState> emit) async {
|
|
final user = await repository.checkAuthStatus();
|
|
if (user != null) {
|
|
emit(Authenticated(user));
|
|
} else {
|
|
emit(Unauthenticated());
|
|
}
|
|
}
|
|
|
|
Future<void> _onLoginRequested(LoginRequested event, Emitter<AuthState> emit) async {
|
|
emit(AuthLoading());
|
|
try {
|
|
final user = await repository.login(event.email, event.password);
|
|
emit(Authenticated(user));
|
|
} on RequiresPasswordChangeException catch (e) {
|
|
emit(AuthRequiresPasswordChange(e.userId));
|
|
} catch (e) {
|
|
emit(AuthFailure(e.toString()));
|
|
}
|
|
}
|
|
|
|
Future<void> _onRegisterRequested(RegisterRequested event, Emitter<AuthState> emit) async {
|
|
emit(AuthLoading());
|
|
try {
|
|
final user = await repository.register(event.email, event.password, event.fullName);
|
|
emit(Authenticated(user));
|
|
} catch (e) {
|
|
emit(AuthFailure(e.toString()));
|
|
}
|
|
}
|
|
|
|
Future<void> _onLogoutRequested(LogoutRequested event, Emitter<AuthState> emit) async {
|
|
await repository.logout();
|
|
emit(Unauthenticated());
|
|
}
|
|
}
|