# CORS Configuration Guide

## Overview
This document explains the CORS (Cross-Origin Resource Sharing) configuration for the B2G User Management API.

## Environment-Based Configuration

### Development (YII_ENV = 'dev')
- **Allowed Origins**: 
  - `http://localhost:4200` (Angular dev server)
  - `http://localhost:3000` (Alternative dev server)
  - `http://127.0.0.1:4200`
  - `http://127.0.0.1:3000`
- **Debug**: Enabled
- **JWT Secret**: Local development key

### Test (YII_ENV = 'test')
- **Allowed Origins**: 
  - `https://test.b2g.com`
  - `http://localhost:4200` (for local testing against test API)
- **Debug**: Enabled
- **JWT Secret**: Test environment key

### UAT (YII_ENV = 'uat')
- **Allowed Origins**: 
  - `https://uat.b2g.com`
- **Debug**: Disabled
- **JWT Secret**: UAT environment key

### Production (YII_ENV = 'prod')
- **Allowed Origins**: 
  - `https://b2g.com`
  - `https://www.b2g.com`
- **Debug**: Disabled
- **JWT Secret**: Read from `JWT_SECRET` environment variable

## Files Structure

```
config/
├── params.php              # Base parameters with environment loading
├── params-local.php        # Development environment
├── params-test.php         # Test environment
├── params-uat.php          # UAT environment
├── params-prod.php         # Production environment
└── environment.php         # Environment helper class

controllers/
└── RegistrationController.php  # CORS-enabled controller

filters/
└── CorsFilter.php          # Custom CORS filter (optional)

proxy.conf.json             # Angular proxy configuration
```

## Angular Integration

### 1. Proxy Configuration (Development Only)
Create `proxy.conf.json` in your Angular project root:

```json
{
  "/api/*": {
    "target": "http://localhost:8080",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
```

### 2. Update angular.json
```json
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "proxyConfig": "proxy.conf.json"
  }
}
```

### 3. Start Angular with Proxy
```bash
ng serve --proxy-config proxy.conf.json
```

### 4. API Calls in Angular
Use relative paths in your Angular services:

```typescript
// ✅ Correct - Uses proxy
this.http.post('/api/registration/register', data)

// ❌ Wrong - Causes CORS issues
this.http.post('http://localhost:8080/registration/register', data)
```

## Testing CORS

### 1. Test CORS Configuration
```bash
curl -H "Origin: http://localhost:4200" \
     -H "Access-Control-Request-Method: POST" \
     -H "Access-Control-Request-Headers: Content-Type" \
     -X OPTIONS \
     http://localhost:8080/index.php?r=registration/cors-test
```

### 2. Test Registration Endpoint
```bash
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Origin: http://localhost:4200" \
     -d '{"test": "data"}' \
     http://localhost:8080/index.php?r=registration/cors-test
```

## Environment Variables (Production)

Set these environment variables in production:

```bash
# Required
JWT_SECRET=your-super-secure-jwt-secret-key-here

# Optional
YII_ENV=prod
YII_DEBUG=false
```

## Troubleshooting

### Common Issues

1. **CORS Error in Browser Console**
   - Check if the origin is in the allowed origins list
   - Verify the environment configuration is loaded correctly
   - Test with the `/registration/cors-test` endpoint

2. **Preflight Requests Failing**
   - Ensure OPTIONS method is allowed
   - Check that all required headers are in Access-Control-Allow-Headers

3. **Credentials Not Working**
   - Verify `Access-Control-Allow-Credentials: true` is set
   - Ensure the origin is explicitly listed (not using wildcards)

### Debug Commands

```bash
# Check current environment
php -r "require 'config/web.php'; echo YII_ENV;"

# Test CORS endpoint
curl -v http://localhost:8080/index.php?r=registration/cors-test

# Check parameters loading
php -r "
require 'vendor/autoload.php';
require 'config/params.php';
var_dump(\$params['cors']['allowedOrigins']);
"
```

## Security Notes

1. **Never use wildcards (*) in production**
2. **Always specify exact origins**
3. **Use HTTPS in production environments**
4. **Rotate JWT secrets regularly**
5. **Monitor CORS logs for suspicious requests**

## Implementation Checklist

- [x] Environment-specific parameter files created
- [x] CORS filter implemented in controllers
- [x] Manual CORS headers removed
- [x] Angular proxy configuration provided
- [x] Test endpoints created
- [x] Production environment variable setup documented
- [x] Security guidelines documented