【问题标题】:Using laravel policy Authorization in blade view file在刀片视图文件中使用 laravel 策略授权
【发布时间】:2018-06-05 07:36:59
【问题描述】:

我正在尝试授权用户对视图文件中的某些内容限制进行授权,因为我知道 laravel 支持的身份验证(门、中间件)之间唯一可以在视图文件中使用的授权是(策略)身份验证。 并且策略身份验证通过使用 laravel 模型工作,而我的数据源不是模型,我只是从一些 Web 服务获取数据。

我创建了一个新策略 (isPlatinum)

    <?php

namespace App\Policies;

use App\User;
use App\WebUser;
use Illuminate\Auth\Access\HandlesAuthorization;

class isPlatinum
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    public function view(WebUser $user){
        return $user->user->subscription->type === 'platinum';
    }

}

注意:App\WebUser 不是模型文件,它只是一个从 web 服务获取用户信息的类。

在我的刀片视图文件中

@cannot('view',$isPlatinum)
        This page is for Platinum Users
        @endcannot

给出错误

Undefined variable: isPlatinum (View: 

我知道我应该只对模型使用 Laravel Policy Auth,在我的情况下,我应该使用什么是正确的 laravel auth,我可以在视图文件中使用?

【问题讨论】:

    标签: php laravel authorization


    【解决方案1】:

    您没有将isPlatinum 变量传递给查看。你可以share data with all views:

    如下创建服务提供者:

    <?php
    
    namespace App\Providers;
    
    use Illuminate\Support\Facades\View;
    
    class AuthServiceProvider extends ServiceProvider
    {
        /**
         * Bootstrap any application services.
         *
         * @return void
         */
        public function boot()
        {
            // method to fetch the webUser?
            // $webUser = ;
            View::share('isPlatinum', $webUser->user->subscription->type === 'platinum');
        }
    
        /**
         * Register the service provider.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    }
    

    【讨论】:

    • 谢谢,这是我认为对我来说是最佳选择的方式,我完全按照你的说法做了,错误显示响应:{"error":"token_not_provided"},为 web 服务请求提供了令牌App\WebUser ,令牌值来自 Session::get('token') , dd( Session::get('token')) 正在返回令牌没有任何问题,我只是想知道 AuthServiceProvider 是否无法使用WebUser 中的会话值?
    • 参考laracasts.com/discuss/channels/general-discussion/… ,在所有提供者注册后会触发提供者引导方法,因此会话应该可以工作。在我的情况下,WebUser 令牌值存储在 Session
    • 您应该在中间件中添加view()-&gt;share(),而不是添加Service Provider。
    猜你喜欢
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    相关资源
    最近更新 更多