60 lines
1.9 KiB
Dart
60 lines
1.9 KiB
Dart
|
|
import 'package:equatable/equatable.dart';
|
||
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||
|
|
import 'package:get_it/get_it.dart';
|
||
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
||
|
|
part 'auth_state.dart';
|
||
|
|
|
||
|
|
class AuthCubit extends Cubit<AuthState> {
|
||
|
|
final _supabase = GetIt.instance<SupabaseClient>();
|
||
|
|
|
||
|
|
AuthCubit() : super(const AuthState());
|
||
|
|
|
||
|
|
void toggleMode() {
|
||
|
|
emit(state.copyWith(isLoginMode: !state.isLoginMode));
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<void> submitAuth(String email, String password) async {
|
||
|
|
// Partiamo puliti: via vecchi messaggi ed errori
|
||
|
|
emit(state.copyWith(status: AuthStatus.loading));
|
||
|
|
|
||
|
|
try {
|
||
|
|
if (state.isLoginMode) {
|
||
|
|
// --- LOGICA LOGIN ---
|
||
|
|
await _supabase.auth.signInWithPassword(
|
||
|
|
email: email,
|
||
|
|
password: password,
|
||
|
|
);
|
||
|
|
// NESSUN EMIT DI SUCCESS!
|
||
|
|
// Supabase lancerà l'evento 'signedIn', il SessionCubit lo catturerà
|
||
|
|
// e il GoRouter ci cambierà pagina. Noi stiamo a guardare il caricamento.
|
||
|
|
} else {
|
||
|
|
// --- LOGICA SIGNUP ---
|
||
|
|
final AuthResponse res = await _supabase.auth.signUp(
|
||
|
|
email: email,
|
||
|
|
password: password,
|
||
|
|
);
|
||
|
|
|
||
|
|
// Se la sessione è null, significa che Supabase ha inviato l'email di conferma
|
||
|
|
if (res.session == null) {
|
||
|
|
emit(
|
||
|
|
state.copyWith(
|
||
|
|
status: AuthStatus.initial,
|
||
|
|
infoMessage: "Controlla la tua email per confermare l'account!",
|
||
|
|
),
|
||
|
|
);
|
||
|
|
}
|
||
|
|
// Se non è null, ha fatto il login automatico. Stessa cosa di sopra, ci pensa il SessionCubit.
|
||
|
|
}
|
||
|
|
} on AuthException catch (e) {
|
||
|
|
emit(state.copyWith(status: AuthStatus.failure, errorMessage: e.message));
|
||
|
|
} catch (e) {
|
||
|
|
emit(
|
||
|
|
state.copyWith(
|
||
|
|
status: AuthStatus.failure,
|
||
|
|
errorMessage: "Errore imprevisto: $e",
|
||
|
|
),
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|