0

I am using policies in my application. And for example, one user has a role customer-role. This customer-role has the customer.view permission. and in my customer policy I am checking like this.

public function view(User $user)
    {
        return $user->hasAccess('customer.view');
    }

And from getcustomer request class:

public function authorize()
    {
        return Gate::allows('view', 'App\Models\Customer') ? true : false;
    }

But this always returns false. Please someone help me here as am new to Laravel.

anonymous
  • 11
  • 6
  • are you currently authenticated? is the policy registered correctly? and `Gate::allows` returns a `boolean` – lagbox Nov 19 '20 at 06:05
  • yes am currently authenticated and policy registered correctly in AuthServiceProvider: 'App\Models\Customer' => 'App\Policies\CustomerPolicy' – anonymous Nov 19 '20 at 06:08
  • Gate::allows return false always even if the authenticated user has the permission – anonymous Nov 19 '20 at 06:10
  • are you sure `$user->hasAccess(...)` is returning what you expect? – lagbox Nov 19 '20 at 06:20
  • no, at least it's not checking the view method in policy, from the request class itself returning false – anonymous Nov 19 '20 at 06:23
  • you will need to find out why `$user->hasAccess(...)` doesn't return what you expect since that is what your authorization is based on – lagbox Nov 19 '20 at 06:25
  • can I know why the policy method is not hitting by my request class authorize method please? – anonymous Nov 19 '20 at 06:29
  • does `$user->hasAccess(...)` return what you expect ... because that is the thing that is what your authorization is based upon so you have to figure out if that is working correctly before the policy/authorization even comes into play – lagbox Nov 19 '20 at 06:30
  • yes it returns true for this – anonymous Nov 19 '20 at 06:33

1 Answers1

0

I could solve this issue. The problem was I've written a before() method in AuthServiceProvider as below:

Gate::before(function ($user) {
            if ($user->inRole('admin')) {
                return true;
            }
            else {
                return false;
           }
        });

As this is returning false for non-admin users, it is not checking any other methods. So I had to remove the else condition from this before() method and now it is working.

This article was helpful for me. https://blog.karmacomputing.co.uk/debugging-laravel-policies/

anonymous
  • 11
  • 6