2016-09-04 42 views
3

我使用policies作爲用戶授權。如何爲訪客用戶使用策略?laravel授權政策中的訪客用戶

這裏是我的代碼:

在控制器:

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

政策:

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

回答

0

我覺得simpliest方式是保護與驗證的中間件。 或檢查用戶是否在政策認證

+0

我不能在策略中檢查它,因爲如果用戶未經過身份驗證,此功能不會執行 – Ildar

+1

然後使用Auth中間件保護路由。 –

7

首先製作一個新的服務提供商:

php artisan make:provider GuestServiceProvider 

然後用這個編輯GuestServiceProvider.php:

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

現在的政策,將來賓用戶工作,在您的保單中,您可以通過以下方式查看客人:

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

這基本上意味着如果用戶沒有身份證,那麼它不是真正的用戶,因此必須是客人。