diff --git a/README.md b/README.md index b312c31..e92695e 100644 --- a/README.md +++ b/README.md @@ -354,37 +354,56 @@ Get current user User user() +### Authorization + +Check if a user has a specific role or superseding role + + boolean is(string $role) + +```php +if (!$auth->is('admin')) { + http_response_code(403); + echo "You're not allowed to see this page"; + exit(); +} +``` + ### Access control (middleware) +Check if a user has a specific role or superseding role + + Jasny\Authz\Middleware asMiddleware(callback $getRequiredRole) + You can apply access control manually using the `is()` method. Alteratively, if you're using a PSR-7 compatible router with middleware support (like [Jasny Router](https://github.com/jasny/router)]). +The `$getRequiredRole` callback should return a boolean, string or array of string. + +Returning true means a the request will only be handled if a user is logged in. + ```php $auth = new Auth(); // Implements the Jasny\Authz interface -$roure->add($auth->asMiddleware(function(ServerRequest $request) { - $route = $request->getAttribute('route'); - return isset($route->auth) ? $route->auth : null; +$router->add($auth->asMiddleware(function(ServerRequest $request) { + return strpos($request->getUri()->getPath(), '/account/') === 0; // `/account/` is only available if logged in })); ``` -### Authorization - -Check if a user has a specific role or superseding role - - boolean is(string $role) +If the `Auth` class implements authorization (`Authz`) and the callback returns a string, the middleware will check if +the user is authorized for that role. If an array of string is returned, the user should be authorized for at least one +of the roles. ```php -if (!$auth->is('admin')) { - http_response_code(403); - echo "You're not allowed to see this page"; - exit(); -} +$auth = new Auth(); // Implements the Jasny\Authz interface + +$router->add($auth->asMiddleware(function(ServerRequest $request) { + $route = $request->getAttribute('route'); + return isset($route->auth) ? $route->auth : null; +})); ``` ### Confirmation - #### Signup confirmation Get a verification token. Use it in an url and set that url in an e-mail to the user.