Laravel 5

时间:2016-05-03 02:22:17

标签: laravel-5.2 policy user-roles laravel-authorization

我正在实施项目的角色和权限,并使用策略,但是当我想要授权或不在Patients表中创建新记录时,我遇到了一个问题,非常简单。 我在PatientPolicy中有这个

// Only the users with root or admin roles can create patients;
public function create(User $user){
    return ($user->hasRole('root') || $user->hasRole('admin'));
}

// only the patient creator can edit the patient and see the edit button
public function update(User $user, Patient $patient){
    return $user->id == $patient->user_id;
}

AuthServiceProvider

protected $policies = [
    'App\Model' => 'App\Policies\ModelPolicy',
    'App\Patient' => 'App\Policies\PatientPolicy'
];

PatientController

public function edit(Patient $patient){
    if(Gate::denies('update', $patient)){
        abort(403, 'No esta autorizado de estar aqui');
    }
    return view('patients.edit', compact('patient'));
}

public function create(){
    if(Gate::denies('create')){
        abort(403, 'Usted no esta autorizado para crear pacientes');
    }
    return view('patients.create');
}

在我的观点中

@can('create')
    <li class="header">PROCESOS</li>
    <li><a href="/paciente/create"><i class="fa fa-book"></i> <span>Apertura de Historia Clínica</span></a></li>
@endcan

问题是即使对于被允许执行操作的用户,创建策略也总是返回false,但是编辑策略完美地运行。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

问题是Gate::denies@can方法在没有参数对应时不知道应该查找哪个模型和策略类,因此请改用此代码:

public function create(){
    if(Gate::denies('create', Patient::class)) {
        abort(403, 'Usted no esta autorizado para crear pacientes');
    }
    return view('patients.create');
}

并在您的观点中:

@can('create', App\Patient::class)
    <li class="header">PROCESOS</li>
    <li><a href="/paciente/create"><i class="fa fa-book"></i> <span>Apertura de Historia Clínica</span></a></li>
@endcan

你可以在这里查看我的完整答案: https://stackoverflow.com/a/37261276/3477084