Files
MoneyFlix/crm/Core/AuthMiddleware.php
T
1sonhador 8542395fbe Add public campaign analytics functionality
- Add PublicCampaignsController for public campaign analytics
- Add public routes for /public/analytics/{slug} and /api/campaigns/{slug}
- Add public campaign analytics view with charts and KPIs
- Support for campaign sharing via custom slugs
- Real-time analytics with ApexCharts integration
2025-10-15 00:30:00 +01:00

84 lines
2.1 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: /login');
exit();
}
}
/**
* API or Auth: allow if logged in OR if Authorization Bearer matches env key
*/
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'] ?? getenv('REDIRECTS_API_KEY') ?? '';
if ($expected && $token && hash_equals($expected, $token)) {
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();
}
}
}