All Projects → mahmoud-y → laravel-roles-abilities-tutorial

mahmoud-y / laravel-roles-abilities-tutorial

Licence: other
Tutorial demonstrating the implementation of roles and abilities in Laravel

Programming Languages

PHP
23972 projects - #3 most used programming language
Blade
752 projects
shell
77523 projects

Projects that are alternatives of or similar to laravel-roles-abilities-tutorial

Brandenburg
Laravel Authentication Package
Stars: ✭ 79 (+393.75%)
Mutual labels:  roles, authorization
Laravel Governor
Manage authorization with granular role-based permissions in your Laravel Apps.
Stars: ✭ 131 (+718.75%)
Mutual labels:  roles, authorization
Sentinel
A framework agnostic authentication & authorization system.
Stars: ✭ 1,354 (+8362.5%)
Mutual labels:  roles, authorization
Policyserver.local
Sample OSS version of PolicyServer
Stars: ✭ 444 (+2675%)
Mutual labels:  roles, authorization
Kan
Simple, functional authorization library and role management for ruby
Stars: ✭ 232 (+1350%)
Mutual labels:  roles, authorization
Php Casbin
An authorization library that supports access control models like ACL, RBAC, ABAC in PHP .
Stars: ✭ 865 (+5306.25%)
Mutual labels:  roles, authorization
Laravel Auth
A powerful authentication, authorization and verification package built on top of Laravel. It provides developers with Role Based Access Control, Two-Factor Authentication, Social Authentication, and much more, compatible Laravel’s standard API and fully featured out of the box.
Stars: ✭ 128 (+700%)
Mutual labels:  roles, authorization
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 (+618.75%)
Mutual labels:  roles, authorization
Security.identity
.NET DevPack Identity is a set of common implementations to help you implementing Identity, Jwt, claims validation and another facilities
Stars: ✭ 165 (+931.25%)
Mutual labels:  roles, authorization
Think Authz
An authorization library that supports access control models like ACL, RBAC, ABAC in ThinkPHP 6.0 .
Stars: ✭ 155 (+868.75%)
Mutual labels:  roles, authorization
keycloak-restrict-client-auth
A Keycloak authenticator to restrict authorization on clients
Stars: ✭ 34 (+112.5%)
Mutual labels:  roles, authorization
Bouncer
Eloquent roles and abilities.
Stars: ✭ 2,763 (+17168.75%)
Mutual labels:  roles, authorization
HeimGuard
🛡 A simple library that allows you to easily manage permissions in your .NET projects.
Stars: ✭ 77 (+381.25%)
Mutual labels:  roles, authorization
Monarchy
Hierarchical access management system with advanced roles inheritance. 🦋
Stars: ✭ 48 (+200%)
Mutual labels:  roles, authorization
firebase-spring-boot-rest-api-authentication
Firebase Spring Boot Rest API Authentication
Stars: ✭ 172 (+975%)
Mutual labels:  roles, authorization
Accesscontrol
Role and Attribute based Access Control for Node.js
Stars: ✭ 1,723 (+10668.75%)
Mutual labels:  roles, authorization
Laratrust
Handle roles and permissions in your Laravel application
Stars: ✭ 1,799 (+11143.75%)
Mutual labels:  roles, authorization
Vue Router User Roles
A Vue.js plugin that protects routes based on user roles. Add your own authentication.
Stars: ✭ 237 (+1381.25%)
Mutual labels:  roles, authorization
auth
Authorization for humans
Stars: ✭ 49 (+206.25%)
Mutual labels:  roles, authorization
casbin-knex-adapter
Knex adapter for Casbin
Stars: ✭ 16 (+0%)
Mutual labels:  authorization

Authorization is one of laravel security features, it provides a simple way to authorize user actions, in this tutorial we'll use this feature to implement roles and abilities logic.

Content:

Installation

  • Clone the repository

  • Install composer dependancies

    composer install
    
  • Create .env file

    cp .env.example .env
    
  • Generate application key

    php artisan key:generate
    
  • Set database connection environment variable

  • Run migrations and seeds

    php artisan migrate --seed
    
  • Following are super user default credentials

    email: [email protected], password: secret

  • Following are demo user defaul credentials

    email: [email protected], password: secret

Models

Role model will group the abilities that will be granted to related users.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
    ];

    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }

    /**
     * The abilities that belong to the role.
     */
    public function abilities()
    {
        return $this->belongsToMany('App\Ability');
    }
}

Ability model represent the actions that needs to be authorized.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Ability extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
    ];

    /**
     * The roles that belong to the ability.
     */
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

Controllers

To authorize controller actions we use authorize helper method which accept the name of the ability needed to perform the action.

UserController and RoleController handles management of users and roles including relating users to roles and roles to abilities, the logic is simply made of crud actions and eloquent relationship manipulation.

Views

To display only the portions of the page that users are authorized to utilize we'll use @can and @canany blade directives.

Commands

SyncAbilities contain an indexed array of strings where each element is an ability, when exceuted it will sync the abilties in the database.

<?php

namespace App\Console\Commands;

use App\Ability;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SyncAbilities extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'abilities:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync abilities';

    /**
     * The abilities.
     *
     * @var string
     */
    protected $abilities = [
        'view-any-user', 'view-user', 'create-user', 'update-user', 'delete-user',
        'view-any-role', 'view-role', 'create-role', 'update-role', 'delete-role',
    ];

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $removedAbilities = Ability::whereNotIn('name', $this->abilities)->pluck('id');
        DB::table('ability_role')->whereIn('ability_id', $removedAbilities)->delete();
        Ability::whereIn('id', $removedAbilities)->delete();
        $presentAbilities = Ability::whereIn('name', $this->abilities)->get();
        $absentAbilities = $presentAbilities->isEmpty() ? $this->abilities : array_diff($this->abilities, $presentAbilities->pluck('name')->toArray());
        if ($absentAbilities) {
            $absentAbilities = array_map(function ($ability) {
                return ['name' => $ability];
            }, $absentAbilities);
            Ability::insert($absentAbilities);
        }
    }
}

Whenever the abilities are modifed run the following command to sync the database.

php artisan abilities:sync

CreateSuperUser will create a super user using credentials provided in config/auth.php which can be set using AUTH_SUPER_USER_EMAIL and AUTH_SUPER_USER_EMAIL environment variable, super user surpass authorization logic hence he's granted all abilities.

<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;

class CreateSuperUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'superuser:create';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create Super User';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        User::where('super', true)->delete();
        User::create([
            'email' => config('auth.super_user.email'),
            'name' => 'super',
            'super' => true,
            'password' => Hash::make(config('auth.super_user.password')),
        ]);
    }
}

Whenever the super user need to be changed, update the correspoding environment variable and run the following command which will delete the current super user and create a new one.

php artisan superuser:create

Authorization

The authorization take place in AuthServiceProvider, where we use Gate::before method to intercept gate checks then we verify if the user is super or is granted the ability through any of his roles.

use Illuminate\Support\Facades\Gate;
use Illuminate\Database\Eloquent\Builder;

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    //

    Gate::before(function ($user, $ability) {
        if ($user->super) {
            return true;
        } else {
            return $user
                ->roles()
                ->whereHas('abilities', function (Builder $query) use ($ability) {
                    $query->where('name', $ability);
                })
                ->exists();
        }
    });
}

Conclusion

Laravel has a lot to offer, having a general idea about what's provided help in finding the best solution, in this tutorial we've used Authorization and Seeders as the base of the roles and abilities system.

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].