59 lines
1.8 KiB
Dart
59 lines
1.8 KiB
Dart
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:equatable/equatable.dart';
|
|
import 'package:get_it/get_it.dart';
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
|
|
part 'auth_events.dart';
|
|
part 'auth_state.dart';
|
|
|
|
class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
|
final _supabase = GetIt.instance<SupabaseClient>();
|
|
|
|
AuthBloc()
|
|
: super(const AuthState(status: AuthStatus.initial, isLoginMode: true)) {
|
|
on<ToggleAuthMode>(
|
|
(event, emit) => emit(state.copyWith(isLoginMode: !state.isLoginMode)),
|
|
);
|
|
on<LoginRequested>((event, emit) async {
|
|
emit(state.copyWith(status: AuthStatus.loading));
|
|
try {
|
|
if (state.isLoginMode) {
|
|
// --- LOGICA LOGIN ---
|
|
await _supabase.auth.signInWithPassword(
|
|
email: event.email,
|
|
password: event.password,
|
|
);
|
|
// Non serve emettere success qui, ci pensa il SessionBloc!
|
|
} else {
|
|
// --- LOGICA SIGNUP ---
|
|
await _supabase.auth.signUp(
|
|
email: event.email,
|
|
password: event.password,
|
|
);
|
|
|
|
// Nota: Se Supabase richiede conferma email, l'utente non sarà
|
|
// loggato subito. Gestiamolo con un messaggio.
|
|
emit(
|
|
state.copyWith(
|
|
status: AuthStatus.success,
|
|
error: "Controlla la tua email per confermare l'account!",
|
|
),
|
|
);
|
|
}
|
|
} on AuthException catch (e) {
|
|
emit(state.copyWith(status: AuthStatus.failure, error: e.message));
|
|
} catch (e) {
|
|
emit(
|
|
state.copyWith(
|
|
status: AuthStatus.failure,
|
|
error: "Errore imprevisto: $e",
|
|
),
|
|
);
|
|
}
|
|
});
|
|
on<LogoutRequested>((event, emit) async {
|
|
await _supabase.auth.signOut();
|
|
});
|
|
}
|
|
}
|