Ildar Ildar - 2 months ago 53
PHP Question

Guest users in laravel authorization policies

I use policies for user authorization. How to use policies for guest users?

Here is my code:

In controller:

class PostController extends Controller
{
public function index(Post $post)
{
$this->authorize($post);
return $post->all();
}
}


In policy:

class PostPolicy
{
// This function executes only for authenticated users.
// I want to use it for guest users too
public function index(User $user)
{
return $user->can('get-posts');
}
}

Answer

First make a new service provider:

php artisan make:provider GuestServiceProvider

Then edit GuestServiceProvider.php with this:

public function boot()
{
    // Laravel policies only work if the user isn't null so for guest access we need to assign a dummpy user.
    // From now on to check for guest use is_null(Auth::user()->getKey())
    if(!Auth::check()) {
        $userClass = config('auth.providers.users.model');
        Auth::setUser(new $userClass());
    }
}

Now Policies will work for guest users and in your policy you can check for the guest by doing:

if(is_null(Auth::user()->getKey())){
    // it's a guest
}

Which essentially means if the user doesn't have an id then its not a real user, hence must be a guest.

Comments