vaened / laravel-authorization

Package for the management of authorizations for Laravel 5

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Laravel Authorization

Build Status Scrutinizer Code Quality Software License

Laravel Authorization is a package that provides a simple administration interface for roles and permissions.

// create authorizations
$cashier = $this->roles->create('Cashier');
$create = $this->permissions->create('Create Documents');
$annul = $this->permissions->create('Annul Documents');


// grant authorizations
$cashier->grantMultiple([$create, $annul]);
$user->grant($cashier);

// check
$user->isMemberOf('cashier'); // true
$user->can('create-documents'); // true
$user->can('annul-documents'); // true

// deny authorizations
$user->deny('annul-documents');

// now
$user->can('annul-documents'); // false

Table of Contents

Installation

Laravel Authorization requires PHP 8.1. This version supports Laravel 9 only.

To get the latest version, simply require the project using Composer:

$ composer require enea/laravel-authorization

Once installed, if you are not using automatic package discovery, then you need to register the Enea\Authorization\AuthorizationServiceProvider service provider in your config/app.php.

and finally, it only remains to run in the console:

$ php artisan authorization:install

Quick Start

Starting with laravel-authorization is as simple as extending the User model that provides the package:

use Enea\Authorization\Models\User as Authorizable;

class User extends Authorizable {
    //
}

Or in case you need to customize your user model, you must implement the Enea\Authorization\Contracts\Authorisable interface and use the Enea\Authorization\Traits\Authorisable trait:

use Enea\Authorization\Contracts\Authorizable as AuthorizableContract;
use Enea\Authorization\Traits\Authorizable;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable;
}

Checks

There are some methods available for checking roles and permissions:

Method Parameter Return
can permission-name boolean
cannot permission-name boolean
isMemberOf role-name boolean
isntMemberOf role-name boolean

Example

// verify if a user has a permission
$user->can('permission-name');
// verify if a user does not have a permission
$user->cannot('permission-name');
// verify if a user is a member of a role
$user->isMemberOf('role-name');
// verify if a user is not a member of a role
$user->isntMemberOf('role-name');

On the other hand, a role can only have permissions:

// verify if a role has a permission
$role->can('permission-name');
// verify if a role does not have a permission
$role->cannot('permission-name');

GRANT

Simplify the way in which roles and permissions are granted, both can be granted through the grant method in your model, you can see an example here

// grant an authorization to user
$user->grant($authorization);
// grant multiple authorizations to user
$user->grantMultiple([$permission, $role]);
// grant a permission to role
$role->grant($permission);
// grant multiple permissions to role
$user->grantMultiple([$firstPermission, $secondPermission]);

REVOKE

To revoke a permission or role of a model, you must use the revoke or revokeMultiple method:

// revoke an authorization to a user
$user->revoke($authorization);
// revoke multiple authorizations of a user
$user->revokeMultiple([$permission, $role]);
// revoke a permission to a role
$role->revoke($permission);
// revoke multiple permissions of a role
$user->revokeMultiple([$firstPermission, $secondPermission]);

DENY

To prohibit certain accesses to a user can do it through the method deny and denyMultiple:

// deny a permission to a user
$user->deny($permission);
// deny multiple permissions to a user
$user->denyMultiple($permissions);

Middleware

The middleware are activated automatically from the beginning, to change this you can do it from the configuration file:

    // automatic middleware configuration.
    'middleware' => [
        'enabled' => true,

        'permissions' => [
            'alias' => 'authenticated.can',
            'class' => \Enea\Authorization\Middleware\PermissionAuthorizerMiddleware::class,
        ],
        'roles' => [
            'alias' => 'authenticated.is',
            'class' => \Enea\Authorization\Middleware\RoleAuthorizerMiddleware::class,
        ],
    ],

Or in case you want to do a manual configuration you can deactivate the automatic load and modify your kernel file:

protected $routeMiddleware = [
    ...
    
    // laravel-authorization
    'authenticated.can' => \Enea\Authorization\Middleware\PermissionAuthorizerMiddleware::class,
    'authenticated.is' => \Enea\Authorization\Middleware\RoleAuthorizerMiddleware::class,
];

Then you can use it in your routes like any other middleware:

$router->get('create', 'CreateController@create')->middleware('authenticated.can:create-articles');
$router->get('admin', 'DashboardController@index')->middleware('authenticated.is:admin');

In case any user tries to access a protected route without authorization, an exception of type UnauthorizedOwnerException will be throw.

Custom errors

To show a custom error, we can edit the Handler file:

public function render($request, Exception $exception)
{
    if ($exception instanceof UnauthorizedOwnerException) {
        return redirect()->route('custom-unauthorized-route');
    }
    return parent::render($request, $exception);
}

Blade Directives

This package also adds Blade directives to verify if the currently connected user has a specific role or permission. Optionally you can pass in the guard that the check will be performed on as a second argument.

For Roles

@authenticatedIs('articles-owner')
    // is articles owner
@else
    // it's not articles owner
@endauthenticatedIs

and to deny

@authenticatedIsnt('articles-owner')
    // it's not articles owner
@else
    // is articles owner
@endauthenticatedIsnt

For Permissions

@authenticatedCan('edit-articles')
    // can edit articles
@else
    // cannot edit articles
@endauthenticatedCan

and to deny

@authenticatedCannot('edit-articles')
    // cannot edit articles
@else
    // can edit articles
@endauthenticatedCannot

Examples

Simple CRUD

Changelog

Please see CHANGELOG for more information what has changed recently.

License

Laravel Authorization is licensed under The MIT License (MIT).

About

Package for the management of authorizations for Laravel 5

License:MIT License


Languages

Language:PHP 99.7%Language:Blade 0.3%