# Subdomain Restriction Implementation

## Overview
This document describes the implementation of subdomain-based access control for the CBT application. The system now properly handles subdomain routing and restricts access based on LBB (Lembaga Bimbingan Belajar) subdomains.

## Requirements
1. Landing page should ONLY be accessible from the central domain (e.g., `localhost:8000`)
2. Valid subdomain (e.g., `mrbob.localhost:8000`) should display the login page
3. Invalid subdomain should redirect to the central domain (landing page)

## Implementation Details

### 1. Middleware: `SetLbbContextFromSubdomain`
**Location:** `app/Http/Middleware/SetLbbContextFromSubdomain.php`

**Functionality:**
- Detects subdomain from the HTTP request host
- Validates if the subdomain corresponds to an active LBB in the database
- Redirects invalid subdomains to the central domain
- Sets LBB context in session when valid subdomain is found
- Checks user access permissions when authenticated

**Key Changes:**
- Added `getCentralDomain()` helper method for redirection
- Only considers active LBBs (status = 'active')
- Smooth redirect without error messages for invalid subdomains

### 2. HomeController Updates
**Location:** `app/Http/Controllers/HomeController.php`

**Functionality:**
- Checks if request is coming from a subdomain
- If valid subdomain detected → redirects to login page
- If invalid subdomain detected → lets middleware handle the redirect
- If no subdomain → displays landing page normally

**Key Methods Added:**
- `getSubdomain($host)` - Extracts subdomain from host
- `isCentralDomain($host)` - Checks if host is central domain

### 3. AuthController Updates
**Location:** `app/Http/Controllers/AuthController.php`

**Functionality:**
- `showLogin()` now detects subdomain and loads LBB settings accordingly
- Displays welcome message with LBB name when accessed from valid subdomain
- Login flow already handles subdomain-based authentication
- Helper methods added for subdomain detection

**Key Methods Added:**
- `getSubdomain($host)` - Extracts subdomain from host
- `isCentralDomain($host)` - Checks if host is central domain

### 4. Route Updates
**Location:** `routes/web.php`

**Changes:**
- Applied `lbb.context` middleware to:
  - Public routes (`/`, `/speed-test`, `/test`)
  - Authentication routes (`/login`, `/register`)
- Middleware is already registered in `bootstrap/app.php`

## How It Works

### Scenario 1: Access Landing Page from Central Domain
```
URL: http://localhost:8000
Flow:
1. Middleware detects no subdomain → passes through
2. HomeController detects no subdomain → displays landing page
Result: Landing page shown ✓
```

### Scenario 2: Access from Valid Subdomain
```
URL: http://mrbob.localhost:8000
Flow:
1. Middleware detects subdomain "mrbob"
2. Finds LBB with subdomain "mrbob" in database
3. Sets LBB context in session
4. HomeController detects valid subdomain → redirects to /login
5. Login page loads with LBB branding
Result: Login page shown with LBB settings ✓
```

### Scenario 3: Access from Invalid Subdomain
```
URL: http://xxx.localhost:8000
Flow:
1. Middleware detects subdomain "xxx"
2. No LBB found with subdomain "xxx"
3. Middleware redirects to central domain (localhost:8000)
4. HomeController displays landing page
Result: Redirected to landing page ✓
```

## Testing Instructions

### Prerequisites
Make sure you have at least one LBB with a subdomain in your database. You can create one via:
1. Super Admin panel → LBB Management → Create LBB
2. Or use database seeder

### Test Case 1: Landing Page Access
```bash
# Access central domain
curl http://localhost:8000

# Expected: Landing page is displayed
# No redirection occurs
```

### Test Case 2: Valid Subdomain
```bash
# Assuming you have LBB with subdomain "mrbob"
curl http://mrbob.localhost:8000

# Expected: Redirects to login page (or shows login if already on /login)
# LBB settings are loaded for branding
```

### Test Case 3: Invalid Subdomain
```bash
# Access non-existent subdomain
curl http://xxx.localhost:8000

# Expected: Redirects to http://localhost:8000 (landing page)
# No error message shown
```

### Test Case 4: Login Flow
1. Create a student account associated with an LBB
2. Access login from the LBB's subdomain
3. Login with student credentials
4. Expected: Student is logged in and redirected to dashboard
5. LBB context is automatically set

## Configuration

### Environment Variables
No new environment variables required. The system uses:
- `APP_URL` - Base URL for the application
- `APP_DOMAIN` - Optional domain name for production

### Central Domains
The following are considered central domains (defined in middleware):
- `localhost:8000`
- `127.0.0.1:8000`
- `APP_DOMAIN` (if set in .env)

## Database Schema

### LBB Table
The `lbbs` table must have:
- `subdomain` (string) - Unique identifier for the subdomain
- `status` (enum) - Must be 'active' for subdomain to work
- `name` (string) - LBB name for display

## Security Considerations

1. **Subdomain Validation**: Only active LBBs are considered valid
2. **User Access Control**: Middleware verifies user has access to the LBB
3. **Session Management**: LBB context is stored in session for authenticated users
4. **Redirect Safety**: Invalid subdomains are safely redirected to central domain

## Troubleshooting

### Issue: Subdomain not working locally
**Solution**: Make sure your local development server is accessible via subdomain. For development with Laravel Valet:
```bash
valet link mrbob
valet link another-subdomain
```

For standard `php artisan serve`, subdomains may not work. Consider using a tool like `localhost` subdomain mapping or use `/login/{subdomain}` route for testing.

### Issue: Middleware not executing
**Solution**: Verify middleware is registered in `bootstrap/app.php`:
```php
$middleware->alias([
    'lbb.context' => \App\Http\Middleware\SetLbbContextFromSubdomain::class,
]);
```

### Issue: LBB not found
**Solution**: Check that:
1. LBB exists in database
2. LBB status is 'active'
3. Subdomain matches exactly (case-sensitive)
4. No trailing spaces in subdomain field

## Future Enhancements

Potential improvements for the future:
1. Add subdomain-specific SSL certificates
2. Implement wildcard SSL for production
3. Add rate limiting for subdomain checks
4. Cache active LBB subdomains for better performance
5. Add admin panel to manage subdomains
6. Implement subdomain analytics/tracking

## Files Modified

1. `app/Http/Middleware/SetLbbContextFromSubdomain.php` - Enhanced with redirect logic
2. `app/Http/Controllers/HomeController.php` - Added subdomain detection
3. `app/Http/Controllers/AuthController.php` - Added subdomain-aware login
4. `routes/web.php` - Applied middleware to public and auth routes

## Summary

The implementation successfully achieves the requirements:
✅ Landing page is only accessible from central domain
✅ Valid subdomains show login page with LBB branding
✅ Invalid subdomains redirect to landing page
✅ User authentication works correctly with subdomain context
✅ LBB settings are loaded for branding on subdomain

The system is now ready for production use with proper subdomain-based routing and access control.