# Authentication and Authorization Specification

## Overview

Comprehensive authentication and authorization system using Laravel Sanctum for API authentication and Filament for admin panel access control, with role-based permissions and security best practices.

## Authentication Architecture

### Laravel Sanctum Integration

**Purpose**: Provides API authentication for SPA applications

**Token Management**:
- **Token Storage**: Database storage with automatic expiration
- **Token Types**: Personal access tokens with configurable abilities
- **Security**: CSRF protection and secure token generation

**Frontend Integration**:
```javascript
// Login process
axios.post('/login', credentials)
  .then(response => {
    // Store token securely
    localStorage.setItem('api_token', response.data.token);
    // Set default authorization header
    axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`;
  });
```

### Session-Based Authentication

**Purpose**: Traditional web session management for admin panel

**Implementation**:
- Laravel Breeze scaffolding for basic auth
- Session cookies for state management
- CSRF protection for form submissions

## User Model and Roles

### User Model

**Location**: `app/Models/User.php`

**Key Attributes**:
```php
// Authentication
email: string (unique)              // Primary login identifier
password: string (hashed)           // Secure password hash
email_verified_at: timestamp        // Email verification status

// Authorization
role_id: bigint unsigned (nullable) // Foreign key to roles table

// Two-Factor Authentication
two_factor_secret: text (nullable)  // TOTP secret key
two_factor_recovery_codes: text (nullable)  // Backup recovery codes
two_factor_confirmed_at: timestamp (nullable)  // 2FA confirmation

// Preferences
email_notifications_enabled: boolean (default: true)  // Notification preferences
theme_preference: string (default: 'light')           // UI theme
locale: string (default: 'en')                        // Language preference
```

### Role-Based Access Control

**Role Model**:
```php
// Simple role system
id: bigint unsigned auto_increment primary key
name: varchar(255) unique          // Role identifier ('admin', 'user')
created_at, updated_at: timestamps
```

**Predefined Roles**:
- **admin**: Full system access, user management, configuration
- **user**: Standard user access, personal gallery management

**Role Assignment**:
```php
// Default role assignment (in migration)
$usersTable->foreignId('role_id')->constrained()->default(2); // Defaults to 'user' role

// Role checking
$user->role->name === 'admin'
$user->role?->name === 'admin' // Safe null checking
```

## Authorization Mechanisms

### API Authorization

**Protected Routes**:
```php
// routes/api.php
Route::middleware('auth:sanctum')->group(function () {
    Route::post('/api/images/keep', [ImageController::class, 'keepImage']);
    Route::delete('/api/images/{image}', [ImageController::class, 'deleteImage']);
    Route::get('/api/user', function (Request $request) {
        return $request->user();
    });
});
```

**Middleware Stack**:
1. **auth:sanctum**: Validates bearer token
2. **Custom Logic**: Additional business rule validation

### Admin Panel Authorization

**Filament Integration**:
- Built-in authentication for `/admin` routes
- Session-based admin access
- Automatic logout on inactivity

**Access Control**:
```php
// Filament panel configuration
->requirePasswordResetAfterLogin(false)
->passwordReset()
->emailVerification()
->twoFactorAuthentication()
```

## Security Measures

### Password Security

**Hashing Algorithm**:
- Laravel default: bcrypt with cost factor 12
- Future migration path to Argon2

**Password Requirements**:
- Minimum 8 characters
- Mixed case letters
- Numbers and special characters
- Not in common password lists

### Two-Factor Authentication

**Implementation**:
- TOTP (Time-based One-Time Password) standard
- Google Authenticator, Authy compatibility
- Recovery codes for account recovery

**Setup Flow**:
1. User enables 2FA in profile settings
2. QR code generated for authenticator app
3. User confirms setup with first TOTP code
4. Recovery codes generated and displayed once

**Verification**:
```php
// Middleware for 2FA verification
if ($user->two_factor_secret && !$user->two_factor_confirmed_at) {
    return redirect()->route('two-factor.challenge');
}
```

### Session Security

**Configuration**:
```php
// config/session.php
'secure' => env('SESSION_SECURE_COOKIE', true),    // HTTPS only
'http_only' => true,                               // Prevent XSS access
'same_site' => 'lax',                              // CSRF protection
'expire_on_close' => false,                        // Persistent sessions
'lifetime' => 120,                                 // 2 hour timeout
```

**Admin Session Management**:
- Shorter session lifetime for admin users
- Automatic logout on suspicious activity
- Session fixation protection

## Permission System

### Image Ownership

**Business Rules**:
- Users can only modify their own images
- Temporary images are tied to processing session
- Public images visible to all authenticated users

**Implementation**:
```php
// ImageController@deleteImage
public function deleteImage(Image $image)
{
    // Implicit authorization via route model binding
    // User must own the image or be admin
    $this->authorize('delete', $image);
    // or explicit check
    if ($image->user_id !== auth()->id() && !auth()->user()->isAdmin()) {
        abort(403);
    }
}
```

### Admin Permissions

**Admin-Only Operations**:
- User management (create, edit, delete users)
- System configuration changes
- Plugin and API provider management
- Style and AI model configuration
- Application settings modification

**Permission Checking**:
```php
// Policy-based authorization
class ImagePolicy
{
    public function delete(User $user, Image $image): bool
    {
        return $user->id === $image->user_id || $user->role->name === 'admin';
    }
}

// Controller usage
$this->authorize('delete', $image);
```

## Security Headers and CSRF Protection

### Security Headers

**Content Security Policy**:
```php
// app/Http/Middleware/SetContentSecurityPolicy.php
$contentSecurityPolicy = [
    'default-src' => ['self'],
    'script-src' => ['self', 'unsafe-inline', 'unsafe-eval'],
    'style-src' => ['self', 'unsafe-inline'],
    'img-src' => ['self', 'data:', 'https:'],
    'connect-src' => ['self', 'ws:', 'wss:'],
];
```

**Other Security Headers**:
- `X-Frame-Options: SAMEORIGIN` - Prevent clickjacking
- `X-Content-Type-Options: nosniff` - Prevent MIME sniffing
- `Referrer-Policy: strict-origin-when-cross-origin` - Control referrer info
- `Permissions-Policy: camera=(), microphone=(), geolocation=()` - Disable unnecessary permissions

### CSRF Protection

**Laravel CSRF**:
- Automatic token generation for forms
- Middleware validation on state-changing requests
- Exception for API routes (handled by Sanctum)

**Custom CSRF**:
```php
// Verify CSRF token manually if needed
if (!hash_equals($request->session()->token(), $request->input('_token'))) {
    abort(419, 'CSRF token mismatch');
}
```

## Authentication Flows

### User Registration

**Flow**:
1. User submits registration form
2. Validation (email format, password strength, uniqueness)
3. Account creation with default 'user' role
4. Email verification (if enabled)
5. Welcome email sent

**Validation Rules**:
```php
'email' => 'required|email|unique:users|max:255',
'password' => 'required|min:8|confirmed',
'name' => 'required|string|max:255',
```

### User Login

**Flow**:
1. User submits credentials
2. Rate limiting applied (5 attempts per minute)
3. Credentials verified against database
4. 2FA challenge if enabled
5. Session/token created
6. Redirect to appropriate interface

**Rate Limiting**:
```php
// Throttle login attempts
RateLimiter::tooManyAttempts($key, 5) // 5 attempts
RateLimiter::hit($key, 60) // Lock for 60 seconds
```

### Password Reset

**Secure Token Flow**:
1. User requests password reset
2. Secure token generated and emailed
3. Token validated on reset form
4. Password updated with new hash
5. Old tokens invalidated

**Token Security**:
- Cryptographically secure random tokens
- Short expiration time (1 hour)
- Single-use tokens

## Admin Authentication

### Admin Panel Access

**Route Protection**:
```php
// Admin routes protected by Filament middleware
Route::prefix('admin')->name('admin.')->middleware([
    'auth:sanctum', // API authentication
    // Filament middleware stack
])->group(function () {
    // Admin routes
});
```

**Role-Based Access**:
- Only users with 'admin' role can access admin panel
- Automatic redirect for unauthorized users
- Session management for admin activities

### Admin User Management

**User CRUD Operations**:
- Create new users with role assignment
- Edit user details and permissions
- Disable/enable user accounts
- Reset passwords securely

**Bulk Operations**:
- Mass role assignment
- Account activation/deactivation
- Email notifications for status changes

## API Security

### Token Management

**Token Creation**:
```php
// Create personal access token
$token = $user->createToken('api-token', ['read', 'write']);
$plainTextToken = $token->plainTextToken;
```

**Token Abilities**:
- `read`: View images and styles
- `write`: Upload images and apply styles
- `admin`: Full administrative access

**Token Expiration**:
```php
// Create expiring token
$token = $user->createToken('temp-token', ['read'], now()->addHour());
```

### API Rate Limiting

**Current Implementation**: No explicit rate limiting (rely on external services)

**Recommended Limits**:
```php
// Per-user rate limits
'api:images:upload' => '5,1',      // 5 uploads per minute
'api:images:style-change' => '3,1', // 3 style changes per minute
'api:admin:*' => '60,1',           // 60 admin actions per minute
```

## Security Monitoring

### Audit Logging

**Authentication Events**:
- Login attempts (success/failure)
- Password changes
- 2FA setup/removal
- Role changes
- Admin actions

**Security Events**:
- Suspicious login attempts
- Multiple failed authentication attempts
- Admin privilege escalation
- API abuse detection

### Intrusion Detection

**Failed Login Monitoring**:
- Track failed attempts by IP/user
- Automatic account lockout after threshold
- Admin notification for repeated failures

**Session Monitoring**:
- Concurrent session detection
- Session hijacking prevention
- Unusual activity flagging

## Data Protection

### Password Storage
- **Algorithm**: bcrypt with configurable cost
- **Salt**: Automatic per-password salt generation
- **Upgrade Path**: Automatic rehash on successful login

### Sensitive Data
- **API Tokens**: Encrypted storage in database
- **2FA Secrets**: Encrypted TOTP secrets
- **Configuration**: Environment variables for sensitive settings

### Data Backup Security
- Encrypted database backups
- Secure backup storage locations
- Access logging for backup operations

## Compliance Considerations

### GDPR Compliance

**Data Handling**:
- User consent for data processing
- Right to data portability
- Right to be forgotten (account deletion)
- Data processing activity logs

**Privacy Features**:
- Granular privacy settings
- Data export functionality
- Secure account deletion process

### Security Standards

**OWASP Compliance**:
- Protection against common web vulnerabilities
- Secure coding practices
- Regular security assessments

**Industry Standards**:
- HTTPS enforcement
- Secure cookie handling
- Input validation and sanitization

## Future Security Enhancements

### Advanced Authentication

**OAuth Integration**:
- Social login providers (Google, GitHub)
- Single sign-on capabilities
- Third-party application access

**Biometric Authentication**:
- WebAuthn/FIDO2 support
- Hardware security key support
- Mobile authenticator integration

### Advanced Authorization

**Permission-Based Access**:
- Granular permissions beyond roles
- Resource-based permissions
- Dynamic permission assignment

**Multi-Tenancy**:
- Organization-based access control
- Team-based permissions
- Resource isolation

### Enhanced Security

**Advanced Monitoring**:
- Real-time threat detection
- Automated security responses
- Security information and event management (SIEM)

**Zero-Trust Architecture**:
- Continuous authentication
- Micro-segmentation
- Least privilege access

## Deployment Security

### Environment Security

**Development**:
- Debug mode disabled
- Verbose error reporting off
- Test credentials and data

**Production**:
- HTTPS enforcement
- Secure headers enabled
- Production credentials only

### Infrastructure Security

**Server Hardening**:
- Minimal attack surface
- Regular security updates
- Firewall configuration

**Database Security**:
- Encrypted database connections
- Minimal privilege accounts
- Regular backup testing

## Testing Security Features

### Authentication Tests

**Unit Tests**:
- Password hashing verification
- Token generation and validation
- Role assignment and checking

**Integration Tests**:
- Complete login/logout flow
- API authentication middleware
- Admin panel access control

**Security Tests**:
- SQL injection prevention
- XSS vulnerability testing
- CSRF protection validation

## Troubleshooting Security

### Common Issues

**Token Expiration**:
- Automatic token refresh mechanisms
- Graceful handling of expired sessions
- User notification and re-authentication

**Permission Errors**:
- Clear error messages for users
- Detailed logging for administrators
- Permission debugging tools

**Session Issues**:
- Session fixation protection
- Secure session handling
- Cross-site request forgery prevention