Spaces:
Sleeping
Sleeping
| namespace App\Http\Middleware; | |
| use Closure; | |
| use Illuminate\Http\RedirectResponse; | |
| use Illuminate\Http\Request; | |
| use Symfony\Component\HttpFoundation\Response; | |
| class EnsureRagAuthenticated | |
| { | |
| private const AUTH_TOKEN_COOKIE = 'sevima_raghub_auth_token'; | |
| private const AUTH_USER_COOKIE = 'sevima_raghub_auth_user'; | |
| /** | |
| * Handle an incoming request. | |
| * | |
| * @param Closure(Request): (Response) $next | |
| */ | |
| public function handle(Request $request, Closure $next, string ...$roles): Response | |
| { | |
| $token = $request->cookie(self::AUTH_TOKEN_COOKIE); | |
| if (! is_string($token) || trim($token) === '') { | |
| return $this->redirectToLogin($roles); | |
| } | |
| if ($roles !== []) { | |
| $user = $this->userFromCookie($request); | |
| $role = $user['role'] ?? null; | |
| if (! is_string($role) || ! in_array($role, $roles, true)) { | |
| return is_string($role) | |
| ? redirect($this->dashboardPath($role)) | |
| ->with('status', 'Akses tidak sesuai role akun.') | |
| : $this->redirectToLogin($roles); | |
| } | |
| } | |
| return $next($request); | |
| } | |
| /** | |
| * @param array<int, string> $roles | |
| */ | |
| private function redirectToLogin(array $roles = []): RedirectResponse | |
| { | |
| $route = in_array('admin', $roles, true) ? 'admin.login' : 'login'; | |
| return redirect()->route($route) | |
| ->with('status', 'Silakan login terlebih dahulu.'); | |
| } | |
| /** | |
| * @return array<string, mixed> | |
| */ | |
| private function userFromCookie(Request $request): array | |
| { | |
| $rawUser = $request->cookie(self::AUTH_USER_COOKIE); | |
| if (! is_string($rawUser) || $rawUser === '') { | |
| return []; | |
| } | |
| $user = json_decode($rawUser, true); | |
| return is_array($user) ? $user : []; | |
| } | |
| private function dashboardPath(string $role): string | |
| { | |
| return match ($role) { | |
| 'admin' => route('admin.dashboard', absolute: false), | |
| 'student' => route('mahasiswa', absolute: false), | |
| 'lecturer' => route('dosen', absolute: false), | |
| default => route('dashboard', absolute: false), | |
| }; | |
| } | |
| } | |