153 lines
4.5 KiB
Dart
153 lines
4.5 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
|
|
class LoginController with ChangeNotifier {
|
|
// 1. Substituímos o FirebaseAuth pelo cliente do Supabase
|
|
final SupabaseClient _supabase = Supabase.instance.client;
|
|
|
|
final TextEditingController emailController = TextEditingController();
|
|
final TextEditingController passwordController = TextEditingController();
|
|
|
|
bool _isLoading = false;
|
|
bool _obscurePassword = true;
|
|
String? _emailError;
|
|
String? _passwordError;
|
|
|
|
bool get isLoading => _isLoading;
|
|
bool get obscurePassword => _obscurePassword;
|
|
String? get emailError => _emailError;
|
|
String? get passwordError => _passwordError;
|
|
|
|
void togglePasswordVisibility() {
|
|
_obscurePassword = !_obscurePassword;
|
|
notifyListeners();
|
|
}
|
|
|
|
// --- VALIDAÇÕES (Mantêm-se iguais) ---
|
|
String? validateEmail(String? value) {
|
|
if (value == null || value.isEmpty) return 'Por favor, insira o seu email';
|
|
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
|
|
if (!emailRegex.hasMatch(value)) return 'Por favor, insira um email válido';
|
|
return null;
|
|
}
|
|
|
|
String? validatePassword(String? value) {
|
|
if (value == null || value.isEmpty) return 'Por favor, insira a sua password';
|
|
if (value.length < 6) return 'A password deve ter pelo menos 6 caracteres';
|
|
return null;
|
|
}
|
|
|
|
// --- MÉTODO PARA ENTRAR (LOGIN) ---
|
|
Future<bool> login() async {
|
|
// Limpa erros anteriores
|
|
_emailError = null;
|
|
_passwordError = null;
|
|
|
|
// Valida localmente primeiro
|
|
String? emailValidation = validateEmail(emailController.text);
|
|
String? passValidation = validatePassword(passwordController.text);
|
|
|
|
if (emailValidation != null || passValidation != null) {
|
|
_emailError = emailValidation;
|
|
_passwordError = passValidation;
|
|
notifyListeners();
|
|
return false;
|
|
}
|
|
|
|
_isLoading = true;
|
|
notifyListeners();
|
|
|
|
try {
|
|
// 2. Chamada ao Supabase para Login
|
|
await _supabase.auth.signInWithPassword(
|
|
email: emailController.text.trim(),
|
|
password: passwordController.text.trim(),
|
|
);
|
|
|
|
_isLoading = false;
|
|
notifyListeners();
|
|
return true;
|
|
|
|
} on AuthException catch (e) {
|
|
// 3. Captura erros específicos do Supabase
|
|
_isLoading = false;
|
|
_handleSupabaseError(e);
|
|
notifyListeners();
|
|
return false;
|
|
} catch (e) {
|
|
_isLoading = false;
|
|
_emailError = 'Ocorreu um erro inesperado.';
|
|
notifyListeners();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// --- MÉTODO PARA CRIAR CONTA (SIGN UP) ---
|
|
Future<bool> signUp() async {
|
|
_emailError = null;
|
|
_passwordError = null;
|
|
|
|
String? emailValidation = validateEmail(emailController.text);
|
|
String? passValidation = validatePassword(passwordController.text);
|
|
|
|
if (emailValidation != null || passValidation != null) {
|
|
_emailError = emailValidation;
|
|
_passwordError = passValidation;
|
|
notifyListeners();
|
|
return false;
|
|
}
|
|
|
|
_isLoading = true;
|
|
notifyListeners();
|
|
|
|
try {
|
|
// 4. Chamada ao Supabase para Registo
|
|
await _supabase.auth.signUp(
|
|
email: emailController.text.trim(),
|
|
password: passwordController.text.trim(),
|
|
);
|
|
|
|
_isLoading = false;
|
|
notifyListeners();
|
|
return true;
|
|
|
|
} on AuthException catch (e) {
|
|
_isLoading = false;
|
|
_handleSupabaseError(e);
|
|
notifyListeners();
|
|
return false;
|
|
} catch (e) {
|
|
_isLoading = false;
|
|
_emailError = 'Ocorreu um erro inesperado.';
|
|
notifyListeners();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// --- TRATAMENTO DE ERROS SUPABASE ---
|
|
void _handleSupabaseError(AuthException error) {
|
|
// O Supabase retorna mensagens em inglês, vamos traduzir as mais comuns.
|
|
// O 'message' contém o texto do erro.
|
|
final msg = error.message.toLowerCase();
|
|
|
|
if (msg.contains('invalid login credentials')) {
|
|
_emailError = 'E-mail ou password incorretos.';
|
|
} else if (msg.contains('user already registered') || msg.contains('already exists')) {
|
|
_emailError = 'Este e-mail já está registado.';
|
|
} else if (msg.contains('password')) {
|
|
_passwordError = 'A password deve ter pelo menos 6 caracteres.';
|
|
} else if (msg.contains('email')) {
|
|
_emailError = 'Formato de e-mail inválido.';
|
|
} else {
|
|
// Fallback para mostrar a mensagem original se não conhecermos o erro
|
|
_emailError = error.message;
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
emailController.dispose();
|
|
passwordController.dispose();
|
|
super.dispose();
|
|
}
|
|
} |