PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 4, 2022

[FIXED] Laravel 5.6 session timeout exception when using spatie permissions

 March 04, 2022     laravel, laravel-5, laravel-permission, php     No comments   

Issue

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.



Answered By - Brian Lee
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing