> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Braian551/viax/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication & Login

> Login, password recovery, and security features for Viax users

## User Authentication

Viax provides secure authentication with email/password login, device tracking, and password recovery options.

## Login Process

### Standard Login

<Steps>
  <Step title="Enter Email">
    Provide the email address used during registration
  </Step>

  <Step title="Enter Password">
    Type your account password
  </Step>

  <Step title="Device Verification">
    System validates device and credentials
  </Step>

  <Step title="Access Granted">
    Redirected to appropriate home screen
  </Step>
</Steps>

### Login Screen Implementation

```dart theme={null}
// lib/src/features/auth/presentation/screens/login_screen.dart

Future<void> _login() async {
  if (_formKey.currentState!.validate()) {
    setState(() => _isLoading = true);
    
    try {
      String emailToUse = _emailController.text.trim();
      
      // Get device UUID for security
      final deviceUuid = await DeviceIdService.getOrCreateDeviceUuid();
      
      // Attempt login
      final resp = await UserService.login(
        email: emailToUse,
        password: _passwordController.text,
        deviceUuid: deviceUuid,
      );
      
      if (resp['success'] == true) {
        // Save session
        final user = resp['data']?['user'];
        await UserService.saveSession(user);
        
        // Navigate based on user type
        final tipoUsuario = user?['tipo_usuario'] ?? 'cliente';
        _navigateToHome(tipoUsuario, user);
      }
    } catch (e) {
      _showError(e.toString());
    }
  }
}
```

<CodeGroup>
  ```dart Login Request theme={null}
  // Service call
  final response = await UserService.login(
    email: 'user@example.com',
    password: 'userPassword123',
    deviceUuid: 'device-uuid-string',
  );
  ```

  ```json Success Response theme={null}
  {
    "success": true,
    "message": "Login successful",
    "data": {
      "user": {
        "id": 123,
        "email": "user@example.com",
        "nombre": "John",
        "apellido": "Doe",
        "telefono": "3001234567",
        "tipo_usuario": "cliente",
        "foto_perfil": "profile_123.jpg",
        "calificacion": 4.8
      },
      "token": "eyJ0eXAiOiJKV1QiLCJhbGc..."
    }
  }
  ```

  ```json Error Response theme={null}
  {
    "success": false,
    "message": "Invalid credentials",
    "error_type": "invalid_password",
    "data": {
      "fail_attempts": 2,
      "too_many_attempts": false
    }
  }
  ```
</CodeGroup>

## User Type Routing

### Automatic Navigation

Viax supports multiple user types with automatic routing:

<Tabs>
  <Tab title="Cliente (User)">
    ### Regular User

    ```dart theme={null}
    // Navigate to user home
    Navigator.pushNamedAndRemoveUntil(
      context,
      RouteNames.home,
      (route) => false,
      arguments: {'email': email, 'user': user},
    );
    ```

    **Home Screen**: `/home` (user home screen)
  </Tab>

  <Tab title="Conductor (Driver)">
    ### Driver Account

    ```dart theme={null}
    // Navigate to driver home
    Navigator.pushNamedAndRemoveUntil(
      context,
      RouteNames.conductorHome,
      (route) => false,
      arguments: {'conductor_user': user},
    );
    ```

    **Home Screen**: `/conductor/home`
  </Tab>

  <Tab title="Empresa (Company)">
    ### Company Account

    ```dart theme={null}
    // Navigate to company home
    Navigator.pushNamedAndRemoveUntil(
      context,
      RouteNames.companyHome,
      (route) => false,
      arguments: {'user': user},
    );
    ```

    **Home Screen**: `/company/home`
  </Tab>

  <Tab title="Administrador (Admin)">
    ### Administrator

    ```dart theme={null}
    // Navigate to admin panel
    Navigator.pushNamedAndRemoveUntil(
      context,
      RouteNames.adminHome,
      (route) => false,
      arguments: {'admin_user': user},
    );
    ```

    **Home Screen**: `/admin/home`
  </Tab>
</Tabs>

## Password Recovery

### Forgot Password Flow

<Steps>
  <Step title="Request Reset">
    Click "Forgot Password?" on login screen
  </Step>

  <Step title="Enter Email">
    Provide registered email address
  </Step>

  <Step title="Verify Code">
    Enter 6-digit code sent to email
  </Step>

  <Step title="Set New Password">
    Create and confirm new password
  </Step>
</Steps>

### Implementation

```dart theme={null}
// lib/src/features/auth/presentation/screens/forgot_password_screen.dart

Future<void> _requestPasswordReset() async {
  final email = _emailController.text.trim();
  
  try {
    final response = await UserService.requestPasswordReset(
      email: email,
    );
    
    if (response['success']) {
      // Navigate to verification screen
      Navigator.pushNamed(
        context,
        RouteNames.passwordRecoveryVerification,
        arguments: {'email': email},
      );
    }
  } catch (e) {
    showError(e.toString());
  }
}
```

### Verification & Reset

<CodeGroup>
  ```dart Verify Code theme={null}
  // password_recovery_verification_screen.dart

  final response = await UserService.verifyResetCode(
    email: email,
    code: verificationCode,
  );

  if (response['success']) {
    // Navigate to set new password screen
    Navigator.pushNamed(
      context,
      RouteNames.setNewPasswordAfterVerification,
      arguments: {'email': email, 'code': verificationCode},
    );
  }
  ```

  ```dart Set New Password theme={null}
  // set_new_password_after_verification_screen.dart

  final response = await UserService.resetPassword(
    email: email,
    code: verificationCode,
    newPassword: newPassword,
  );

  if (response['success']) {
    // Redirect to login
    Navigator.pushNamedAndRemoveUntil(
      context,
      RouteNames.login,
      (route) => false,
    );
  }
  ```
</CodeGroup>

## Device Security

### Device UUID Tracking

Viax tracks devices for security:

```dart theme={null}
// lib/src/global/services/device_id_service.dart

class DeviceIdService {
  static Future<String> getOrCreateDeviceUuid() async {
    final prefs = await SharedPreferences.getInstance();
    String? uuid = prefs.getString(_kDeviceUuidKey);
    
    if (uuid == null || uuid.isEmpty) {
      // Generate new UUID
      uuid = const Uuid().v4();
      await prefs.setString(_kDeviceUuidKey, uuid);
    }
    
    return uuid;
  }
}
```

<Info>
  **Why Device Tracking?**

  * Prevent unauthorized access
  * Detect suspicious login attempts
  * Enable multi-device management
  * Support device-specific features
</Info>

## Failed Login Protection

### Rate Limiting

```dart theme={null}
// Track failed attempts
int _localFailAttempts = 0;

if (message.contains('Contraseña')) {
  _localFailAttempts = failAttempts;
  
  if (tooMany || _localFailAttempts >= 5) {
    // Require email verification for security
    Navigator.pushReplacementNamed(
      context,
      RouteNames.emailVerification,
      arguments: {
        'email': emailToUse,
        'userName': emailToUse.split('@')[0],
        'deviceUuid': deviceUuid,
      },
    );
  }
}
```

<Warning>
  **Account Protection**: After 5 failed login attempts, you'll need to verify your email before logging in again.
</Warning>

## Session Management

### Saving User Session

```dart theme={null}
// lib/src/global/services/auth/user_service.dart

static Future<void> saveSession(Map<String, dynamic> userData) async {
  final prefs = await SharedPreferences.getInstance();
  
  // Store user data
  await prefs.setInt('user_id', userData['id']);
  await prefs.setString('user_email', userData['email']);
  await prefs.setString('user_name', userData['nombre']);
  await prefs.setString('user_type', userData['tipo_usuario']);
  
  // Store full user object as JSON
  await prefs.setString('user_session', jsonEncode(userData));
}
```

### Retrieving Session

```dart theme={null}
static Future<Map<String, dynamic>?> getSavedSession() async {
  final prefs = await SharedPreferences.getInstance();
  final sessionString = prefs.getString('user_session');
  
  if (sessionString != null) {
    return jsonDecode(sessionString) as Map<String, dynamic>;
  }
  
  return null;
}
```

### Clearing Session (Logout)

```dart theme={null}
static Future<void> clearSession() async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.clear(); // Clear all stored data
}
```

## Auto-Login

### Persistent Sessions

```dart theme={null}
// Check for existing session on app start
@override
void initState() {
  super.initState();
  _checkExistingSession();
}

Future<void> _checkExistingSession() async {
  final session = await UserService.getSavedSession();
  
  if (session != null && session['email'] != null) {
    // User has active session - auto-navigate
    final userType = session['tipo_usuario'] ?? 'cliente';
    _navigateToHome(userType, session);
  } else {
    // No session - show login
    setState(() => _isLoading = false);
  }
}
```

## Security Best Practices

<AccordionGroup>
  <Accordion title="Password Security">
    * **Minimum Length**: 6 characters required
    * **Hashing**: Passwords hashed with bcrypt on backend
    * **Never Stored Plain**: Only hashed values in database
    * **HTTPS Only**: All auth requests over secure connection
  </Accordion>

  <Accordion title="Device Verification">
    * **Unique Device ID**: Generated per installation
    * **Device Tracking**: Monitor login locations
    * **Suspicious Activity**: Alert on unusual patterns
    * **Multi-Device Support**: Login from multiple devices
  </Accordion>

  <Accordion title="Session Security">
    * **Local Storage**: Encrypted SharedPreferences
    * **Auto-Logout**: After extended inactivity
    * **Secure Tokens**: JWT with expiration
    * **Refresh Tokens**: Background session renewal
  </Accordion>
</AccordionGroup>

## Common Issues

### Troubleshooting

<Tabs>
  <Tab title="Invalid Credentials">
    **Problem**: "Email or password incorrect"

    **Solutions**:

    1. Verify email is spelled correctly
    2. Check password (case-sensitive)
    3. Use "Forgot Password" if needed
    4. Ensure account was created successfully
  </Tab>

  <Tab title="Too Many Attempts">
    **Problem**: "Account temporarily locked"

    **Solutions**:

    1. Wait 15 minutes before retry
    2. Use email verification to unlock
    3. Request password reset
    4. Contact support if persistent
  </Tab>

  <Tab title="Network Error">
    **Problem**: "Unable to connect"

    **Solutions**:

    1. Check internet connection
    2. Try different network (WiFi/mobile)
    3. Disable VPN if active
    4. Retry after a few moments
  </Tab>
</Tabs>

## Next Steps

<CardGroup cols={2}>
  <Card title="Profile Management" icon="id-card" href="/users/profile-management">
    Update your account details
  </Card>

  <Card title="Book Your First Ride" icon="car" href="/users/booking-a-ride">
    Start using Viax
  </Card>
</CardGroup>
