The authentication system provides secure user registration and login using Firebase Authentication. It supports both email/password authentication and Google Sign-In integration, with automatic profile creation in Firestore.
The login flow authenticates users with their email and password credentials.Code Example:
lib/services/auth_service.dart
// Sign in with email and passwordFuture<User?> signInWithEmailAndPassword(String email, String password) async { try { UserCredential userCredential = await _auth.signInWithEmailAndPassword( email: email, password: password, ); return userCredential.user; } catch (e) { _logger.e('Error al iniciar sesión: $e'); return null; }}
Usage in LoginScreen:
lib/ui/screens/login_screen.dart
void _loginWithEmail() async { final email = _emailController.text.trim(); final password = _passwordController.text.trim(); final user = await _authService.signInWithEmailAndPassword(email, password); if (user != null) { if (!mounted) return; Navigator.pushReplacementNamed(context, '/home'); } else if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Inicio de sesión fallido. Verifica tus credenciales.') ), ); }}
Always validate user input before attempting authentication. The app includes email format validation and minimum password length requirements (8 characters).
Google Sign-In provides a streamlined authentication experience using the user’s Google account.Code Example:
lib/services/auth_service.dart
// Sign in with GoogleFuture<User?> signInWithGoogle() async { try { final GoogleSignInAccount? googleUser = await _googleSignIn.signIn(); if (googleUser == null) return null; final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final AuthCredential credential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); final UserCredential userCredential = await _auth.signInWithCredential(credential); User? user = userCredential.user; // Check if user profile exists in Firestore DocumentSnapshot userDoc = await _firestore.collection('users').doc(user!.uid).get(); if (!userDoc.exists) { // Create profile if it doesn't exist await saveUserProfile(user.uid, user.displayName ?? 'Sin nombre', '', null); } return user; } catch (e) { _logger.e('Error al iniciar sesión con Google: $e'); return null; }}
Google Sign-In automatically creates a user profile in Firestore if one doesn’t exist. The system checks for existing profiles to avoid duplicate entries.
Firebase Authentication provides built-in password reset functionality. Users receive a password reset email at their registered email address. Implementation details can be added using Firebase’s sendPasswordResetEmail() method.