AuthCheckMiddleware.php 1.44 KB
<?php

namespace App\Http\Middleware;

use App\Enums\UserStatusEnum;
use Closure;
use Hikoon\LaravelJwt\JwtGuard;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Http\Request;

class AuthCheckMiddleware
{
    /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected Auth $auth;

    /**
     * Create a new middleware instance.
     *
     * @param \Illuminate\Contracts\Auth\Factory $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @param mixed                                                                                             ...$guards
     * @throws \Throwable
     */
    public function handle(Request $request, Closure $next, ...$guards)
    {
        if (empty($guards)) {
            $guards = [NULL];
        }

        foreach ($guards as $guard) {
            $authGuard = $this->auth->guard($guard);
            $check     = $authGuard instanceof JwtGuard ? $authGuard->checkOrFail() : $authGuard->check();
            if ($check && $authGuard->user()?->getAttribute('status') === UserStatusEnum::ACTIVATE) {
                $this->auth->shouldUse($guard);
            }
        }

        return $next($request);
    }
}