# User Login API Documentation

Base URL: `https://api.alldigtalseva.com`

---

## User Login

Authenticate user with email and password to receive an access token.

**Endpoint:** `POST /api/user/login`

**Request Headers:**
```
Content-Type: application/json
```

**Request Body:**
```json
{
    "email": "user@example.com",
    "password": "yourpassword123"
}
```

**Parameters:**
- `email` (required, string, email): User's email address
- `password` (required, string): User's password (minimum 6 characters)

**Success Response (200):**
```json
{
    "success": true,
    "message": "Login successful",
    "data": {
        "id": 1,
        "email": "user@example.com",
        "phone_number": "1234567890",
        "user_type": "user",
        "wallet_balance": "100.50",
        "token": "2|abcdefghijklmnopqrstuvwxyz1234567890"
    }
}
```

**Error Response (401) - Invalid Credentials:**
```json
{
    "success": false,
    "message": "Invalid credentials"
}
```

**Error Response (403) - User Not Verified:**
```json
{
    "success": false,
    "message": "User account is not verified. Please complete signup first."
}
```

**Error Response (422) - Validation Error:**
```json
{
    "success": false,
    "message": "Validation error",
    "errors": {
        "email": ["The email field is required."],
        "password": ["The password field is required."]
    }
}
```

**cURL Example:**
```bash
curl -X POST https://api.alldigtalseva.com/api/user/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "user@example.com",
    "password": "yourpassword123"
  }'
```

**JavaScript/Fetch Example:**
```javascript
fetch('https://api.alldigtalseva.com/api/user/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    email: 'user@example.com',
    password: 'yourpassword123'
  })
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('Login successful!');
    console.log('Token:', data.data.token);
    console.log('User ID:', data.data.id);
    console.log('Wallet Balance:', data.data.wallet_balance);
    
    // Store token for future API calls
    localStorage.setItem('auth_token', data.data.token);
  } else {
    console.error('Login failed:', data.message);
  }
})
.catch((error) => {
  console.error('Error:', error);
});
```

**PHP Example:**
```php
<?php
$url = 'https://api.alldigtalseva.com/api/user/login';
$data = [
    'email' => 'user@example.com',
    'password' => 'yourpassword123'
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$result = json_decode($response, true);

if ($result['success']) {
    echo "Login successful!\n";
    echo "Token: " . $result['data']['token'] . "\n";
    echo "User ID: " . $result['data']['id'] . "\n";
    echo "Wallet Balance: " . $result['data']['wallet_balance'] . "\n";
    
    // Store token for future API calls
    $token = $result['data']['token'];
} else {
    echo "Login failed: " . $result['message'] . "\n";
}
?>
```

**Python Example:**
```python
import requests
import json

url = "https://api.alldigtalseva.com/api/user/login"
payload = {
    "email": "user@example.com",
    "password": "yourpassword123"
}
headers = {
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)
result = response.json()

if result['success']:
    print("Login successful!")
    print("Token:", result['data']['token'])
    print("User ID:", result['data']['id'])
    print("Wallet Balance:", result['data']['wallet_balance'])
    
    # Store token for future API calls
    token = result['data']['token']
else:
    print("Login failed:", result['message'])
```

**React/Next.js Example:**
```javascript
const loginUser = async (email, password) => {
  try {
    const response = await fetch('https://api.alldigtalseva.com/api/user/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email,
        password
      })
    });

    const data = await response.json();

    if (data.success) {
      // Store token in localStorage or state management
      localStorage.setItem('auth_token', data.data.token);
      localStorage.setItem('user_data', JSON.stringify(data.data));
      
      return {
        success: true,
        token: data.data.token,
        user: data.data
      };
    } else {
      return {
        success: false,
        message: data.message
      };
    }
  } catch (error) {
    return {
      success: false,
      message: 'Network error. Please try again.'
    };
  }
};

// Usage
loginUser('user@example.com', 'yourpassword123')
  .then(result => {
    if (result.success) {
      console.log('Logged in!', result.user);
      // Redirect to dashboard or update UI
    } else {
      console.error('Login failed:', result.message);
    }
  });
```

---

## Using the Authentication Token

After successful login, you'll receive an authentication token. Use this token in subsequent API requests by including it in the Authorization header.

**Header Format:**
```
Authorization: Bearer {token}
```

**Example - Get User Profile:**
```bash
curl -X GET https://api.alldigtalseva.com/api/user \
  -H "Authorization: Bearer 2|abcdefghijklmnopqrstuvwxyz1234567890"
```

**Example - JavaScript with Token:**
```javascript
const token = localStorage.getItem('auth_token');

fetch('https://api.alldigtalseva.com/api/user', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  console.log('User data:', data);
});
```

---

## Important Notes

1. **Password Storage**: 
   - Password is stored in plain text (not encrypted) as per requirements
   - Password must be at least 6 characters long

2. **User Verification**: 
   - User must be verified (completed signup with OTP) before login
   - Unverified users will receive a 403 error

3. **Token Usage**:
   - Token is valid until revoked or expired
   - Store token securely (localStorage, secure cookie, or state management)
   - Include token in Authorization header for protected endpoints

4. **Account Types**:
   - `"user"` - Regular user
   - `"distributor"` - Distributor user

5. **Wallet Balance**:
   - Current wallet balance is returned in login response
   - Balance is in decimal format with 2 decimal places

6. **Error Handling**:
   - Always check the `success` field in response
   - Handle 401 (Invalid credentials) and 403 (Not verified) errors appropriately
   - Display user-friendly error messages

---

## Response Codes

| Status Code | Description |
|------------|-------------|
| 200 | Success - Login successful, token returned |
| 401 | Unauthorized - Invalid email or password |
| 403 | Forbidden - User account not verified |
| 422 | Validation Error - Invalid input data |
| 500 | Server Error - Internal server error |

---

## Complete Login Flow

1. **User signs up** → `POST /api/user/signup`
   - Provides email and phone number
   - Receives OTP via SMS

2. **User verifies OTP** → `POST /api/user/verify-otp`
   - Provides email, OTP, and password
   - Account is verified and password is set

3. **User logs in** → `POST /api/user/login` (This endpoint)
   - Provides email and password
   - Receives authentication token

4. **User makes authenticated requests** → Include token in headers
   - Use token for protected endpoints
   - Token format: `Authorization: Bearer {token}`

---

## Security Best Practices

1. **Never expose tokens** in client-side code or URLs
2. **Use HTTPS** for all API requests
3. **Store tokens securely** (avoid localStorage for sensitive apps, use httpOnly cookies)
4. **Implement token refresh** if needed for long sessions
5. **Logout functionality** should revoke tokens on server side

---

**Last Updated:** December 4, 2025

