76

GitHub - imanghafoori1/laravel-heyman: Laravel Authorization and validation made...

 5 years ago
source link: https://github.com/imanghafoori1/laravel-heyman
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

Laravel Hey Man

A package to help you write expressive code in a functional manner

image

And it works !!!

Quality Score code coverage Maintainability Build Status Code Coverage StyleCI Latest Stable Version Software License

??? HeyMan : "cleaner code" ➕ "easy authorization" ???

Built with ❤️ for every smart laravel developer

and it is very well tested !

Installation


composer require imanghafoori/laravel-heyman

Requirements:

PHP > v7.0
Laravel > v5.4

Sample Application :

https://github.com/imanghafoori1/council

https://github.com/imanghafoori1/council

This is fork from result of laracasts.com toturial series refactored to use the Heyman package.

A story :

Imagine your boss comes to you and says :

Hey man, When you go to login form, You should be guest, Otherwise you must get redirected to '/panel', Write the code for me, just now... But KEEP IN MIND you are not allowed to touch the current code. it is very sensitive and we do not want you to tamper with it. You may break it.

And you write code like this in a Service Provider boot method to implement what your boss wanted.

image

That is what this package does for you + a lot more...

Structural Benefits:

This way you can fully decouple authorization and a lot of guarding code from the rest of your application code and put it in an other place. So your Controllers and Routes become less crowded. and you will have a central place where you limit the access of users to your application or perform validation.

Should You Remember and Type in All The Methods?

IDE Auto-completion is fully supported.

untitled

Where do I put these codes ?

You can put these codes in AuthServiceProvider.php (or any other service provider) boot method to take effect.

image

Watching Urls

HeyMan::whenYouVisitUrl(['/welcome', '/home'])->...   // you can pass an Array
HeyMan::whenYouVisitUrl('/admin/articles/*')->...     // or match by wildcard
HeyMan::whenYouSendPost($url)->   ...   
HeyMan::whenYouSendPatch($url)->  ...  
HeyMan::whenYouSendPut($url)->    ...     
HeyMan::whenYouSendDelete($url)-> ...

Watching Route Names

HeyMan::whenYouReachRoute('welcome.name')->...
HeyMan::whenYouReachRoute('welcome.*')->...                 // or match by wildcard

Watching Controller Actions

HeyMan::whenYouCallAction('HomeController@index')->...
HeyMan::whenYouCallAction('HomeController@*')->...          // or match by wildcard

Watching Blade files

 HeyMan::whenYouMakeView('article.editForm')->...     // also accepts an array
 HeyMan::whenYouMakeView('article.*')->...            // You can watch a group of views

Watching Custom Events

HeyMan::whenEventHappens('myEvent')->...

Watching Eloquent Model Events

HeyMan::whenYouSave(\App\User::class)->...
HeyMan::whenYouFetch(\App\User::class)->...
HeyMan::whenYouCreate(\App\User::class)->...
HeyMan::whenYouUpdate(\App\User::class)->...
HeyMan::whenYouDelete(\App\User::class)->...

Note that the saving model is passed to the Gate of callback in the next chain call. so for example you can check the ID of the model which is saving.

*In case the gate returns false an AuthorizationException will be thrown. *(If it is not the thing you want, do not worry you can customize the action very easily, we will discuss shortly.)

This way gate is checked after event('myEvent') is executed any where in our app

What can be checked:

1 - Gates

HeyMan::whenYouVisitUrl('/home')->thisGateShouldAllow('hasRole', 'param1')->otherwise()->...;
HeyMan::whenYouVisitUrl('/home')->thisGateShouldAllow('SomeClass@someMethod', 'param1')->otherwise()->...;

Passing a Closure as a Gate:

$gate = function($user, $role){
    /// some logic
    return true;
}
HeyMan::whenYouVisitUrl('/home')->thisGateShouldAllow($gate, 'editor')->otherwise()->...;

2 - Authentication stuff:

HeyMan::whenYouVisitUrl('/home')->  youShouldBeGuest()    ->otherwise()->...;
HeyMan::whenYouVisitUrl('/home')->  youShouldBeLoggedIn() ->otherwise()->...;

3 - Checking A Closure or Method or Value:

HeyMan::whenYouVisitUrl('home')->thisMethodShouldAllow('someClass@someMethod', ['param1'])->otherwise()->...;
HeyMan::whenYouVisitUrl('home')->thisClosureShouldAllow(ّ function($a) { ... }, ['param1'])  ->otherwise()->...;
HeyMan::whenYouVisitUrl('home')->thisValueShouldAllow(ّ $someValue )->otherwise()->...;

4- Validate Requests:

HeyMan::whenYouSendPost('articles.store')->yourRequestShouldBeValid([
    'title' => 'required', 'body' => 'required',
]);

That way you do not need to validate requests in your controllers or create dedicated FormRequest classes to validate input.

Other things:

You can also use one of these:

HeyMan::whenYouVisitUrl('home')->youShouldAlways()-> ...
HeyMan::whenYouVisitUrl('home')->sessionShouldHave('key1')->...

Reactions:

1 - Deny Access

HeyMan::whenSaving(\App\User::class)->thisGateShouldAllow('hasRole', 'editor')->otherwise()->weDenyAccess();

An AuthorizationException will be thrown if needed

2 - Redirect

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->to(...)     ->with([...]);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->route(...)  ->withErrors(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->action(...) ->withInput(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->intended(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->redirect()->guest(...);

3- Throw Exception:

$msg = 'My Message';

HeyMan::whenYouVisitUrl('/login')
    ->youShouldBeGuest()
    ->otherwise()
    ->throwNew(AuthorizationException::class, $msg);

4- Abort:

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->abort(...);

5- Send Response:

Calling these functions generate exact same response as calling them on the response() helper function: return response()->json(...);

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->json(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->view(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->jsonp(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->make(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->response()->download(...);

Advanced Usage:

You may want to call some method or fire an event right before you send the response back. You can do so by afterCalling() and afterFiringEvent() methods.

HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->afterFiringEvent('explode')->response()->json(...);
HeyMan::whenYouVisitUrl('/login')-> ... ->otherwise()->afterCalling('someclass@method1')->response()->json(...);

Disabling Heyman:

You can disable HeyMan chacks like this (useful while testing):

untitled

HeyMan::turnOff()->allChecks();
...
/// some code here
...
HeyMan::turnOn()->allChecks();

? Contributing

If you find an issue, or have a better way to do something, feel free to open an issue or a pull request. If you use laravel-widgetize in your open source project, create a pull request to provide it's url as a sample application in the README.md file.

❗️ Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

⭐️ Your Stars Make Us Do More ⭐️

As always if you found this package useful and you want to encourage us to maintain and work on it. Just press the star button to declare your willing.

More from the authors:

Laravel Widgetize

? A minimal yet powerful package to give a better structure and caching opportunity for your laravel apps.


Laravel Terminator

? A minimal yet powerful package to give you opportunity to refactor your controllers.


Laravel AnyPass

? It allows you login with any password in local environment only.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK