laravel - Laravel 5.6 中的策略
问题描述
我正在尝试policy
在我的Laravel 5.6
应用程序中进行访问级别控制。
我有一个Subscriber
模型和一个Company
模型,Subscribers
只能Company
由那里的办公室位置根据 访问states/region
,即如果办公室属于分配给他们的区域,订户可以查看办公室的详细信息。为此,我有模型:
订户
class Subscriber extends Model {
//Fillables and basic attributes being assigned
public function stateIncludeRelation()
{
return $this->belongsToMany('Models\State','subscriber_states',
'subscriber_id', 'state_id');
}
public function user()
{
return $this->belongsTo('Models\User', 'user_id', 'id');
}
}
公司
class Company extends Model {
//Fillables and basic attributes being assigned
public function offices()
{
return $this->hasMany('Models\Company\Office', 'company_id');
}
}
然后为办公室
class Office extends Model {
//Fillables and basic attributes being assigned
public function company()
{
return $this->belongsTo('Models\Company', 'company_id', 'id');
}}
}
和一个常见的状态表:
class State extends Model {
//Fillables and basic attributes being assigned
public function subscriberAccess()
{
return $this->belongsToMany('Models\Subscriber',
'subscriber_states_included_relation',
'state_id', 'subscriber_id');
}
public function companyOffice()
{
return $this->hasOne('Models\Company\Office', 'state', 'id');
}
}
我创建了一个像这样的CompanyPolicy :
class CompanyPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the subscriber.
*
* @param User $user
* @param Company $company
* @return mixed
*/
public function view(User $user, Company $company)
{
//Finding subscriber/user state
$userState = State::whereHas('subscriberAccess', function ($q) use($user) {
$q->whereHas('user', function ($q) use($user) {
$q->where('email', $user->email);
});
})->get()->pluck('name');
//Finding company state
$companyState = State::whereHas('companyOffice', function ($q) use($company) {
$q->whereHas('company', function ($q) use($company) {
$q->where('slug', $company->slug);
});
})->get()->pluck('name');
if($userState->intersect($companyState)->all())
return true;
else
return false;
}
}
并将其注册到AuthServiceProvider
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
'Models\User' => 'Policies\CompanyPolicy',
];
在我的控制器中尝试获取类似的东西时:
public function companyGeneral(Request $request)
{
$user = Auth::user();
$company = Company::where('slug', $request->slug)
->with('offices')
->get()->first();
if($user->can('view', $company))
return response()->json(['data' => $company], 200);
else
return response()->json(['data' => 'Unauthorised'], 403);
}
每次我收到未经授权的回复。引导我进入这个。谢谢
解决方案
推荐阅读
- javascript - 无法在 puppeteer 中使用 xpath 提取下一页链接
- c++ - 如何在图标上方的壁纸上绘画?progman 0x052C 的替代方案
- selenium - 使用 Selenium 关键字查找元素中是否有任何文本
- javascript - 运行表单验证时我的 javascript 代码出错
- cakephp - cakephp 2.10 获取没有模型类的数据
- bootstrap-datetimepicker - datetimepicker 如何在 0-23 小时内显示时间?
- java - 如何在不启动任何活动或片段的情况下做到这一点
- node.js - 在无状态(REST)API 中使用 Redis(存储用户相关数据)是否错误?
- c++ - CBT Hook dll,拦截窗口被调整大小
- ios - SwiftUI - 由多个属性确定的动画没有动画,或者奇怪地更新