# Laravel JWT Authentication API - Setup Complete

## Overview
The Laravel JWT authentication system is now fully implemented with:
- ✅ Authentication Controller (AuthController.php)
- ✅ API Routes (routes/api.php)
- ✅ User Model with JWT Support
- ✅ Database Migration (users table)
- ✅ Database Seeder (18 test users)
- ✅ Auth Config Updated for JWT

## Files Created/Modified

### 1. **AuthController** - `app/Http/Controllers/Api/Auth/AuthController.php`
Complete authentication controller with methods:
- `login(email, password)` - Returns JWT token
- `register(name, email, password)` - Create new user
- `profile()` - Get current user profile
- `logout()` - Invalidate JWT token
- `refresh()` - Refresh JWT token
- `verify()` - Verify token validity
- `changePassword()` - Update password
- `forgotPassword()` - Request password reset
- `resetPassword()` - Reset password with token

**Key Features:**
- JWT token generation with php-open-source-saver/jwt-auth
- Token TTL: Configurable (default 60 minutes)
- Custom claims: email, role, tenant
- Error handling with detailed messages
- Validation on all endpoints

### 2. **API Routes** - `routes/api.php`
Configured endpoints:
```
POST   /api/auth/login              - Public
POST   /api/auth/register           - Public
POST   /api/auth/forgot-password    - Public
POST   /api/auth/reset-password     - Public

GET    /api/auth/profile            - Protected
POST   /api/auth/logout             - Protected
POST   /api/auth/refresh            - Protected
GET    /api/auth/verify             - Protected
POST   /api/auth/change-password    - Protected
```

### 3. **User Model** - `app/Models/User.php`
Updated to support JWT:
- Implements `JWTSubject` interface
- JWT methods: `getJWTIdentifier()`, `getJWTCustomClaims()`
- Helper methods: `hasRole()`, `isAdmin()`, `isDriver()`, etc.
- `updateLastLogin()` method
- All relationships preserved

**Database Fields:**
- id, name, email (unique), password
- phone, address
- role (Platform Admin, Tenant Admin, Operator Admin, Affiliate Admin, Corporate Traveler, Driver, Customer, Operations Manager, Finance Manager)
- tenant (for multi-tenant support)
- company, department, grade (for corporate travelers)
- status (active, inactive, suspended)
- last_login_at
- timestamps

### 4. **Database Migration** - `database/migrations/2024_01_01_000000_create_users_table.php`
Creates users table with:
- Full role-based access control columns
- Multi-tenant support
- Corporate traveler fields
- Proper indexes on email, role, tenant

### 5. **Database Seeder** - `database/seeders/UserSeeder.php`
18 test users with password **12345678**:

**Platform Admin:**
- Email: `admin@limozx.com`

**Operator Admins (2):**
- Email: `operator@olacabs.com` (Ola Cabs)
- Email: `operator@uber.com` (Uber)

**Tenant Admins (2):**
- Email: `tenant@olacabs.com` (Ola Cabs)
- Email: `tenant@uber.com` (Uber)

**Affiliate Admins (2):**
- Email: `affiliate@premiertravel.com` (Premier Travel)
- Email: `affiliate@corporatetravel.com` (Corporate Travel)

**Corporate Travelers (3):**
- Email: `raj.kumar@techcorp.com` (Sales - Senior Executive)
- Email: `priya.singh@techcorp.com` (Finance - Manager)
- Email: `anil.patel@techcorp.com` (Operations - Executive)

**Drivers (4):**
- Email: `driver1@limozx.com` through `driver4@limozx.com`

**Customers (2):**
- Email: `sarah.customer@email.com`
- Email: `john.corporate@email.com`

**Managers (2):**
- Email: `ops@limozx.com` (Operations Manager)
- Email: `finance@limozx.com` (Finance Manager)

### 6. **Auth Config** - `config/auth.php`
Updated API guard to use JWT driver:
```php
'api' => [
    'driver' => 'jwt',
    'provider' => 'users',
]
```

## Setup Instructions

### Step 1: Run Database Migrations
```bash
cd c:\Apps\LimozX\limozxAPI
php artisan migrate
```

### Step 2: Run Database Seeder
```bash
php artisan db:seed --class=UserSeeder
```

Or seed all:
```bash
php artisan db:seed
```

### Step 3: Verify JWT Package
Ensure `php-open-source-saver/jwt-auth` is installed:
```bash
composer require php-open-source-saver/jwt-auth
```

### Step 4: Publish JWT Config
```bash
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
```

### Step 5: Generate JWT Secret
```bash
php artisan jwt:secret
```

This creates the secret key in `.env`:
```
JWT_SECRET=your_generated_secret_key
```

### Step 6: Start Laravel Development Server
```bash
php artisan serve
```

Server runs on: `http://127.0.0.1:8000`

## API Usage Examples

### Login Request
```bash
POST http://127.0.0.1:8000/api/auth/login
Content-Type: application/json

{
  "email": "admin@limozx.com",
  "password": "12345678"
}
```

### Login Response
```json
{
  "success": true,
  "message": "Login successful",
  "token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "user": {
    "id": 1,
    "name": "Platform Admin",
    "email": "admin@limozx.com",
    "role": "Platform Admin",
    "tenant": null,
    "company": null,
    "department": null,
    "grade": null,
    "phone": "+91-9999999999"
  },
  "data": {
    "id": 1,
    "name": "Platform Admin",
    "email": "admin@limozx.com",
    "role": "Platform Admin",
    "tenant": null,
    "company": null,
    "department": null,
    "grade": null
  }
}
```

### Protected Request (Get Profile)
```bash
GET http://127.0.0.1:8000/api/auth/profile
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...
```

### Refresh Token
```bash
POST http://127.0.0.1:8000/api/auth/refresh
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...
```

### Logout
```bash
POST http://127.0.0.1:8000/api/auth/logout
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...
```

## Angular Integration

The Angular frontend is already configured to:
1. Call `POST /api/auth/login` with credentials
2. Receive JWT token in response
3. Store token in localStorage
4. Automatically inject token in all API requests via JwtInterceptor
5. Refresh token before expiration
6. Navigate to dashboards based on user role

### Angular Login Flow
```typescript
// src/app/services/auth.service.ts
login(email: string, password: string) {
  return this.restApi.login({ email, password })
    .then(response => {
      localStorage.setItem('token', response.token);
      // Set user data and navigate
    });
}
```

## Testing the System

### Test Users by Role

1. **Platform Admin Dashboard:**
   - Email: `admin@limozx.com`
   - Password: `12345678`
   - Access: System-wide administration

2. **Operator Admin Dashboard:**
   - Email: `operator@olacabs.com`
   - Password: `12345678`
   - Access: Ola Cabs fleet management

3. **Affiliate Admin Dashboard:**
   - Email: `affiliate@premiertravel.com`
   - Password: `12345678`
   - Access: Affiliate commission management

4. **Corporate Traveler Dashboard:**
   - Email: `raj.kumar@techcorp.com`
   - Password: `12345678`
   - Access: Personal trip management

5. **Driver Mobile App:**
   - Email: `driver1@limozx.com`
   - Password: `12345678`
   - Access: Trip pickup/delivery

6. **Customer:**
   - Email: `sarah.customer@email.com`
   - Password: `12345678`
   - Access: Ride booking

## Architecture Diagram

```
┌─────────────────┐
│  Angular Login  │
│   Component     │
└────────┬────────┘
         │
         │ POST /api/auth/login
         │ { email, password }
         ▼
┌─────────────────────────────────┐
│  Laravel AuthController::login  │
│  - Validate credentials         │
│  - Generate JWT token          │
│  - Return token + user data     │
└────────┬────────────────────────┘
         │
         │ { token, user }
         ▼
┌─────────────────────────────────┐
│  Angular stores token           │
│  - localStorage['token']        │
│  - Updates authState signal    │
│  - Navigates to dashboard       │
└────────┬────────────────────────┘
         │
         │ All subsequent requests
         │ Authorization: Bearer {token}
         ▼
┌─────────────────────────────────┐
│  JwtInterceptor                 │
│  - Reads token from localStorage│
│  - Injects into request header  │
└────────┬────────────────────────┘
         │
         │ Protected API endpoint
         ▼
┌─────────────────────────────────┐
│  Laravel (Protected Routes)     │
│  - Verify JWT signature         │
│  - Decode custom claims         │
│  - Process request              │
└─────────────────────────────────┘
```

## Token Expiration & Refresh

- **Token TTL:** 1 hour (3600 seconds)
- **Refresh Endpoint:** `POST /api/auth/refresh`
- **Angular Refresh Logic:** Automatically refresh 5 minutes before expiration

## Security Checklist

- ✅ Passwords hashed with bcrypt
- ✅ JWT tokens signed with secret key
- ✅ Protected routes with `auth:api` middleware
- ✅ Token included in all protected requests
- ✅ Token expiration enforced
- ✅ Invalid token rejection
- ✅ CORS configured for Angular domain

## Troubleshooting

### Issue: "CORS error" when logging in
**Solution:** Ensure CORS is configured in `config/cors.php`:
```php
'allowed_origins' => ['http://localhost:4200', 'http://localhost:3000'],
```

### Issue: "Token not found" on protected routes
**Solution:** Ensure Authorization header is sent:
```
Authorization: Bearer {token}
```

### Issue: "Invalid signature" error
**Solution:** Run `php artisan jwt:secret` and verify JWT_SECRET in .env

### Issue: "User not found" after login
**Solution:** Verify test users exist by running:
```bash
php artisan tinker
App\Models\User::count();
```

## Next Steps

1. **Test Login** - Try logging in with test credentials from Angular
2. **Verify Token** - Check token in browser DevTools > Application > localStorage
3. **Test Protected Routes** - Try accessing /api/auth/profile
4. **Role-Based Access** - Implement role checks in Angular guards
5. **Dashboard Access** - Verify dashboard components load based on user role

---

**System Status:** ✅ READY FOR TESTING

All backend components are in place. Test the end-to-end flow with the provided test credentials.
