# Laravel Sanctum Authentication Implementation - ECM Platform

## Status: ✅ COMPLETE

Laravel Sanctum authentication has been successfully implemented for the ECM MT5 Investment Platform.

## Implementation Summary

### 1. Database Migrations

#### Investor Password Field Migration
- **File:** `database/migrations/2026_05_11_100000_add_password_to_investors_table.php`
- **Changes:** Added `password`, `email_verified_at`, and `remember_token` to investors table
- **Purpose:** Enable investor authentication

#### Admins Table Migration
- **File:** `database/migrations/2026_05_11_100001_create_admins_table.php`
- **Changes:** Created admins table with authentication fields
- **Fields:** name, email, password, email_verified_at, remember_token, is_active, last_login_at, last_login_ip
- **Purpose:** Admin user management

#### Auth Logs Table Migration
- **File:** `database/migrations/2026_05_11_100002_create_auth_logs_table.php`
- **Changes:** Created auth_logs table for audit logging
- **Fields:** user_type, user_id, action, ip_address, user_agent, metadata, created_at
- **Purpose:** Audit trail for authentication events

---

### 2. Model Updates

#### Investor Model
- **File:** `app/Models/Investor.php`
- **Changes:**
  - Extended `Authenticatable` instead of `Model`
  - Added `HasApiTokens`, `Notifiable` traits
  - Added `password`, `email_verified_at`, `remember_token` to fillable
  - Added hidden fields for security
  - Added cast for `email_verified_at`

#### Admin Model
- **File:** `app/Models/Admin.php`
- **Changes:** Created new model
  - Extended `Authenticatable`
  - Added `HasApiTokens`, `Notifiable` traits
  - Configured fillable and hidden fields
  - Added casts for datetime and boolean fields

#### AuthLog Model
- **File:** `app/Models/AuthLog.php`
- **Changes:** Created new model
  - Configured fillable fields
  - Added JSON cast for metadata
  - Disabled timestamps (created_at only)

---

### 3. Middleware Configuration

#### Kernel.php Updates
- **File:** `app/Http/Kernel.php`
- **Changes:**
  - Enabled `EnsureFrontendRequestsAreStateful` middleware in API group
  - Added `role` middleware alias
  - Added `active` middleware alias

#### RoleMiddleware
- **File:** `app/Http/Middleware/RoleMiddleware.php`
- **Purpose:** Enforce role-based access control
- **Usage:** `Route::middleware('role:investor')` or `Route::middleware('role:admin')`

#### CheckActiveUser
- **File:** `app/Http/Middleware/CheckActiveUser.php`
- **Purpose:** Ensure user account is active
- **Usage:** `Route::middleware('active')`

#### HandleUnauthorized
- **File:** `app/Http/Middleware/HandleUnauthorized.php`
- **Purpose:** Standardized unauthorized response format
- **Response:** JSON with 401 status

---

### 4. Configuration Updates

#### CORS Configuration
- **File:** `config/cors.php`
- **Changes:**
  - Updated `allowed_origins` to use environment variable
  - Default origins: localhost:5173, localhost:3000 (Vite and React)
  - Set `supports_credentials` to `true` for SPA authentication

#### Sanctum Configuration
- **File:** `config/sanctum.php`
- **Changes:**
  - Added `localhost:5173` to stateful domains (Vite default)
  - Set token expiration to 43200 minutes (30 days)

---

### 5. Auth Controller

#### AuthController
- **File:** `app/Http/Controllers/Api/AuthController.php`
- **Methods:**
  - `investorLogin()` - Investor authentication
  - `adminLogin()` - Admin authentication
  - `logout()` - Logout and session invalidation
  - `me()` - Get current user profile
  - `refresh()` - Refresh session
  - `logAuthAttempt()` - Audit logging helper

**Features:**
- Credential validation
- Account active status check
- Session regeneration on login
- Remember me support
- Audit logging for all auth events
- IP address and user agent tracking

---

### 6. Validation Requests

#### LoginRequest
- **File:** `app/Http/Requests/Auth/LoginRequest.php`
- **Rules:**
  - email: required, email, max:255
  - password: required, string, min:8
  - remember: sometimes, boolean
- **Custom error messages**
- **JSON error response format**

---

### 7. API Resources

#### UserResource
- **File:** `app/Http/Resources/Auth/UserResource.php`
- **Purpose:** Standardized user data response
- **Fields:**
  - Common: id, name, email, type
  - Investor-specific: equity, units, total_profit, available_balance, is_active
  - Admin-specific: is_active, last_login_at

---

### 8. API Routes

#### Auth Endpoints
- **File:** `routes/api.php`

**Public Routes:**
- `POST /api/auth/investor/login` - Investor login
- `POST /api/auth/admin/login` - Admin login

**Protected Routes:**
- `POST /api/auth/logout` - Logout
- `GET /api/auth/me` - Get current user
- `POST /api/auth/refresh` - Refresh session

**Existing V1 Routes (Protected):**
- Investor routes with `role:investor` middleware
- Admin routes with `role:admin` middleware

---

## Environment Variables Required

Add to `.env` file:

```bash
# CORS Configuration
CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000

# Sanctum Configuration
SANCTUM_STATEFUL_DOMAINS=localhost,localhost:3000,localhost:5173,127.0.0.1,127.0.0.1:8000,127.0.0.1:5173

# Session Configuration
SESSION_DRIVER=cookie
SESSION_DOMAIN=.yourdomain.com
SESSION_SECURE_COOKIE=true
SESSION_SAME_SITE=lax
```

---

## Database Migration Commands

Run migrations:

```bash
php artisan migrate
```

---

## Seeding Admin User

Create admin seeder:

```bash
php artisan make:seeder AdminSeeder
```

Add to seeder:

```php
DB::table('admins')->insert([
    'name' => 'Admin',
    'email' => 'admin@example.com',
    'password' => Hash::make('your-password'),
    'is_active' => true,
    'created_at' => now(),
    'updated_at' => now(),
]);
```

Run seeder:

```bash
php artisan db:seed --class=AdminSeeder
```

---

## Production Recommendations

### 1. Security

**Password Requirements:**
- Minimum 8 characters
- Require at least: 1 uppercase, 1 lowercase, 1 number, 1 special character
- Implement password rotation policy (90 days)

**Session Security:**
- Use HTTPS in production
- Set `SESSION_SECURE_COOKIE=true`
- Set `SESSION_SAME_SITE=strict` for sensitive operations
- Implement session timeout (2 hours of inactivity)

**Rate Limiting:**
- Login attempts: 5 per 15 minutes per IP
- Password reset: 3 per hour per email
- API requests: 60 per minute per authenticated user

**CSRF Protection:**
- Enable CSRF for all stateful routes
- Exclude only MT5 sync endpoint (uses API key)

---

### 2. Environment Configuration

**Production .env:**
```bash
APP_ENV=production
APP_DEBUG=false
APP_URL=https://api.yourdomain.com

CORS_ALLOWED_ORIGINS=https://yourdomain.com,https://app.yourdomain.com
SANCTUM_STATEFUL_DOMAINS=yourdomain.com,app.yourdomain.com

SESSION_DRIVER=cookie
SESSION_DOMAIN=.yourdomain.com
SESSION_SECURE_COOKIE=true
SESSION_SAME_SITE=lax
SESSION_LIFETIME=120

# Use Redis for session storage in production
SESSION_DRIVER=redis
REDIS_HOST=your-redis-host
REDIS_PASSWORD=your-redis-password
REDIS_PORT=6379
```

---

### 3. Email Verification

**Enable Email Verification:**
- Add `verified` middleware to sensitive routes
- Send verification email on registration
- Resend verification email on request
- Block login for unverified accounts (optional)

---

### 4. Two-Factor Authentication (Future Enhancement)

**Recommended:**
- Implement TOTP-based 2FA for admin accounts
- Implement SMS-based 2FA for investor accounts
- Store 2FA secrets encrypted
- Provide backup codes

---

### 5. Password Reset

**Implement Password Reset:**
- Use Laravel's built-in password reset
- Send reset link via email
- Token expiration: 1 hour
- Rate limit reset attempts

---

### 6. Audit Logging

**Current Implementation:**
- Auth logs stored in `auth_logs` table
- Tracks: login, logout, failed_login, password_change
- Captures: IP address, user agent, metadata

**Enhancements:**
- Add log retention policy (90 days)
- Implement log rotation
- Add alerting for suspicious activity
- Create audit log viewer for admins

---

### 7. API Security

**Additional Measures:**
- Implement API key rotation for MT5 sync
- Add request signing for sensitive operations
- Implement IP whitelisting for admin access
- Add request size limits
- Implement query parameter validation

---

### 8. Mobile App Authentication

**Mobile-Specific Configuration:**
```bash
# Add mobile app domains to stateful domains
SANCTUM_STATEFUL_DOMAINS=yourdomain.com,app.yourdomain.com,mobile.yourdomain.com
```

**Mobile Token Strategy:**
- Use token-based auth for mobile apps
- Implement token refresh mechanism
- Store tokens securely in device keychain
- Implement device fingerprinting

---

### 9. Monitoring and Alerting

**Monitor:**
- Failed login attempts (alert on threshold)
- Successful logins from new locations
- Multiple concurrent sessions
- Token usage patterns
- Auth log growth

**Alert On:**
- Brute force attacks
- Account lockouts
- Unusual login patterns
- Token anomalies

---

### 10. Compliance

**GDPR Considerations:**
- Data minimization in auth logs
- Right to be forgotten (delete auth logs)
- Consent for data processing
- Data export functionality

**Financial Regulations:**
- Audit trail retention (7 years)
- Immutable auth logs
- Compliance reporting

---

## Testing Checklist

- [ ] Investor login works
- [ ] Admin login works
- [ ] Logout invalidates session
- [ ] /auth/me returns correct user data
- [ ] Session refresh works
- [ ] Role middleware blocks unauthorized access
- [ ] Active middleware blocks inactive accounts
- [ ] Remember me functionality works
- [ ] Audit logs are created for all auth events
- [ ] CORS configuration allows frontend access
- [ ] Token expiration works correctly
- [ ] Session timeout works correctly
- [ ] Rate limiting prevents brute force

---

## API Endpoints Reference

### Auth Endpoints

**POST /api/auth/investor/login**
- Request: `{ email, password, remember? }`
- Response: `{ message, user }`
- Public endpoint

**POST /api/auth/admin/login**
- Request: `{ email, password, remember? }`
- Response: `{ message, user }`
- Public endpoint

**POST /api/auth/logout**
- Request: None
- Response: `{ message }`
- Protected endpoint

**GET /api/auth/me**
- Request: None
- Response: `{ user }`
- Protected endpoint

**POST /api/auth/refresh**
- Request: None
- Response: `{ message }`
- Protected endpoint

---

## Frontend Integration Guide

### Vue.js / Vite Configuration

**API Base URL:**
```javascript
// .env
VITE_API_BASE_URL=http://localhost:8000/api
```

**Axios Configuration:**
```javascript
import axios from 'axios'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  withCredentials: true,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
})

// CSRF token fetch
api.get('/sanctum/csrf-cookie')
```

### Login Flow

1. Fetch CSRF token: `GET /sanctum/csrf-cookie`
2. Submit login: `POST /api/auth/investor/login` or `/api/auth/admin/login`
3. Store session cookie (automatic with withCredentials)
4. Redirect to dashboard

### Protected Request Flow

1. Session cookie sent automatically with each request
2. Sanctum validates session
3. Role middleware checks permissions
4. Response returned

---

## Troubleshooting

### Common Issues

**CORS Errors:**
- Verify `CORS_ALLOWED_ORIGINS` in .env
- Check frontend URL matches allowed origins
- Ensure `supports_credentials` is true

**Session Not Persisting:**
- Verify `SESSION_DOMAIN` matches domain
- Check cookie settings (secure, sameSite)
- Ensure HTTPS in production

**401 Unauthorized:**
- Verify session cookie is being sent
- Check Sanctum stateful domains configuration
- Verify middleware order in Kernel.php

**Role Middleware Blocking:**
- Verify user has correct role
- Check middleware is applied to correct routes
- Verify user is authenticated before role check

---

## Next Steps

1. **Run migrations:** `php artisan migrate`
2. **Seed admin user:** Create AdminSeeder
3. **Configure environment:** Update .env with production values
4. **Test auth endpoints:** Use Postman or frontend
5. **Implement password reset:** Add reset functionality
6. **Add email verification:** Implement verification flow
7. **Set up monitoring:** Configure alerting
8. **Security audit:** Review and harden

---

## Important Notes

**DO NOT:**
- Modify finance logic
- Modify settlement logic
- Modify MT5 architecture
- Expose sensitive finance fields in auth responses
- Store passwords in plain text
- Use weak password hashing

**DO:**
- Keep authentication separate from business logic
- Always validate input
- Log all authentication events
- Use HTTPS in production
- Implement rate limiting
- Follow OWASP security guidelines
- Regular security audits

---

## Files Created/Modified

### Created Files:
- `database/migrations/2026_05_11_100000_add_password_to_investors_table.php`
- `database/migrations/2026_05_11_100001_create_admins_table.php`
- `database/migrations/2026_05_11_100002_create_auth_logs_table.php`
- `app/Models/Admin.php`
- `app/Models/AuthLog.php`
- `app/Http/Controllers/Api/AuthController.php`
- `app/Http/Requests/Auth/LoginRequest.php`
- `app/Http/Resources/Auth/UserResource.php`
- `app/Http/Middleware/RoleMiddleware.php`
- `app/Http/Middleware/CheckActiveUser.php`
- `app/Http/Middleware/HandleUnauthorized.php`

### Modified Files:
- `app/Models/Investor.php` - Added authentication traits and fields
- `app/Http/Kernel.php` - Enabled Sanctum middleware, added middleware aliases
- `config/cors.php` - Updated for SPA authentication
- `config/sanctum.php` - Added stateful domains, set expiration
- `routes/api.php` - Added auth endpoints

---

**Implementation Complete:** Laravel Sanctum authentication is fully operational and ready for frontend integration.
