> ## 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.

# Login

> Authenticate a user and create a session

## Endpoint

```
POST /auth/login.php
```

Authenticate a user with email and password credentials.

## Headers

<ParamField header="Content-Type" type="string" required>
  Must be `application/json`
</ParamField>

<ParamField header="Accept" type="string" required>
  Must be `application/json`
</ParamField>

## Request Body

<ParamField body="email" type="string" required>
  User's email address
</ParamField>

<ParamField body="password" type="string" required>
  User's password
</ParamField>

## Response

<ResponseField name="success" type="boolean" required>
  Indicates if login was successful
</ResponseField>

<ResponseField name="message" type="string">
  Success or error message
</ResponseField>

<ResponseField name="user" type="object">
  Authenticated user object with complete profile

  <Expandable title="user object">
    <ResponseField name="id" type="integer">
      Unique user identifier
    </ResponseField>

    <ResponseField name="uuid" type="string">
      Universally unique identifier
    </ResponseField>

    <ResponseField name="nombre" type="string">
      User's first name
    </ResponseField>

    <ResponseField name="apellido" type="string">
      User's last name
    </ResponseField>

    <ResponseField name="email" type="string">
      User's email address
    </ResponseField>

    <ResponseField name="telefono" type="string">
      User's phone number
    </ResponseField>

    <ResponseField name="tipo_usuario" type="string">
      User type: `pasajero`, `conductor`, `admin`, or `empresa`
    </ResponseField>

    <ResponseField name="calificacion" type="number">
      Average user rating (0-5)
    </ResponseField>

    <ResponseField name="creado_en" type="string">
      Account creation timestamp (ISO 8601)
    </ResponseField>

    <ResponseField name="location" type="object">
      User's primary location
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="token" type="string" nullable>
  Authentication token (currently null, reserved for future use)
</ResponseField>

<ResponseField name="token_expires_at" type="string" nullable>
  Token expiration timestamp (currently null)
</ResponseField>

## Request Example

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://76.13.114.194/auth/login.php \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -d '{
      "email": "carlos.rodriguez@example.com",
      "password": "SecurePass123!"
    }'
  ```

  ```dart Dart theme={null}
  import 'package:http/http.dart' as http;
  import 'dart:convert';

  final response = await http.post(
    Uri.parse('https://76.13.114.194/auth/login.php'),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
    body: jsonEncode({
      'email': 'carlos.rodriguez@example.com',
      'password': 'SecurePass123!',
    }),
  );

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    if (data['success'] == true) {
      // Store user data
      final userId = data['user']['id'];
      // Navigate to home screen
    }
  }
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://76.13.114.194/auth/login.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
    body: JSON.stringify({
      email: 'carlos.rodriguez@example.com',
      password: 'SecurePass123!',
    }),
  });

  const data = await response.json();
  if (data.success) {
    // Store user session
    localStorage.setItem('user', JSON.stringify(data.user));
  }
  ```

  ```php PHP theme={null}
  <?php
  $ch = curl_init('https://76.13.114.194/auth/login.php');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Content-Type: application/json',
      'Accept: application/json',
  ]);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
      'email' => 'carlos.rodriguez@example.com',
      'password' => 'SecurePass123!',
  ]));

  $response = curl_exec($ch);
  $data = json_decode($response, true);

  if ($data['success']) {
      $_SESSION['user_id'] = $data['user']['id'];
  }
  ?>
  ```
</CodeGroup>

## Response Example

<CodeGroup>
  ```json Success (200) theme={null}
  {
    "success": true,
    "message": "Login exitoso",
    "user": {
      "id": 456,
      "uuid": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
      "nombre": "Carlos",
      "apellido": "Rodríguez",
      "email": "carlos.rodriguez@example.com",
      "telefono": "+573001234567",
      "tipo_usuario": "pasajero",
      "calificacion": 4.8,
      "creado_en": "2024-01-15T10:30:00.000Z",
      "actualizado_en": "2024-03-15T14:30:00.000Z",
      "location": {
        "id": 89,
        "usuario_id": 456,
        "direccion": "Carrera 15 #85-30",
        "latitud": 4.6814,
        "longitud": -74.0479,
        "ciudad": "Bogotá",
        "departamento": "Cundinamarca",
        "pais": "Colombia",
        "es_principal": true
      }
    },
    "token": null,
    "token_expires_at": null
  }
  ```

  ```json Invalid Credentials (401) theme={null}
  {
    "success": false,
    "message": "Email o contraseña incorrectos"
  }
  ```

  ```json User Not Found (404) theme={null}
  {
    "success": false,
    "message": "Usuario no encontrado"
  }
  ```

  ```json Account Inactive (403) theme={null}
  {
    "success": false,
    "message": "Cuenta inactiva o suspendida"
  }
  ```
</CodeGroup>

## Error Responses

<ResponseField name="400" type="Bad Request">
  Missing required fields or invalid request format
</ResponseField>

<ResponseField name="401" type="Unauthorized">
  Invalid email or password combination
</ResponseField>

<ResponseField name="403" type="Forbidden">
  User account is inactive or suspended
</ResponseField>

<ResponseField name="404" type="Not Found">
  User with provided email does not exist
</ResponseField>

<ResponseField name="500" type="Internal Server Error">
  Server error during authentication
</ResponseField>

## Session Management

After successful login, store the user data securely:

<CodeGroup>
  ```dart Flutter theme={null}
  import 'package:shared_preferences/shared_preferences.dart';

  // Store user session
  final prefs = await SharedPreferences.getInstance();
  await prefs.setInt('user_id', userData['id']);
  await prefs.setString('user_email', userData['email']);
  await prefs.setString('user_type', userData['tipo_usuario']);

  // Retrieve user session
  final userId = prefs.getInt('user_id');
  final userEmail = prefs.getString('user_email');
  ```

  ```javascript Web theme={null}
  // Store in localStorage
  localStorage.setItem('userId', data.user.id);
  localStorage.setItem('userEmail', data.user.email);

  // Or use sessionStorage for session-only storage
  sessionStorage.setItem('user', JSON.stringify(data.user));

  // Retrieve
  const userId = localStorage.getItem('userId');
  const user = JSON.parse(sessionStorage.getItem('user'));
  ```
</CodeGroup>

<Warning>
  Never store passwords locally. Only store the user ID and non-sensitive information.
</Warning>

## User Types

The `tipo_usuario` field indicates the user's role:

* **pasajero** - Regular passenger who can book rides
* **conductor** - Driver who can accept and complete trips
* **admin** - Administrator with access to admin endpoints
* **empresa** - Company/fleet manager

Use this field to determine which features to show in your application.

## See Also

* [Register](/api/auth/register) - Create a new user account
* [User Profile](/api/users/profile) - Fetch user profile
* [Check User Exists](/api/auth/verify-email) - Verify email before login
