1
votes

I want to make some entries of Analysis publicly available. I tried to implement it with Policies but failed. I think it's because the AuthServiceProvider fails with AccessDeniedHttpException every time I try to access without an authorized user.

AuthServiceProvider

class AuthServiceProvider extends ServiceProvider
{
  protected $policies = [
    Analysis::class => AnalysisPolicy::class
  ];

  public function boot()
  {
    $this->registerPolicies();
  }
}

AnalysisPolicy

public function view(User $user, Analysis $analysis)
{
    if($analysis->demo === true){
        return true;
    }
    return $user->id === $analysis->user_id;
}

AnalysisController

public function show(int $analysis)
{
    $ana = Analysis::find($analysis);

    $this->authorize('view', $ana);

    ...
}

I tried to just create a new Service Provider, but that didn't work either as I cannot call the registerPolicies function without extending from AuthServiceProvider.

Basically, all I want is to now check for anything if the demo Attribute is true.

Edit:

My Quick-Fix form now is just checking in the controller if it's a demo. But that's not a great solution in my opinion as I think the goal with Policies should be that I don't have Access Management in the Controller. So I'd love to find a better solution.

if(!$ana->demo){
    $this->authorize('view', $ana);
}
1
What middlewares do you have on the route or controller?Devon
There is currently no middleware for the route. I just edited a fix which does work, so I don't think it is a problem with the middleware.onatcer
Yes, the issue that presents itself is Policies expect a user instance (as per the method definitions) and there is no User instance that represents a guest. See a discussion here: github.com/laravel/framework/issues/10568Devon
thanks a lot for the link. sorry I only searched for policy not for gates.onatcer
Sorry but I was just searching through various issues and PRs and found this: user-images.githubusercontent.com/1702638/… (it was to funny to not put it here)onatcer

1 Answers

3
votes

Ok so it turns out you should always read the release notes of the latest Laravel version before asking a question.

As of Laravel 5.7 there is a proper solution for this:

public function update(?User $user, Post $post)
{
    return $user->id === $post->user_id;
}

(https://laravel.com/docs/5.7/authorization#writing-policies)
By declaring $user optional, it's null for guest users and can be handled in the policy.