authorization in laravel with laravel heyman package
Laravel-heyman is a package created by Iman Ghafoori to implement authorization in Laravel. the primary way for us to implement authorization in laravel is by using gates and policies and then using authorize()
ot Gate::allows()
in controller methods.
but this package offers another way. with Heyman we define all the rules in a service provider and don’t touch the code itself.
this way we can separate the autorization logic from controllers and have all the necessary rules in one place.
laravel-heyman does not create roles and permissions. we can do that with a package like spatie-permissions.
Laravel HeyMan has a facade named HeyMan
. we use this facade in a service provider boot method to define rules.
for example, I want to deny a guest user to go to a certain route. I write this code in AuthServiceProvider:
Heyman::whenYouHitRoute('post.edit')->YouShouldBeLoggedIn();
there is a template for writing rules with this package:
we use chaining method after using HeyMan facade.
there are predefined situation, condition and reaction methods that help us implement authorization.
Situation Methods
hitting root names:
HeyMan::whenYouHitRouteName('admin')->...
visiting urls:
HeyMan::WhenYouVisitUrl('/signup')->...
when a controller gets called:
HeyMan::WhenYouCallAction('FileController@delete')->...
when a view file is rendered:
HeyMan::whenYouMakeView('post.edit')->...
when an Eloquent model is going to be saved:
HeyMan::whenYouSave(Post::class)->...
HeyMan::whenYouFetch(Post::class)->...
HeyMan::whenYouCreate(Post::class)->...
HeyMan::whenYouUpdate(Post::class)->...
HeyMan::whenYouDelete(Post::class)->...
conditions:
after the first method, we write the condition we want to check:
we usually define gates and use thisGateShouldAllow()
like this:
Gate::define('edit-user', function ($user) { return $user->hasRole('super-admin'); });
HeyMan::WhenYouVisitUrl('/post/edit')->thisGateShouldAllow('edit-user')->...
checking for authentication:
HeyMan::WhenYouVisitUrl('/panel*')->YouShoudbeLoggedIn()->...
HeyMan::WhenYouVisitUrl('/login')->YouShoudbeGuest()->...
Reactions
deny access:
HeyMan::whenYouHitRouteName('post.update')->thisGateShouldAllow('update-post')->otherwise()->weDenyAccess();
redirect:
HeyMan::whenYouHitVisitUrl('/admin')->YouShouldBeLoggedIn()->otherwise()->redirect()->to('/login');
//or
HeyMan::whenYouHitVisitUrl('/admin')->YouShouldBeLoggedIn()->otherwise()->redirect()->route('login');
abort:
HeyMan::whenYouVisitUrl('/panel')->YoushouldBeLoggedIn()->otherwise()->abort(403);
throw exception:
HeyMan::whenYouVisitUrl('/panel')->YoushouldBeLoggedIn()->otherwise()->weThrowNew(AuthorizationException::class, 'You have to login first');
you can find laravel-heyman documentation in its GitHub repo along with more examples.