我正在尝试通过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');
}
}
然后是 Office
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);
}
每次我收到未经授权的回复。引导我进入这个。感谢