cms-laravel/app/Http/Middleware/CheckAuth.php

47 lines
1.4 KiB
PHP

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use App\Services\CookieService;
use App\Services\ApiService;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Log;
class CheckAuth
{
protected $cookieService;
protected $apiService;
public function __construct(CookieService $cookieService, ApiService $apiService)
{
$this->cookieService = $cookieService;
$this->apiService = $apiService;
}
public function handle(Request $request, Closure $next)
{
$token = $this->cookieService->getCookie('TOKEN');
$publicRoutes = ['/', '/login', '/registration', '/change-password', '/topup-success-page', '/topup-error-page'];
if ($token) {
try {
$response = $this->apiService->post('adminProfile');
if ($response) {
Session::put('userInfo', $response);
Session::put('isAuthenticated', true);
if (in_array($request->path(), $publicRoutes)) {
return redirect('/user-management');
}
}
} catch (\Exception $e) {
Log::error('Failed to load user data', ['error' => $e->getMessage(), 'source' => 'CheckAuth']);
Session::flash('error', 'Something went wrong loading user data.');
}
}
return $next($request);
}
}