# System Admin Security Module

## Overview

The System Admin Security module provides enhanced authentication and access control for system administrators. It features a separate authentication system with stricter security measures to protect system-level operations.

**Version**: 1.0  
**Added**: February 2026

---

## Features

### Core Functionality
- ✅ Separate system admin authentication
- ✅ Stricter rate limiting (3 attempts per 15 minutes)
- ✅ Dedicated login page
- ✅ Enhanced session management
- ✅ System-level access control
- ✅ Organization management capabilities
- ✅ Audit logging for admin actions
- ✅ Two-factor authentication support

---

## System Admin vs Organization Admin

### System Admin
- **Scope**: Entire system
- **Access**: All organizations
- **Capabilities**:
  - Create/manage organizations
  - View system-wide analytics
  - Manage system settings
  - Access all data
  - System maintenance

### Organization Admin
- **Scope**: Single organization
- **Access**: Own organization only
- **Capabilities**:
  - Manage organization settings
  - Manage users and roles
  - View organization data
  - Configure organization features

---

## Authentication

### System Admin Login

**URL**: `/systemadmin/login`

**Features**:
- Separate login page
- Stricter rate limiting
- Enhanced security checks
- Session isolation

**Login Form**:
```
┌─────────────────────────────────────┐
│ System Administrator Login           │
├─────────────────────────────────────┤
│ Email:                               │
│ [____________________________]       │
│                                      │
│ Password:                            │
│ [____________________________]       │
│                                      │
│ [ ] Remember Me                      │
│                                      │
│ [Login as System Admin]              │
│                                      │
│ [Forgot Password?]                   │
└─────────────────────────────────────┘
```

### Rate Limiting

**System Admin Login**:
```
Attempts: 3
Window: 15 minutes
Lockout: 15 minutes
```

**Organization Login**:
```
Attempts: 5
Window: 1 minute
Lockout: 1 minute
```

**Why Stricter?**:
- System admins have elevated privileges
- Protect against brute force attacks
- Reduce attack surface
- Comply with security best practices

---

## Access Control

### System Admin Flag

**Database**:
```sql
ALTER TABLE users ADD COLUMN is_system_admin BOOLEAN DEFAULT FALSE;
```

**Checking System Admin**:
```php
// In controller
if (!auth()->user()->is_system_admin) {
    abort(403, 'System admin access required');
}

// In middleware
Route::middleware(['auth', 'system_admin'])->group(function () {
    // System admin routes
});

// In blade
@if(auth()->user()->is_system_admin)
    <a href="{{ route('systemadmin.dashboard') }}">System Admin</a>
@endif
```

### Middleware

**SystemAdminMiddleware**:
```php
namespace App\Http\Middleware;

class SystemAdminMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        if (!auth()->check()) {
            return redirect()->route('systemadmin.login');
        }

        if (!auth()->user()->is_system_admin) {
            abort(403, 'System administrator access required');
        }

        return $next($request);
    }
}
```

---

## System Admin Dashboard

### Dashboard Features

**URL**: `/systemadmin/dashboard`

**Sections**:

1. **System Overview**
   ```
   Total Organizations: 25
   Active Organizations: 23
   Total Users: 1,250
   Active Users: 1,180
   System Health: Good
   ```

2. **Recent Activity**
   - New organizations
   - User registrations
   - System errors
   - Security events

3. **Quick Actions**
   - Create Organization
   - View All Organizations
   - System Settings
   - View Logs

4. **System Metrics**
   - Database size
   - Storage usage
   - API requests
   - Performance metrics

---

## Organization Management

### Create Organization

**Access**: System Admin Dashboard → Create Organization

**Required Information**:
```yaml
Organization Details:
  name: string (required)
  slug: string (auto-generated)
  status: active|inactive|suspended
  
Admin User:
  name: string (required)
  email: email (required)
  password: string (required)
  
Settings:
  logo: file (optional)
  settings: json (optional)
```

**Creation Process**:
```
1. Enter organization details
2. Create admin user
3. Set initial settings
4. Activate organization
5. Send welcome email
```

### Manage Organizations

**List View**:
```
┌────────────────────────────────────────────────┐
│ Organizations (25)                              │
├────────────────────────────────────────────────┤
│ [Search] [Filter: All] [Sort: Name]           │
├────────────────────────────────────────────────┤
│ Qaya Creatives                                 │
│ Status: Active • Users: 45 • Created: Jan 2026│
│ [View] [Edit] [Suspend] [Delete]              │
├────────────────────────────────────────────────┤
│ Tech Solutions Ltd                             │
│ Status: Active • Users: 32 • Created: Jan 2026│
│ [View] [Edit] [Suspend] [Delete]              │
└────────────────────────────────────────────────┘
```

**Organization Details**:
```
Organization: Qaya Creatives
Status: Active
Created: January 15, 2026
Users: 45 (42 active, 3 inactive)
Employees: 38
Departments: 5

Settings:
- Email configured: Yes
- Theme customized: Yes
- Storage used: 2.5 GB
- Last activity: 2 hours ago

Actions:
[Edit Details] [Suspend] [Delete] [View Audit Log]
```

### Organization Actions

**Suspend Organization**:
```
Reason: [Select reason]
- Payment issues
- Policy violation
- Security concern
- Maintenance
- Other

Notes: [Optional notes]

[Confirm Suspension]
```

**Delete Organization**:
```
⚠️ Warning: This action cannot be undone!

Deleting organization will:
- Remove all users
- Delete all data
- Remove all files
- Cancel all subscriptions

Type organization name to confirm: [________]

[Delete Organization]
```

---

## Security Features

### Session Management

**System Admin Sessions**:
```
Timeout: 30 minutes
Remember Me: 7 days
Concurrent Sessions: 1
Session Isolation: Yes
```

**Features**:
- Automatic logout on inactivity
- Single session per admin
- Secure session storage
- Session hijacking protection

### Audit Logging

**Logged Actions**:
- Login/logout
- Organization creation
- Organization modification
- Organization suspension/deletion
- User management
- System settings changes
- Security events

**Log Entry**:
```
Timestamp: 2026-02-08 10:30:45
User: admin@system.com
Action: organization.created
Details: Created organization "Qaya Creatives"
IP Address: 192.168.1.100
User Agent: Mozilla/5.0...
```

### Two-Factor Authentication

**Setup**:
1. Enable 2FA in profile
2. Scan QR code with authenticator app
3. Enter verification code
4. Save recovery codes

**Login with 2FA**:
```
1. Enter email and password
2. Enter 6-digit code from app
3. Access granted
```

**Recovery**:
- Use recovery codes
- Contact system administrator
- Reset via email

---

## Routes

### System Admin Routes

```php
// Guest routes
Route::prefix('systemadmin')->name('systemadmin.')->group(function () {
    Route::middleware('guest')->group(function () {
        Route::get('/login', [SytemAdminController::class, 'showLogin'])
            ->name('login');
        Route::post('/login', [SytemAdminController::class, 'login'])
            ->middleware('throttle:3,15');
    });
    
    // Authenticated routes
    Route::middleware(['auth', 'system_admin'])->group(function () {
        Route::get('/dashboard', [SytemAdminController::class, 'dashboard'])
            ->name('dashboard');
        Route::resource('organizations', OrganizationController::class);
        Route::post('/logout', [SytemAdminController::class, 'logout'])
            ->name('logout');
    });
});
```

---

## Best Practices

### For System Admins

1. **Use Strong Passwords**
   - Minimum 12 characters
   - Mix of letters, numbers, symbols
   - Unique password
   - Change regularly

2. **Enable 2FA**
   - Always enable two-factor authentication
   - Keep recovery codes safe
   - Use authenticator app

3. **Monitor Activity**
   - Review audit logs regularly
   - Check for suspicious activity
   - Monitor system health

4. **Secure Access**
   - Use VPN when remote
   - Don't share credentials
   - Log out when done
   - Use secure networks

5. **Data Protection**
   - Regular backups
   - Secure data handling
   - Follow privacy policies
   - Comply with regulations

### For Organizations

1. **Limit System Admin Access**
   - Only grant to trusted users
   - Review access regularly
   - Remove when not needed

2. **Monitor System Admin Actions**
   - Review audit logs
   - Set up alerts
   - Investigate anomalies

3. **Security Training**
   - Train system admins
   - Update security policies
   - Conduct security audits

---

## Troubleshooting

### Cannot Login as System Admin

**Symptoms**:
- Login fails
- Access denied
- Redirected to organization login

**Solutions**:
1. Verify using correct login URL: `/systemadmin/login`
2. Check `is_system_admin` flag in database
3. Verify credentials are correct
4. Check rate limiting hasn't locked account
5. Clear browser cache and cookies

### Rate Limit Exceeded

**Symptoms**:
- "Too many attempts" error
- Cannot login
- Locked out

**Solutions**:
1. Wait 15 minutes
2. Check IP address
3. Verify credentials
4. Contact another system admin
5. Check server logs

### Session Expired

**Symptoms**:
- Logged out unexpectedly
- Session timeout
- Need to login again

**Solutions**:
1. Login again
2. Enable "Remember Me"
3. Check session timeout settings
4. Verify server time is correct
5. Check session storage

### Cannot Access Organization

**Symptoms**:
- 403 Forbidden
- Access denied
- Cannot view organization

**Solutions**:
1. Verify system admin status
2. Check organization exists
3. Verify permissions
4. Check middleware
5. Review audit logs

---

## Security Checklist

### Initial Setup
- [ ] Create system admin account
- [ ] Set strong password
- [ ] Enable two-factor authentication
- [ ] Save recovery codes
- [ ] Test login
- [ ] Configure rate limiting
- [ ] Set up audit logging
- [ ] Review security settings

### Regular Maintenance
- [ ] Review audit logs weekly
- [ ] Check for suspicious activity
- [ ] Update passwords quarterly
- [ ] Review system admin access
- [ ] Test backup and recovery
- [ ] Update security policies
- [ ] Conduct security audits
- [ ] Train system admins

### Incident Response
- [ ] Document security incidents
- [ ] Investigate anomalies
- [ ] Revoke compromised access
- [ ] Reset passwords
- [ ] Review audit logs
- [ ] Update security measures
- [ ] Notify affected parties
- [ ] Conduct post-incident review

---

## API Reference

### Endpoints

```
GET    /systemadmin/login           - Show login page
POST   /systemadmin/login           - Authenticate
GET    /systemadmin/dashboard       - System admin dashboard
GET    /systemadmin/organizations   - List organizations
POST   /systemadmin/organizations   - Create organization
GET    /systemadmin/organizations/{id} - View organization
PUT    /systemadmin/organizations/{id} - Update organization
DELETE /systemadmin/organizations/{id} - Delete organization
POST   /systemadmin/logout          - Logout
```

### Request Examples

**Login**:
```http
POST /systemadmin/login
Content-Type: application/json

{
  "email": "admin@system.com",
  "password": "SecurePassword123!",
  "remember": true
}
```

**Create Organization**:
```http
POST /systemadmin/organizations
Content-Type: application/json

{
  "name": "Qaya Creatives",
  "slug": "qaya-creatives",
  "status": "active",
  "admin_name": "John Doe",
  "admin_email": "john@qaya.com",
  "admin_password": "SecurePassword123!"
}
```

---

## Support

For issues or questions:
- Review [Troubleshooting Guide](../TROUBLESHOOTING.md)
- Check [FAQ](../FAQ.md)
- Check [CHANGELOG](../CHANGELOG.md)
- Contact system administrator

---

**Module Version**: 1.0  
**Last Updated**: February 6, 2026  
**Documentation Status**: Complete
