php - Laravel 政策退货未经授权
问题描述
我正在尝试在我的项目中实施政策。尽管遵循了信函的文件,但所有尝试都被证明是不成功的。并且还阅读了关于 SO 和其他媒体的大量帖子。我按照文档中的描述做了,但它仍然不起作用。是什么赋予了?
在 AuthServiceProvider 中:
<?php
namespace App\Providers;
use App\User;
use App\Job;
use App\Policies\JobPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Job' => 'App\Policies\JobPolicy',
//Job::class => JobPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
在政策:
<?php
namespace App\Policies;
use App\Job;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class JobPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any jobs.
*
* @param \App\User $user
* @return mixed
*/
public function viewAny(User $user,Job $job)
{
//return (($user->isAdmin() || $user->isModerator() || $user->isUser()) && $user->status==1);
//return ($user->isMod());
return true;
}
在控制器中:
public function index()
{
$this->authorize('viewAny', User::class, Job::class);
return view("jobs.index");
}
我的用户模型:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Role;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',"role_id"
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function role(){
return $this->belongsTo("App\Role", "role_id");
}
public function isMod()
{
$user = User::find(auth()->user()->id);
$role = $user->role()->first()->name;
if($role==="job board moderator"){
return true;
}
else{
return false;
}
}
}
和工作模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\User;
class Job extends Model
{
protected $fillable = [
"title", "description", "email"
];
public function user(){
return $this->belongsTo("App\User","user_id");
}
}
解决方案
在政策:
public function viewAny(User $user)
{
return true;
}
在控制器中:
public function index()
{
$this->authorize('viewAny', Job::class);
return view("jobs.index");
}
推荐阅读
- filter - 嵌套 filter_time 过滤非序列月份
- reactjs - socket.io-client 在 ie 11 上导致语法错误 - Next js
- react-router - react route v4.1 除非刷新,否则无法显示组件,不使用 redux
- c# - 如何使用 C# 在 Slack 上共享 Extent 报告
- python - 有没有办法从py中的文本打印一行?
- reactjs - 尝试更改图层绘制属性但出现类型错误:无法读取未定义的属性“值”
- xml - 我如何继承模板门户 odoo 12
- javascript - 运行不安全 JavaScript 代码的最佳解决方案
- python - 我正在通过隐藏的 api 抓取 mysqltutorial 网站示例数据库表
- python - Python 中的动态编程 - 资源分配