░▒▓████████████████████████████████▓▒░ ░▒▓█ ▓▒░ ░▒▓█ ~ S W A M P ~ ▓▒░ ░▒▓█ ▓▒░ ░▒▓████████████████████████████████▓▒░
lon105.truehost.cloud
LOCATION:
/home/ilrtztmy/mandariconstructionsupplies.com/api/middleware
☗ ROOT
↻ REFRESH
✎ CARVE FLESH
EDITING: auth.php
<?php // middleware/auth.php require_once __DIR__ . "/../vendor/autoload.php"; // Assuming composer autoloader use Firebase\JWT\JWT; use Firebase\JWT\Key; // Function to get JWT secret from environment variable function getJwtSecret(): string { $secret = getenv("JWT_SECRET"); if (!$secret) { // Fallback for local development if .env is not loaded or variable is missing // In production, this should always be set via environment variables. // For local testing, you might set it directly here or in your web server config. error_log("JWT_SECRET environment variable not set. Using a default for development."); $secret = "5eeb3b45ff49f76a9c72ab5830dc75f7658751c31691a12cd0fce6bc64d471e6"; } return $secret; } // Function to verify JWT and return user data function verifyJwt(): ?object { $authHeader = $_SERVER["HTTP_AUTHORIZATION"] ?? ""; if (empty($authHeader) || !preg_match("/Bearer\s((.*)\\.(.*)\\.(.*))/", $authHeader, $matches)) { return null; // No token or invalid format } $jwt = $matches[1]; $secret = getJwtSecret(); try { $decoded = JWT::decode($jwt, new Key($secret, "HS256")); // Optionally, add more validation here (e.g., issuer, audience) return $decoded->data ?? null; } catch (Exception $e) { // Log the exception for debugging, but don't expose details to the client error_log("JWT verification failed: " . $e->getMessage()); return null; } } // Middleware function to protect admin routes function authMiddleware(array $allowedRoles = []): ?object { $adminUser = verifyJwt(); if (!$adminUser) { http_response_code(401); echo json_encode(["success" => false, "error" => ["code" => "UNAUTHORIZED", "message" => "Authentication required or token invalid."]]); exit(); } // Role-based access control if (!empty($allowedRoles) && !in_array($adminUser->role, $allowedRoles)) { http_response_code(403); echo json_encode(["success" => false, "error" => ["code" => "FORBIDDEN", "message" => "Insufficient permissions."]]); exit(); } return $adminUser; } // Helper to issue a new JWT (used by login/refresh endpoints later) function issueJwt(int $userId, string $userRole, int $expiryHours = 2): string { $secret = getJwtSecret(); $issuedAt = time(); $expirationTime = $issuedAt + (3600 * $expiryHours); // 2 hours expiry $payload = [ "iat" => $issuedAt, // Issued at: time when the token was generated "exp" => $expirationTime, // Expiration time "iss" => "mandari-api", // Issuer "data" => [ "id" => $userId, "role" => $userRole, ], ]; return JWT::encode($payload, $secret, "HS256"); } // Placeholder for rate limiting (Section 11) // This would typically involve checking an IP against a cache (e.g., Redis or file-based) // and incrementing a counter, then blocking if a threshold is exceeded. function rateLimitMiddleware(int $maxRequests = 100, int $windowSeconds = 3600): void { $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown'; $cacheDir = __DIR__ . '/../cache/rate_limit'; if (!is_dir($cacheDir)) { mkdir($cacheDir, 0755, true); } $file = $cacheDir . '/' . md5($ip); $now = time(); $data = ['count' => 0, 'start' => $now]; if (file_exists($file)) { $data = json_decode(file_get_contents($file), true); if ($now - $data['start'] > $windowSeconds) { $data = ['count' => 0, 'start' => $now]; } } $data['count']++; file_put_contents($file, json_encode($data)); if ($data['count'] > $maxRequests) { header("Content-Type: application/json"); http_response_code(429); echo json_encode(['success' => false, 'error' => ['code' => 'TOO_MANY_REQUESTS', 'message' => 'Rate limit exceeded.']]); exit(); } }
CANCEL
Name
Type
Size
Modified
Actions
↩ ..
DIR
—
—
📄 auth.php
PHP
3.9 KB
2026-07-02 15:56
EDIT