jeudi 29 novembre 2018

Where I should use "Gates" in Laravel 5?

I store list of permissions in database.

I have a resource controller:

class UserController extends Controller {

   public function store(Request $request) {
       if (Gate::denies('create-user', User::class)) {

       }       

       /**
        when I use controller helper it throws 
        Illuminate\Auth\Access\AuthorizationException

        like this $this->authorize('create-user', User::class); 
       */

       return response()->json(User::create($request->validated()));
   }   

}

In my case more convenient use Gate::allows way because I have a specific list of permissions.

But how can I throw Illuminate\Auth\Access\AuthorizationException? if a user does not have permission to do this action.

I have to use Gate::allows instead of $this->authorize because in my UserPolicy I have to specify the name of a permission like this:

class UserPolicy
{
    use HandlesAuthorization;

     public function create(User $user)
     {
        $has = MyPermissionModel::hasAccess($user, 'create-user');
        return $has;
     }
}

But if I use Gates it seems more clear and correct:

class AuthServiceProvider extends ServiceProvider
{ 
    public function boot()
    { 
      Gate::define('create-user', 'App\Policies\UserPolicy@create');
    }
}

And now I can check access anywhere, not only inside UserController.

So my questions are:

What is a better way to check permissions when I store my permissions dynamically in DB?

How can I throw Illuminate\Auth\Access\AuthorizationException? if I use Gates.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2rdjPrJ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire