🔐 Sistema de Registro y Login
Flutter app connected to a PHP API and FacturaScripts Plugin
Download Complete Examples📱 What is this system?
Complete Authentication System
This Flutter application demonstrates how to build a complete registration and login system that integrates with:
- Simple PHP Backend: API REST for basic authentication
- Plugin FacturaScripts: Extension that automatically creates API Keys
- App Flutter: Mobile interface with registration, login and home screens
- State Management: Session control and authentication tokens
System Architecture
- 📱 Frontend Flutter: Authentication screens and services
- 🔌 API PHP: Example backend with JWT/tokens
- 🏢 Plugin FacturaScripts: Extension of the Cliente model to generate API Keys
- 🔗 Connection: The client's password is used as the API Key in FacturaScripts
📁 Project Structure
RegistroLogin/
├── lib/ # <?php echo t('Aplicación Flutter'); ?>
│ ├── config/
│ │ └── api_config.dart # <?php echo t('Configuración de endpoints'); ?>
│ ├── models/
│ │ └── user.dart # <?php echo t('Modelo de Usuario'); ?>
│ ├── services/
│ │ └── auth_service.dart # <?php echo t('Servicio de autenticación'); ?>
│ ├── screens/
│ │ ├── register_screen.dart # <?php echo t('Pantalla de registro'); ?>
│ │ ├── login_screen.dart # <?php echo t('Pantalla de login'); ?>
│ │ └── home_screen.dart # <?php echo t('Pantalla principal'); ?>
│ ├── backend_ejemplo/
│ │ └── api.php # <?php echo t('Backend PHP de ejemplo'); ?>
│ └── main.dart # <?php echo t('Punto de entrada'); ?>
│
└── ReparacionesRK/ # Plugin FacturaScripts
├── facturascripts.ini # <?php echo t('Configuración del plugin'); ?>
├── Init.php # <?php echo t('Inicialización'); ?>
├── Extension/
│ └── Model/
│ └── Cliente.php # <?php echo t('Extensión del modelo Cliente'); ?>
├── Model/
├── Controller/
└── XMLView/
🔍 Explore the Components
Click any component to see its complete code:
Entry Point
main.dart
Ver código →API Configuration
api_config.dart
Ver código →Model User
user.dart
Ver código →Auth Service
auth_service.dart
Ver código →Login Screen
login_screen.dart
Ver código →Registration Screen
register_screen.dart
Ver código →Home Screen
home_screen.dart
Ver código →PHP Backend
api.php
Ver código →Cliente Extension
Cliente.php
Ver código →Init Plugin
Init.php
Ver código →Config Plugin
facturascripts.ini
Ver código →🔄 How It Works
1️⃣ User Registration
- User fills out the form in
RegisterScreen AuthService.register()sends the data to the API- PHP backend validates and creates the user with a token
- User is redirected to the login screen
2️⃣ User Login
- User enters email and password in
LoginScreen AuthService.login()authenticates with the API- Backend verifies credentials and returns a token
- Token is saved and the user accesses
HomeScreen
3️⃣ Integration with FacturaScripts
- In FacturaScripts, a Client is created/edited
- Field
passwordfield is filled in - The
Cliente.phpextension intercepts the save - An
ApiKeyis automatically created using:- dni: CIF/NIF of the client
- description: Client's email
- apikey: Client's password
- The Flutter app can use that password to authenticate with FacturaScripts
🔧 Detailed Technical Explanation
🎯 Service Layer Pattern
AuthService centralizes all the authentication logic:
- Abstracts HTTP requests
- Handles errors centrally
- Automatically serializes/deserializes JSON
- Returns typed
Userobjects
🔐 Token Management
The system uses Bearer tokens for authentication:
- Generated on the backend with
bin2hex(random_bytes(32)) - Sent in the
Authorization: Bearer {token}header - Validated on each protected request
- Stored in the app (SharedPreferences recommended)
🏗️ Model Extension
Plugin FacturaScripts extends the Cliente model:
saveInsert(): Runs when creating a clientsaveUpdate(): Runs when updating a client- Use
Closureto inject custom logic - Creates/updates
ApiKeyautomatically
🔗 How Flutter and FacturaScripts Connect
Crear Cliente en FacturaScripts
Admin añade cliente con email y password personalizado
Plugin Genera API Key
Extensión Cliente.php crea ApiKey automáticamente
apikey = password del cliente
Usuario Login en App
Usuario ingresa email y password en la app Flutter
App Accesses FacturaScripts
Flutter uses the password as a token in the header:
token: {password}
📋 Requirements and Dependencies
Flutter (pubspec.yaml)
dependencies:
flutter:
sdk: flutter
http: ^1.1.0 # <?php echo t('Peticiones HTTP'); ?>
provider: ^6.0.0 # <?php echo t('Gestión de estado (opcional)'); ?>
shared_preferences: ^2.0.0 # <?php echo t('Persistencia de token'); ?>
PHP Backend
- PHP 7.4 or higher
- JSON extension enabled
- OpenSSL extension for tokens
- Configured CORS headers
FacturaScripts
- FacturaScripts 2024 or higher
- Plugin installed at
/Plugins/ReparacionesRK/ - Custom field
passwordin the Cliente model - API enabled in configuration
✅ Best Practices Implemented
🛡️ Security
- Hashed passwords with
password_hash() - Secure random tokens
- Validation on client and server
- Configured CORS headers
- No passwords in responses
🎨 UX/UI
- Loading indicators (
_isLoading) - Real-time form validation
- SnackBars for user feedback
- Smooth navigation between screens
- TextFormField with validators
🏗️ Architecture
- Layer separation (UI, Service, Model)
- Centralized configuration
- Reusable and maintainable code
- Consistent error handling
- Informative logs in backend and plugin
🔧 Common Troubleshooting
❌ CORS Error
Symptom: "CORS policy blocked"
Solution:
- Check headers in
api.php - Make sure
Access-Control-Allow-Origin: *is present - Handle OPTIONS (preflight) requests
🔐 API Key isn't created
Symptom: Client saved but without an ApiKey
Solution:
- Verify that the
passwordfield is not empty - Check FacturaScripts logs
- Confirm that
Init.phploads the extension - Check DB write permissions
📱 App doesn't connect
Symptom: "Connection refused"
Solution:
- On a physical device, use a real IP (not localhost)
- Verify the server is running
- Check
baseUrlinapi_config.dart - Use
http://10.0.2.2:8000on an Android emulator
🔑 Token invalid
Symptom: "Error 401: Token invalid"
Solution:
- Verify format:
Bearer {token} - Confirm the token is saved correctly
- Check that there are no extra spaces
- Validate that the token exists in users.json
🚀 Suggested Improvements
1. Session Persistence
Implement SharedPreferences to keep the user logged in:
- Save token on login
- Verify token on app start
- Clear token on logout
- Auto-login if the token is valid
2. State Management
Use Provider, Riverpod or BLoC to manage global state:
- AuthProvider with user state
- Loading states centralized
- Conditional navigation based on state
- Automatic data refresh
3. Real Database
Migrate from JSON to MySQL/PostgreSQL:
- Relational tables for users
- Indexes for fast searches
- ACID transactions
- Automated backups
4. Advanced Security
- JWT with automatic expiration
- Refresh tokens
- Rate limiting in the API
- Email validation with a code
- 2FA (two-factor authentication)