# API Security Implementation

## Overview
Complete role-based API security implementation with JWT authentication and access control.

## 🔐 Features Implemented

### 1. Role-Based Authentication
✅ Added `role` column to users table
✅ Three roles: `system_admin`, `finance`, `user`
✅ Role-based middleware (`CheckUserRole`)
✅ Helper methods in User model

### 2. Database Changes

#### Migration: `add_role_to_users_table`
```php
Schema::table('users', function (Blueprint $table) {
    $table->string('role')->default('user')->after('email');
    $table->index('role');
});
```

#### User Model Updates
```php
// Added to fillable
'role'

// New methods
isSystemAdmin(): bool
isFinance(): bool
hasRole(string $role): bool
hasAnyRole(array $roles): bool
```

### 3. Middleware: CheckUserRole

**Location:** `app/Http/Middleware/CheckUserRole.php`

**Features:**
- Checks if user is authenticated
- System admin bypasses all checks (full access)
- Validates user has required role(s)
- Returns 401 for unauthenticated
- Returns 403 for unauthorized

**Usage in Routes:**
```php
Route::middleware(['auth:sanctum', 'role:system_admin'])->group(function () {
    // System admin only routes
});

Route::middleware(['auth:sanctum', 'role:system_admin,finance'])->group(function () {
    // System admin OR finance routes
});
```

### 4. Protected Routes

#### User Management
```php
// View Users - System Admin & Finance
GET /api/users
GET /api/users/{id}

// Manage Users - System Admin Only
POST   /api/users
PUT    /api/users/{id}
DELETE /api/users/{id}
```

### 5. Seeded Test Users

**System Administrator:**
- Username: `sysadmin`
- Password: `Admin@123`
- Role: `system_admin`
- Access: Everything

**Finance Manager:**
- Username: `finance`
- Password: `Finance@123`
- Role: `finance`
- Access: Finance module + view users

**Regular User:**
- Username: `user`
- Password: `User@123`
- Role: `user`
- Access: Basic features

### 6. Authentication Flow

```
1. User Login
   ↓
2. Validate Credentials
   ↓
3. Check Account Status
   ↓
4. Generate JWT Token
   ↓
5. Return Token + User Data
   ↓
6. Frontend Stores Token
   ↓
7. Token Used in API Requests
   ↓
8. Middleware Validates Token & Role
   ↓
9. Access Granted/Denied
```

## 📋 API Endpoints

### Authentication
```
POST /api/auth/login      - Login (returns token)
POST /api/auth/logout     - Logout (auth required)
POST /api/auth/refresh    - Refresh token (auth required)
GET  /api/auth/me         - Get current user (auth required)
```

### User Management
```
GET    /api/users         - List users (system_admin, finance)
GET    /api/users/{id}    - Get user (system_admin, finance)
POST   /api/users         - Create user (system_admin only)
PUT    /api/users/{id}    - Update user (system_admin only)
DELETE /api/users/{id}    - Delete user (system_admin only)
```

## 🛡️ Security Layers

### Layer 1: Authentication
- JWT token validation
- Laravel Sanctum
- Token expiration (30 days)

### Layer 2: Authorization
- Role-based middleware
- Permission checking
- Access control

### Layer 3: Data Validation
- Request validation
- Input sanitization
- Type checking

### Layer 4: Logging
- Access logs
- Failed login attempts
- User actions

## 🔧 Configuration

### Middleware Registration
**File:** `bootstrap/app.php`
```php
$middleware->alias([
    'verified' => \App\Http\Middleware\EnsureEmailIsVerified::class,
    'role' => \App\Http\Middleware\CheckUserRole::class,
]);
```

### CORS Configuration
**File:** `config/cors.php`
- Supports credentials: `true`
- Allowed origins: Frontend URL
- Allowed headers: Authorization, Content-Type

### Sanctum Configuration
**File:** `config/sanctum.php`
- Stateful domains configured
- Token expiration: 30 days
- httpOnly cookies enabled

## 🧪 Testing

### Test System Admin Access
```bash
# Login
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"sysadmin","password":"Admin@123"}'

# Create User (should work)
curl -X POST http://localhost:8000/api/users \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"username":"newuser","email":"new@test.com","password":"Test@123","role":"user"}'
```

### Test Finance Access
```bash
# Login
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"finance","password":"Finance@123"}'

# View Users (should work)
curl -X GET http://localhost:8000/api/users \
  -H "Authorization: Bearer YOUR_TOKEN"

# Create User (should fail - 403)
curl -X POST http://localhost:8000/api/users \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"username":"newuser","email":"new@test.com","password":"Test@123","role":"user"}'
```

### Test Regular User Access
```bash
# Login
curl -X POST http://localhost:8000/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"user","password":"User@123"}'

# View Users (should fail - 403)
curl -X GET http://localhost:8000/api/users \
  -H "Authorization: Bearer YOUR_TOKEN"
```

## 📊 Error Responses

### 401 Unauthorized
```json
{
  "message": "Unauthenticated.",
  "error": "Please login to continue"
}
```

### 403 Forbidden
```json
{
  "message": "Access Denied",
  "error": "You do not have permission to access this resource"
}
```

### 422 Validation Error
```json
{
  "message": "The given data was invalid.",
  "errors": {
    "username": ["The username field is required."]
  }
}
```

## 🚀 Deployment Checklist

### Security
- [ ] Change default passwords
- [ ] Enable HTTPS in production
- [ ] Set secure cookie flag (production)
- [ ] Configure proper CORS origins
- [ ] Use strong JWT secret
- [ ] Enable rate limiting
- [ ] Add API throttling
- [ ] Setup monitoring

### Database
- [ ] Run migrations on production
- [ ] Create production admin user
- [ ] Backup database
- [ ] Index role column

### Environment
- [ ] Set APP_ENV=production
- [ ] Set APP_DEBUG=false
- [ ] Configure proper database
- [ ] Set SANCTUM_STATEFUL_DOMAINS
- [ ] Configure SESSION_DOMAIN

## 📝 Notes

### Password Requirements (Production)
- Minimum 12 characters
- Mix of uppercase, lowercase, numbers, special chars
- Password expiration policy
- Prevent password reuse

### Token Management
- Tokens expire after 30 days
- Refresh token before expiration
- Logout invalidates token
- One token per device/session

### Audit Trail
All user actions are logged:
- Login attempts (success/failure)
- User CRUD operations
- Access to sensitive data
- Role changes

## 🆘 Troubleshooting

### Issue: 401 on all requests
**Solution:** Check token in Authorization header
```
Authorization: Bearer YOUR_TOKEN_HERE
```

### Issue: 403 on protected routes
**Solution:** Check user role in database
```sql
SELECT id, username, role FROM users WHERE username = 'your_username';
```

### Issue: Token not working
**Solution:** 
1. Check token expiration
2. Verify SANCTUM_STATEFUL_DOMAINS
3. Check CORS configuration
4. Clear Laravel cache: `php artisan config:clear`

### Issue: Middleware not working
**Solution:**
1. Check middleware registration in bootstrap/app.php
2. Verify route middleware syntax
3. Clear route cache: `php artisan route:clear`

---

**Created:** December 3, 2025
**Version:** 1.0.0
**Author:** System Administrator

