Complete Phase 1: MVC, DB migrations, Auth, RBAC, Security, and Views

This commit is contained in:
Hamza-Ayed
2026-06-05 00:56:41 +03:00
parent 7ffbc8bafa
commit bed7624ae9
51 changed files with 3295 additions and 0 deletions

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Middleware;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Services\Auth\AuthService;
use Exception;
class Authenticate implements MiddlewareInterface
{
private Session $session;
private AuthService $authService;
public function __construct(Session $session, AuthService $authService)
{
$this->session = $session;
$this->authService = $authService;
}
/**
* Authenticate session or JWT bearer token.
*/
public function handle(Request $request, Response $response, callable $next): void
{
$path = $request->getPath();
// 1. API Route Authentication (JWT verification)
if (str_starts_with($path, '/api')) {
$authHeader = $request->getHeader('Authorization');
if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
throw new Exception("Unauthorized. Bearer token missing.", 401);
}
$token = substr($authHeader, 7);
$user = $this->authService->verifyJwt($token);
if (!$user) {
throw new Exception("Unauthorized. Invalid or expired token.", 401);
}
// Inject the authenticated user into route parameters for controller access
$request->setRouteParams(array_merge($request->getRouteParams(), ['_authenticated_user' => $user]));
$next();
return;
}
// 2. Web Route Authentication (Session verification)
$userId = $this->session->get('user_id');
if (!$userId) {
$this->session->setFlash('error', 'Please login to access this page.');
$response->redirect('/login');
return;
}
$user = $this->authService->getUserById($userId);
if (!$user) {
$this->session->destroy();
$response->redirect('/login');
return;
}
// Inject the authenticated user
$request->setRouteParams(array_merge($request->getRouteParams(), ['_authenticated_user' => $user]));
$next();
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Middleware;
use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use Exception;
class CsrfProtection implements MiddlewareInterface
{
private Session $session;
public function __construct(Session $session)
{
$this->session = $session;
}
/**
* Handle CSRF token validation.
*/
public function handle(Request $request, Response $response, callable $next): void
{
// Skip validation for read-only requests
if (in_array($request->getMethod(), ['GET', 'HEAD', 'OPTIONS'])) {
$next();
return;
}
// Retrieve token from request parameters or custom header
$token = $request->input('_csrf') ?? $request->getHeader('X-CSRF-Token');
if (!$this->session->validateCsrfToken($token)) {
throw new Exception("CSRF token validation failed. Request untrusted.", 403);
}
$next();
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Middleware;
use App\Core\Request;
use App\Core\Response;
interface MiddlewareInterface
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Response $response
* @param callable $next The next middleware/action in the chain
*/
public function handle(Request $request, Response $response, callable $next): void;
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Middleware;
use App\Core\Request;
use App\Core\Response;
use Predis\Client as RedisClient;
use Exception;
use Throwable;
class RateLimit implements MiddlewareInterface
{
private ?RedisClient $redis = null;
private int $limit = 100; // Allow 100 requests
private int $window = 60; // Per 60 seconds
public function __construct()
{
$config = require __DIR__ . '/../../config/redis.php';
if (!empty($config['host'])) {
try {
$this->redis = new RedisClient([
'scheme' => 'tcp',
'host' => $config['host'],
'port' => $config['port'],
'password' => $config['password'],
'timeout' => 0.5, // 500ms connection timeout to fail fast
]);
$this->redis->connect();
} catch (Throwable $e) {
// Degrade gracefully if Redis server is down
$this->redis = null;
}
}
}
/**
* Handle rate limiting logic.
*/
public function handle(Request $request, Response $response, callable $next): void
{
if ($this->redis === null) {
// Redis unavailable, skip throttle check to avoid service outage
$next();
return;
}
$ip = $request->getIp();
$path = $request->getPath();
$key = "rate_limit:" . md5($ip . ":" . $path);
try {
$current = $this->redis->get($key);
if ($current !== null && (int)$current >= $this->limit) {
$ttl = $this->redis->ttl($key);
$response->header('Retry-After', (string)max(1, $ttl));
throw new Exception("Too Many Requests. Rate limit exceeded.", 429);
}
if ($current === null) {
// First request in the time frame window
$this->redis->setex($key, $this->window, 1);
$current = 0;
} else {
$this->redis->incr($key);
}
// Set rate limit headers
$remaining = $this->limit - ((int)$current + 1);
$response->header('X-RateLimit-Limit', (string)$this->limit);
$response->header('X-RateLimit-Remaining', (string)max(0, $remaining));
} catch (Throwable $e) {
if ($e->getCode() === 429) {
throw $e;
}
// Logging or catching connection dropping mid-request
}
$next();
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace App\Middleware;
use App\Core\Request;
use App\Core\Response;
class SecurityHeaders implements MiddlewareInterface
{
/**
* Add security-hardening headers to the response.
*/
public function handle(Request $request, Response $response, callable $next): void
{
// Enforce frame options to avoid clickjacking
$response->header('X-Frame-Options', 'SAMEORIGIN');
// Prevent MIME type sniffing
$response->header('X-Content-Type-Options', 'nosniff');
// Referrer policy
$response->header('Referrer-Policy', 'no-referrer-when-downgrade');
// Cross-Site Scripting protection
$response->header('X-XSS-Protection', '1; mode=block');
// HTTP Strict Transport Security (HSTS) - force HTTPS
$response->header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
// Content Security Policy (CSP)
// Allow scripts from self, google fonts, CDN js, styles from self/fonts
$csp = "default-src 'self'; " .
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net; " .
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://cdn.jsdelivr.net; " .
"font-src 'self' https://fonts.gstatic.com; " .
"img-src 'self' data: https:; " .
"connect-src 'self'; " .
"frame-ancestors 'none'; " .
"base-uri 'self'; " .
"form-action 'self';";
$response->header('Content-Security-Policy', $csp);
$next();
}
}