Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
    }
}
like image 256
Ildar Avatar asked Dec 11 '22 15:12

Ildar


2 Answers

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.

like image 51
malhal Avatar answered Dec 15 '22 00:12

malhal


In your PostPolicy change this

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');
}
}

to:

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');
}
}

source

like image 33
Arnoldkk Avatar answered Dec 14 '22 23:12

Arnoldkk