Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Authorize() confusion

I'm currently migrating a project from CodeIgniter to Laravel5.

I saw in Laracasts that you can use the Request::authorize() method to authorize access before the controller is called, and it returns true or false.

This would (I think) be the ideal solution as I can contain permission checks within the request, rather than pollute the controller with permission checks and redirections / responses.

The only problem is, when I return false from authorize(), it simply loads an empty white page with forbidden written, and I can't find any documentation on laravel.com on how to template it (either there is no documentation, or I'm overlooking it)

I know I can edit the 404 page in errors/404.blade.php, but I can't work out how to customize the 403 page, which I've tried to add a custom 403.blade.php page, which doesn't get displayed. ( https://mattstauffer.co/blog/laravel-5.0-custom-error-pages )

Is placing these permission checks in the Request a good idea? Or am I missing something?

Update I ran a backtrace from authorize(), and it looks like it throws an UnauthorizedException, which extends RuntimeException. I've tried catching both in the routes.php file, which doesn't work either.

I've also tried to create middleware, and call the middleware from a method, which doesn't work either, since the middleware's not even called at all.

Update 2 Ok, so I found out that I can only call $this->middleware() from the constructor, not individual methods, which is progress, I guess.

like image 743
Phil Cross Avatar asked Mar 17 '23 20:03

Phil Cross


1 Answers

What i do is add a forbiddenResponse() method to Request abstract class. You can return a response object from that method to render a human readable error.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;

abstract class Request extends FormRequest {

    public function forbiddenResponse()
    {
        return new JsonResponse('Unauthorized', 403);
        // or return Response::make('Unauthorized', 403);
    }
}
like image 150
Varol Avatar answered Mar 19 '23 12:03

Varol