Search code examples
phplaravellaravel-5laravel-permission

Laravel 5.6 session timeout exception when using spatie permissions


I have been trying to redirect the user after session timeout, but when using spatie permissions package i cant get the TokenMismatchException for the session timeout, i always get UnauthorizedException. Here is my Exceptions/Handler.php file:

public function render($request, Exception $exception)
{

    if ($exception instanceof TokenMismatchException){


        session()->flash('warning','Session timeout. Please login again.');
        return redirect()->guest(route('login'));
    }



    if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException){


        return redirect('/restricted');
    }



    return parent::render($request, $exception);
}

How to catch the session timeout exception and make a custom redirect in this case?


Solution

  • Sounds like the package's RoleMiddleware is being evaluated before VerifyCsrfToken in the pipeline. From their source, you can see it throws an UnauthorizedException immediately if the user is not logged in:

    namespace Spatie\Permission\Middlewares;
    use Closure;
    use Illuminate\Support\Facades\Auth;
    use Spatie\Permission\Exceptions\UnauthorizedException;
    class RoleMiddleware
    {
        public function handle($request, Closure $next, $role)
        {
            if (Auth::guest()) {
                throw UnauthorizedException::notLoggedIn();
            }
            $roles = is_array($role)
                ? $role
                : explode('|', $role);
            if (! Auth::user()->hasAnyRole($roles)) {
                throw UnauthorizedException::forRoles($roles);
            }
            return $next($request);
        }
    }
    

    You can modify the order of middleware by setting the $middlewarePriority property in the kernel, however, be aware this can lead to unintended side effects:

    protected $middlewarePriority = [
        \App\Http\Middleware\MyMiddleware::class,
    ];
    

    Look at the order of middleware defined in Illuminate\Foundation\Http\Kernel and work off that.