laravel - Use multiple Auth guards for one Policy -
i have implemented multiple auth guards in laravel 5.4 project (one of admins , other regular users). has worked far , both admins , users able log in. trying implement policy class works both auth guards. because have models want administrators edit , users own model able edit. have defined policy method.
app\policies\modelpolicy
public function update(user $user, model $model) { if ($user->id === $model->user_id) { return true; } if (auth::guard('admin')->check()) { return true; } return false; }
then in whatever controller method have model:
app\http\controllers\modelcontroller
public function update(model $model) { $this->authorize('update', $model); // update model }
this works if regular user logged in. however, when admin user logged in, doesn't reach policy (i know error logging). guessing policy class automatically deny request if default guard in auth::check()
fails. however, since valid users have 1 of several guards (not default), need bypass behavior.
i know implement admin logic in controller method , use policy if know dealing non-admin:
public function update(model $model) { if (!auth::guard('admin')->check()) { $this->authorize('update', $model); } // update model }
however, can spiral out of control if admin condition more complicated being logged in. more importantly, of logic belongs in policy, not muddying controller.
how possible use same policy class multiple authentication guards?
you can override "authorize" method in common controller (/app/http/controllers/controller.php
):
class controller extends basecontroller { use authorizesresources, dispatchesjobs, validatesrequests; use authorizesrequests { authorize protected laravelauthorize; } public function authorize($ability, $arguments = []) { if (!auth::guard('admin')->check()) { $this->laravelauthorize($ability, $arguments); } } }
Comments
Post a Comment