Files
musadaq-saas/app/middleware/AuthMiddleware.php
Hamza-Ayed 214d96ee8d Security Hardening: Phase 1-3 complete
- C1: Hash refresh tokens before DB storage (sha256)
- C2: Remove JWT_SECRET fallback, fail hard if missing
- H1: Enforce HTTP methods per route (405 on mismatch)
- H2: CORS with origin whitelist from CORS_ORIGIN env var
- H3: Redact sensitive fields (tokens, passwords) from logs
- M1: Build HmacMiddleware with replay attack prevention
- M2: Fix rate limiter race condition with flock LOCK_EX
- M3: Guard dd() — suppressed in production
- M4: Remove .env from git tracking, strengthen .gitignore
- I1: Add HSTS header (max-age=31536000)
2026-05-03 21:06:17 +03:00

40 lines
946 B
PHP

<?php
/**
* Simple Authentication Middleware
*/
declare(strict_types=1);
namespace App\Middleware;
use App\Core\JWT;
final class AuthMiddleware
{
public static function check(): array
{
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
if (!str_starts_with($authHeader, 'Bearer ')) {
json_error('Unauthorized: Missing or invalid token', 401);
}
$token = substr($authHeader, 7);
$secret = env('JWT_SECRET');
if (!$secret || strlen($secret) < 32) {
error_log('FATAL: JWT_SECRET is missing or too short');
json_error('Server configuration error', 500);
}
$decoded = JWT::decode($token, $secret);
if (!$decoded) {
json_error('Unauthorized: Invalid or expired token', 401);
}
return $decoded;
}
}