# Mobile App Authentication Implementation

## Overview
This implementation provides token-based authentication for iOS (and Android) mobile apps using Laravel Sanctum personal access tokens. This solves the issue where session cookies get deleted in iOS WebView, preventing long-term authentication.

## Key Features
- **90-day token expiration** for mobile apps
- **Automatic detection** of mobile app requests
- **Comprehensive logging** for debugging session/token issues
- **Dual authentication support**: Web uses sessions, mobile uses tokens
- **Seamless integration** with existing web authentication

## Architecture

### 1. Token-Based Authentication
- Mobile apps authenticate via `/api/mobile/login` endpoint
- Returns a personal access token with 90-day expiration
- Token is stored securely in the mobile app
- Token is sent in `Authorization: Bearer {token}` header on all requests

### 2. Middleware Chain
The authentication flow works as follows:
1. `SetPlatformSessionLifetime` - Sets session lifetime based on platform
2. `StartSession` - Starts session (for web)
3. `AuthenticateMobileApp` - Detects mobile apps and authenticates via token
4. Other middleware continues normally

### 3. Detection Methods
Mobile app requests are detected by:
- `X-Platform: mobile-app` header (most reliable)
- `Authorization: Bearer {token}` header
- User agent patterns (Capacitor, WKWebView, etc.)

## API Endpoints

### Login
```
POST /api/mobile/login
Content-Type: application/json

{
    "email": "user@example.com",
    "password": "password"
}
```

**Response:**
```json
{
    "user": {
        "id": 1,
        "first_name": "John",
        "last_name": "Doe",
        "email": "user@example.com",
        "role": "maestru",
        "is_admin": false,
        "is_super_admin": false
    },
    "token": "1|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "token_type": "Bearer",
    "expires_at": "2025-04-21T12:00:00+00:00",
    "expires_in_days": 90
}
```

### Get Current User
```
GET /api/mobile/user
Authorization: Bearer {token}
```

### Logout
```
POST /api/mobile/logout
Authorization: Bearer {token}
```

## Mobile App Integration

### iOS Implementation
1. **Store the token** securely (Keychain recommended)
2. **Include token in all requests**:
   ```swift
   request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
   request.setValue("mobile-app", forHTTPHeaderField: "X-Platform")
   ```
3. **Handle token expiration**: When receiving 401, redirect to login
4. **Refresh token**: Currently tokens last 90 days, but you can implement refresh logic

### Example Request
```swift
var request = URLRequest(url: url)
request.setValue("Bearer \(storedToken)", forHTTPHeaderField: "Authorization")
request.setValue("mobile-app", forHTTPHeaderField: "X-Platform")
```

## Logging

All authentication events are logged to `storage/logs/laravel.log` with detailed information:

### Login Logs
- Login attempts
- Token creation
- Token expiration dates
- User information

### Request Logs
- Platform detection
- Authentication method (token vs session)
- Token validation
- Session information
- Expiration times

### Example Log Entries
```
[2025-01-21 10:00:00] local.INFO: Mobile app login attempt {"email":"user@example.com"}
[2025-01-21 10:00:01] local.INFO: Mobile login successful - token created {"user_id":1,"token_expires_at":"2025-04-21T10:00:01+00:00"}
[2025-01-21 10:00:02] local.INFO: AuthenticateMobileApp middleware {"is_mobile_app":true,"has_authorization_header":true}
[2025-01-21 10:00:02] local.INFO: Token found and valid {"user_id":1,"token_expires_at":"2025-04-21T10:00:01+00:00"}
```

## Configuration

### Environment Variables
```env
# Sanctum token expiration (in minutes)
SANCTUM_EXPIRATION=129600  # 90 days

# Session lifetimes (in minutes)
SESSION_LIFETIME_MOBILE=129600  # 90 days
SESSION_LIFETIME_WEB=2880      # 48 hours
```

### Config Files
- `config/sanctum.php` - Sanctum configuration with 90-day expiration
- `config/session.php` - Session configuration (dynamically adjusted)

## Database

### Required Migration
Run the migration to create the `personal_access_tokens` table:
```bash
php artisan migrate
```

This creates a table with:
- `id` - Token ID
- `tokenable_type` - Model type (User)
- `tokenable_id` - User ID
- `name` - Token name ("mobile-app-token")
- `token` - Hashed token
- `abilities` - Token abilities
- `last_used_at` - Last usage timestamp
- `expires_at` - Expiration timestamp
- `created_at`, `updated_at` - Timestamps

## Security Considerations

1. **Token Storage**: Store tokens securely in mobile app (Keychain on iOS)
2. **HTTPS Only**: Always use HTTPS in production
3. **Token Rotation**: Consider implementing token refresh
4. **Revocation**: Tokens can be revoked on logout or security events
5. **Expiration**: Tokens expire after 90 days, requiring re-authentication

## Troubleshooting

### Check Logs
All authentication events are logged. Check `storage/logs/laravel.log` for:
- Token creation
- Token validation
- Expiration checks
- Platform detection
- Session information

### Common Issues

1. **Token not working**
   - Check logs for token validation errors
   - Verify token is sent in `Authorization` header
   - Ensure `X-Platform: mobile-app` header is set

2. **Token expired**
   - Check `expires_at` in logs
   - Tokens expire after 90 days
   - User needs to login again

3. **Platform not detected**
   - Ensure `X-Platform: mobile-app` header is set
   - Check user agent in logs
   - Verify middleware is running

## Testing

### Test Token Creation
```bash
curl -X POST http://localhost/api/mobile/login \
  -H "Content-Type: application/json" \
  -H "X-Platform: mobile-app" \
  -d '{"email":"user@example.com","password":"password"}'
```

### Test Authenticated Request
```bash
curl -X GET http://localhost/api/mobile/user \
  -H "Authorization: Bearer {token}" \
  -H "X-Platform: mobile-app"
```

## Files Modified/Created

1. `config/sanctum.php` - Sanctum configuration
2. `app/Http/Middleware/AuthenticateMobileApp.php` - Mobile authentication middleware
3. `app/Http/Controllers/Auth/MobileAuthController.php` - Mobile auth endpoints
4. `app/Http/Controllers/Auth/AuthenticatedSessionController.php` - Updated for mobile support
5. `app/Http/Middleware/SetPlatformSessionLifetime.php` - Added logging
6. `app/Http/Kernel.php` - Added middleware to web group
7. `routes/api.php` - Added mobile auth routes
8. `database/migrations/2025_01_21_000000_create_personal_access_tokens_table.php` - Token table
