Files
MoneyFlix/crm/Core/AuthMiddleware.php
T
XikaandCursor 1c67b0744f feat: add MoneyFlix lab smoke stack and fix redirector env loading (BIT-24693)
Lab bootstrap scripts exercise CRM PHP, Node redirector, health endpoints, and
MySQL analytics on 10.10.50.17. Bearer auth is checked before session dev-login;
redirector reads CRM_API_URL at fetch time so dotenv applies correctly.

Paperclip-Task: BIT-24693
Paperclip-Run: 3467cbf0-a91f-4cb0-808a-ccb043de28d3
Co-authored-by: Cursor <[email protected]>
2026-06-08 13:06:03 +00:00

88 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core;
class AuthMiddleware
{
/**
* Check if user is authenticated. If not, redirect to login page.
*/
public static function requireAuth(): void
{
if (!Auth::check()) {
header('Location: /auth/login');
exit();
}
}
/**
* API or Auth: allow if logged in OR if Authorization Bearer matches env key
* Se autenticado via Bearer, define flag para bypass de checks de role
*/
public static function apiOrAuth(): void
{
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$token = null;
if (stripos($authHeader, 'Bearer ') === 0) {
$token = trim(substr($authHeader, 7));
}
$expected = $_ENV['REDIRECTS_API_KEY'] ?? '';
if ($expected && $token && hash_equals($expected, $token)) {
$_SERVER['API_KEY_AUTH'] = true;
return;
}
if (Auth::check()) {
return;
}
http_response_code(401);
header('Content-Type: application/json');
echo json_encode(['success' => false, 'message' => 'Unauthorized']);
exit;
}
/**
* Check if user has a specific role.
*/
public static function requireRole(string $role): void
{
self::requireAuth();
$user = Auth::user();
if (!$user || $user['role'] !== $role) {
// Or redirect to a "403 Forbidden" page
header('Location: /');
exit;
}
}
/**
* Check if user has admin role.
*/
public static function requireAdmin(): void
{
self::requireRole('admin');
}
/**
* If user is already logged in, redirect them from login/register pages.
*/
public static function redirectIfAuthenticated(): void
{
if (Auth::check()) {
header('Location: /apps/users/profile'); // Redirect to profile or dashboard
exit();
}
}
public function requireGuest(): void
{
if (Auth::check()) {
header('Location: /apps/users/profile'); // Redirect to profile or dashboard
exit();
}
}
}