# Permission Auto-Fix Automation Guide

## Overview

This guide shows you how to **automatically** add permission checks to all unprotected methods in your codebase.

## ⚠️ IMPORTANT: Read Before Running

**The automation will modify your controller files.** While it's designed to be safe, you should:
1. ✅ Backup first (automated)
2. ✅ Review changes before committing
3. ✅ Test thoroughly after running

## Quick Start (Recommended)

### Step 1: Preview Changes (Dry Run)
See what will be changed **without modifying any files**:

```bash
php scripts/auto_fix_permissions.php --dry-run
```

This shows you exactly what the script will do.

### Step 2: Backup Controllers
```bash
./scripts/backup_controllers.sh
```

Creates a timestamped backup in `backups/controllers_YYYYMMDD_HHMMSS/`

### Step 3: Run Auto-Fix (Excluding Auth-Only Methods)
Fix only the 165 critical methods that have NO protection:

```bash
php scripts/auto_fix_permissions.php --exclude-auth-only
```

This will:
- ✅ Add `requireAuth()` and `checkPermission()` to 165 unprotected methods
- ⏭️ Skip methods that already have authentication
- ⏭️ Skip intentionally public methods (login, logout, etc.)
- ⏭️ Skip test controllers (marks them for removal)

### Step 4: Add Missing Permissions to Database
```bash
php scripts/generate_missing_permissions_sql.php > missing_permissions.sql
mysql -u rpmbbu brickwal_m1_ds < missing_permissions.sql
```

### Step 5: Assign Permissions to Roles
Open: http://localhost:8080/roles/111/edit
- Check the appropriate permissions for your admin role
- Save

### Step 6: Test!
Test your application thoroughly to ensure everything still works.

### Step 7: Verify
```bash
php scripts/categorize_unprotected_methods.php
```

Should show dramatically fewer unprotected methods.

## Options

### Dry Run (Preview Mode)
```bash
php scripts/auto_fix_permissions.php --dry-run
```
Shows what would be changed without making any changes.

### Fix Specific Controller Only
```bash
php scripts/auto_fix_permissions.php --controller=ProjectsController
```
Only fixes one controller (good for testing).

### Include Auth-Only Methods
```bash
php scripts/auto_fix_permissions.php
```
Fixes ALL unprotected methods, including those that have auth but no permissions (302 total methods).

### Exclude Auth-Only Methods (Recommended)
```bash
php scripts/auto_fix_permissions.php --exclude-auth-only
```
Only fixes methods with NO protection at all (165 methods).

## What Gets Changed?

### Before:
```php
public function dashboard() {
    $projects = $this->projectModel->getAll();
    $this->layout('projects/dashboard', ['projects' => $projects]);
}
```

### After:
```php
public function dashboard() {
    $this->requireAuth();
    $this->checkPermission('projects.view');
    
    $projects = $this->projectModel->getAll();
    $this->layout('projects/dashboard', ['projects' => $projects]);
}
```

## What Gets Skipped?

The script **will NOT modify**:
- ✅ **AuthController** - Login/logout are intentionally public
- ✅ **AgreementController** - Public agreement views
- ✅ **Public methods** - login, logout, forgotPassword, publicView, etc.
- ✅ **Already protected methods** - Methods that already have permission checks
- ⚠️ **Test controllers** - AITestController, TestController (marks for removal)
- ⚠️ **Auth-only methods** (if using `--exclude-auth-only`)

## How Permissions Are Determined

The script intelligently determines permissions based on:

### Module Name (from controller):
- `ProjectsController` → `projects.*`
- `ShopFloorController` → `manufacturing.*`
- `BankImportController` → `accounting.*`
- `FileManagerController` → `files.*`

### Action (from method name):
- `index, list, show, view, display, dashboard` → `*.view`
- `create, store, add, new` → `*.create`
- `edit, update, modify` → `*.edit`
- `delete, remove, destroy` → `*.delete`
- `upload, import` → `*.upload`
- `export, download` → `*.export`
- `approve, reject, verify` → `*.approve`

### Examples:
- `ProjectsController::dashboard()` → `projects.view`
- `ProjectsController::create()` → `projects.create`
- `ShopFloorController::startProduction()` → `manufacturing.view` (default)
- `FileManagerController::upload()` → `files.upload`

## Step-by-Step Walkthrough

### Example: Fix ProjectsController Only

**1. Preview:**
```bash
php scripts/auto_fix_permissions.php --dry-run --controller=ProjectsController
```

Output:
```
📄 Processing ProjectsController...
  ✓ Would fix dashboard() - add: projects.view
  ✓ Would fix myTasks() - add: projects.view
  ✓ Would fix create() - add: projects.create
  ✓ Would fix store() - add: projects.create
  ... (31 methods total)
```

**2. Backup:**
```bash
./scripts/backup_controllers.sh
```

**3. Apply:**
```bash
php scripts/auto_fix_permissions.php --controller=ProjectsController
```

Output:
```
📄 Processing ProjectsController...
  ✓ Fixed dashboard() - added: projects.view
  ✓ Fixed myTasks() - added: projects.view
  💾 Saved changes (31 methods fixed)

Files modified: 1
Methods fixed: 31
```

**4. Review changes:**
```bash
git diff controllers/ProjectsController.php
```

**5. Test:**
- Visit project pages
- Verify they still work
- Check that permissions are being enforced

**6. Commit if good:**
```bash
git add controllers/ProjectsController.php
git commit -m "Add permission checks to ProjectsController"
```

## Batch Processing

### Fix All Critical Controllers at Once
```bash
# Backup first
./scripts/backup_controllers.sh

# Fix all (excluding auth-only)
php scripts/auto_fix_permissions.php --exclude-auth-only

# Add permissions to database
php scripts/generate_missing_permissions_sql.php > missing.sql
mysql -u rpmbbu brickwal_m1_ds < missing.sql

# Assign to roles
echo "Now assign permissions at: http://localhost:8080/roles/111/edit"
```

## Verification

After running the automation:

### Check Fixed Methods Count:
```bash
php scripts/categorize_unprotected_methods.php | head -30
```

### Expected Results:
- **Before:** 165 methods need protection
- **After (exclude-auth-only):** ~0 methods need protection (only test controllers remain)
- **After (full):** ~0 methods need protection

### Full Audit:
```bash
php scripts/audit_permissions_html.php > public/permission_audit.html
```

View at: http://localhost:8080/permission_audit.html

## Troubleshooting

### Issue: Permission not found in database
**Solution:**
```bash
php scripts/generate_missing_permissions_sql.php > missing.sql
mysql -u rpmbbu brickwal_m1_ds < missing.sql
```

### Issue: Users can't access pages after fix
**Solution:** Assign permissions to their roles at http://localhost:8080/roles/111/edit

### Issue: Wrong permission assigned
**Solution:** Manually edit the controller and change the permission:
```php
$this->checkPermission('correct.permission');
```

### Issue: Method should be public but got protected
**Solution:** Remove the protection from that method, or add it to the skip list.

## Rollback

If something goes wrong:

### Option 1: Restore from backup
```bash
# Find your backup
ls -la backups/

# Restore
cp -r backups/controllers_20251128_134500/* controllers/
```

### Option 2: Git revert
```bash
git checkout controllers/
```

### Option 3: Manual fix
Edit the specific controller and remove the added lines.

## Safety Features

The script has multiple safety features:

1. **Dry-run mode** - Preview before applying
2. **Skip lists** - Won't modify intentionally public methods
3. **Backup script** - Easy rollback
4. **Selective fixing** - Can fix one controller at a time
5. **Smart detection** - Only fixes truly unprotected methods
6. **Git-friendly** - Easy to review changes with `git diff`

## Best Practices

### ✅ DO:
- Run dry-run first
- Create backup before applying
- Fix one controller at a time initially
- Review changes with git diff
- Test thoroughly after each change
- Use --exclude-auth-only for first pass

### ❌ DON'T:
- Run without backup
- Apply to production without testing
- Skip the dry-run preview
- Ignore test controller warnings
- Forget to add permissions to database

## Complete Automation Workflow

```bash
# 1. See what needs fixing
php scripts/categorize_unprotected_methods.php

# 2. Preview changes
php scripts/auto_fix_permissions.php --dry-run --exclude-auth-only

# 3. Backup
./scripts/backup_controllers.sh

# 4. Apply fixes
php scripts/auto_fix_permissions.php --exclude-auth-only

# 5. Add permissions to database
php scripts/generate_missing_permissions_sql.php > missing.sql
mysql -u rpmbbu brickwal_m1_ds < missing.sql

# 6. Review changes
git diff controllers/

# 7. Test application
# (manual testing)

# 8. Verify success
php scripts/categorize_unprotected_methods.php

# 9. If good, commit
git add controllers/
git commit -m "Add automated permission checks to unprotected methods"

# 10. Assign permissions to roles (manual)
# http://localhost:8080/roles/111/edit
```

## Time Estimates

- **Dry run:** 2 seconds
- **Backup:** 1 second
- **Auto-fix (165 methods):** 3-5 seconds
- **Database update:** 1 second
- **Role assignment:** 5-10 minutes (manual)
- **Testing:** 30-60 minutes (manual)

**Total automated time:** ~10 seconds  
**Total including manual steps:** ~45-75 minutes

Compare to **manual fixing:** ~8-10 hours for 165 methods!

## Support

If you encounter issues:

1. Check the backup exists
2. Review the dry-run output
3. Check git diff to see what changed
4. Test on a single controller first
5. Consult `PERMISSION_AUDIT_GUIDE.md`

---

**Ready to automate?** Start with:
```bash
php scripts/auto_fix_permissions.php --dry-run --exclude-auth-only
```
