Files
MoneyFlix/crm/Core/AuthMiddleware.php
T
1sonhador 0283e966a9 MoneyFlix: Add remaining assets and source maps
- Add source maps and license files for compiled assets
- Add debug and test files for development
- Complete Git repository with all necessary files for MoneyFlix project
2025-10-22 18:09:55 +01:00

87 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
{
if (Auth::check()) {
return;
}
$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)) {
// Define flag indicando autenticação via API key (acesso total)
$_SERVER['API_KEY_AUTH'] = true;
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();
}
}
}