All Projects → httpoz → Roles

httpoz / Roles

Licence: mit
Powerful package for handling roles in Laravel

Projects that are alternatives of or similar to Roles

Bouncer
Eloquent roles and abilities.
Stars: ✭ 2,763 (+2608.82%)
Mutual labels:  laravel, acl, roles
Laratrust
Handle roles and permissions in your Laravel application
Stars: ✭ 1,799 (+1663.73%)
Mutual labels:  laravel, acl, roles
Brandenburg
Laravel Authentication Package
Stars: ✭ 79 (-22.55%)
Mutual labels:  laravel, acl, roles
laravel-acl
Laravel ACL is a simple role, permission ACL for Laravel Framework.
Stars: ✭ 78 (-23.53%)
Mutual labels:  acl, roles
nova-permissions
Add Permissions based authorization for your Nova installation via User-based Roles and Permissions. Roles are defined in the database whereas Permissions are defined in the code base.
Stars: ✭ 115 (+12.75%)
Mutual labels:  acl, roles
ngx-security
Security directives for your Angular application to show/hide elements based on a user roles / permissions.
Stars: ✭ 18 (-82.35%)
Mutual labels:  acl, roles
Vue Gates
🔒 A Vue.js & Nuxt.js plugin that allows you to use roles and permissions in your components or DOM elements, also compatible as middleware and methods.
Stars: ✭ 184 (+80.39%)
Mutual labels:  laravel, roles
Shinobi
👺 Simple and light-weight role-based permissions system for Laravel's built in Auth system.
Stars: ✭ 349 (+242.16%)
Mutual labels:  laravel, roles
Laravel Authentication Acl
Laravel authentication and ACL admin panel package based on sentry
Stars: ✭ 292 (+186.27%)
Mutual labels:  laravel, acl
Permissionmanager
Admin interface for managing users, roles, permissions, using Backpack CRUD
Stars: ✭ 363 (+255.88%)
Mutual labels:  laravel, acl
Ngx Permissions
Permission and roles based access control for your angular(angular 2,4,5,6,7,9+) applications(AOT, lazy modules compatible
Stars: ✭ 749 (+634.31%)
Mutual labels:  acl, roles
rbac
Simple RBAC/ACL for Laravel 8 caching and permission groups.
Stars: ✭ 43 (-57.84%)
Mutual labels:  acl, roles
Laravel Acl
This package helps you to associate users with permissions and permission groups with laravel framework
Stars: ✭ 404 (+296.08%)
Mutual labels:  laravel, acl
Php Casbin
An authorization library that supports access control models like ACL, RBAC, ABAC in PHP .
Stars: ✭ 865 (+748.04%)
Mutual labels:  acl, roles
Sentinel
A framework agnostic authentication & authorization system.
Stars: ✭ 1,354 (+1227.45%)
Mutual labels:  laravel, roles
Laravel Auth
Laravel 8 with user authentication, registration with email confirmation, social media authentication, password recovery, and captcha protection. Uses offical [Bootstrap 4](http://getbootstrap.com). This also makes full use of Controllers for the routes, templates for the views, and makes use of middleware for routing. The project can be stood u…
Stars: ✭ 2,692 (+2539.22%)
Mutual labels:  laravel, roles
Nova Permission
A Laravel Nova tool for Spatie's laravel-permission library
Stars: ✭ 294 (+188.24%)
Mutual labels:  laravel, acl
Maravel Permissions
Because in the Maravelous univer every user deserves super power
Stars: ✭ 139 (+36.27%)
Mutual labels:  laravel, roles
Lock Laravel
This package is a Laravel 5 driver for Lock
Stars: ✭ 161 (+57.84%)
Mutual labels:  laravel, acl
Defender
Roles & Permissions for Laravel 8 / 7 / 6 / 5
Stars: ✭ 403 (+295.1%)
Mutual labels:  laravel, acl

Roles for Laravel 5 / 6

Powerful package for handling roles in Laravel

Build Status codecov Total Downloads PHPPackages Rank Latest Stable Version SensioLabsInsight

Laravel Version Roles Version
5.3.* Roles 1.4.x
5.4.* Roles 2.3.x
5.5.* Roles 3.0.x
5.6.* Roles 3.1.x
5.7.* Roles 3.2.x
5.8.* Roles 3.3.x
6.x Roles 4.x
7.x Roles 5.x

History

This project was largely inspired by Roman's romanbican/roles Laravel package. However at the time Laravel 5.3 was released his package was not actively maintained. I have ommitted permissions in this package in favour of Laravel's Authorization. I intend to keep this package as simple and minimal as is possible.

Installation

This package is very easy to set up. There are only couple of steps.

Composer

Add the package to your project via composer.

composer require httpoz/roles:^v5.0

Config File And Migrations

To publish the package config's file and migrations to your application. Run this command inside your terminal.

php artisan vendor:publish --provider="HttpOz\Roles\RolesServiceProvider"
php artisan migrate

Enable HasRole Trait And Contract

Include HasRole trait and also implement HasRole contract inside your User model.

<?php

use HttpOz\Roles\Traits\HasRole;
use HttpOz\Roles\Contracts\HasRole as HasRoleContract;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements HasRoleContract
{
    use Notifiable, HasRole;

    ///
}

And that's it!

Usage

Creating Roles

$adminRole = \HttpOz\Roles\Models\Role::create([
    'name' => 'Admin',
    'slug' => 'admin',
    'description' => 'Custodians of the system.', // optional
    'group' => 'default' // optional, set as 'default' by default
]);

$moderatorRole = \HttpOz\Roles\Models\Role::create([
    'name' => 'Forum Moderator',
    'slug' => 'forum.moderator',
]);

Because of Slugable trait, if you make a mistake and for example leave a space in slug parameter, it'll be replaced with a dot automatically, because of str_slug function.

Attaching And Detaching Roles

It's really simple. You fetch a user from database and call attachRole method. There is BelongsToMany relationship between User and Role model.

use App\User;

$user = User::find($id);

$user->attachRole($adminRole); // you can pass whole object, or just an id
$user->detachRole($adminRole); // in case you want to detach role
$user->detachAllRoles(); // in case you want to detach all roles

Syncing Roles

You may also use the sync method to attach roles to a user model. Any roles that are not passed into the method will be detached from the user's roles. So, after this operation is complete, only the roles passed into the method will be attached to the user:

$user = App\User::find($id);

$roles = [1, 4, 6]; // using the role IDs we want to assign to a user

$user->syncRoles($roles); // you can pass Eloquent collection, or just an array of ids

Checking For Roles

You can now check if the user has required role.

if ($user->isRole('admin')) { // you can pass an id or slug
    // do something
}

// or

if($user->hasRole('admin')) {
    // do something
}

// or

if ($user->isAdmin()) {
    //
}

And of course, there is a way to check for multiple roles:

In this case, a user has to have at least one of the given roles. Multiple options have been illustrated below that achieve the same goal.

    if ($user->isRole('admin|forum.moderator')) {
        // do something
    }

    if($user->isRole('admin, forum.moderator')){
        // do something
    }

    if($user->isRole(['admin', 'forum.moderator'])){
        // do something
    }

    if($user->isOne('admin|forum.moderator')){
        // do something
    }

    if($user->isOne('admin, forum.moderator')){
        // do something
    }

    if($user->isOne(['admin', 'forum.moderator'])){
        // do something
    }

In this case, a user has to have all the given roles. Multiple options have been illustrated below that achieve the same goal.

    if ($user->isRole('admin|forum.moderator', true)) {
        // do something
    }

    if($user->isRole('admin, forum.moderator', true)){
        // do something
    }

    if($user->isRole(['admin', 'forum.moderator'], true)){
        // do something
    }

    if($user->isAll('admin|forum.moderator')){
        // do something
    }

    if($user->isAll('admin, forum.moderator')){
        // do something
    }

    if($user->isAll(['admin', 'forum.moderator'])){
        // do something
    }

Find users by role

There are multiple ways to get a list of users by their given role.

Using the role's id

   $admins = Role::find(1)->users;

Using the role's slug

   $adminRole = Role::findBySlug('admin');
   $admins = $adminRole->users;

Using the role's group

   $adminRole = Role::where('group', 'forum.moderator')->first();
   $admins = $adminRole->users;

If you use soft delete on your Users model, and want to include deleted users, you can use usersWithTrashed method instead of users.

Groups

if ($user->group() == 'application.managers') {
    //
}

if ($user->inGroup('application.managers')) {
    // if true do something
}

If a user has multiple roles, method group returns the first one in alphabetical order (a better implementation of this will be explored).

Group is intended to collectively organise and assign permissions (Laravel's built in authorization feature) to a role group that can be shared by multiple roles (examples and implementation to be added to documentation in future).

Blade Extensions

There are two Blade extensions. Basically, it is replacement for classic if statements.

@role('admin') // @if(Auth::check() && Auth::user()->isRole('admin'))
    // user is admin
@endrole

@group('application.managers') // @if(Auth::check() && Auth::user()->group() == 'application.managers')
    // user belongs to 'application.managers' group
@endgroup

@role('admin|moderator', 'all') // @if(Auth::check() && Auth::user()->isRole('admin|moderator', 'all'))
    // user is admin and also moderator
@else
    // something else
@endrole

Middleware

This package comes with VerifyRole and VerifyGroup middleware. You must add them inside your app/Http/Kernel.php file.

/**
 * The application's route middleware.
 *
 * @var array
 */
protected $routeMiddleware = [

    // ...

    'role' => \HttpOz\Roles\Middleware\VerifyRole::class,
    'group' => \HttpOz\Roles\Middleware\VerifyGroup::class,
];

Now you can easily protect your routes.

$router->get('/example', [
    'as' => 'example',
    'middleware' => 'role:admin',
    'uses' => '[email protected]',
]);

$router->get('/example', [
    'as' => 'example',
    'middleware' => 'group:application.managers',
    'uses' => '[email protected]',
]);

It throws \HttpOz\Roles\Exceptions\RoleDeniedException or \HttpOz\Roles\Exceptions\GroupDeniedException exceptions if it goes wrong.

You can catch these exceptions inside app/Exceptions/Handler.php file and do whatever you want. You can control the error page that your application users see when they try to open a page their role is not allowed to. This package already has a view bundled with it that should have been published to resources/views/vendor/roles/error.blade.php when you published the package. Simply add the below condition inside your app\Exceptions\Handler.php's render function. Feel free to point to another view of your choice.

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof \HttpOz\Roles\Exceptions\RoleDeniedException || $exception instanceof \HttpOz\Roles\Exceptions\GroupDeniedException) {
            return response()->view('vendor.roles.error', compact('exception'), 403);
        }

        return parent::render($request, $exception);
    }

Config File

You can change connection for models, slug separator, models path and there is also a handy pretend feature. Have a look at config file for more information.

Caching

The configuration for cache expiry is defaulted to 2 weeks (in seconds). You can update this value to suit your project specific needs.

License

This package is free software distributed under the terms of the MIT license.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].