Hierarchical Rol-Permission Based Laravel Auth Package with Limitless Hierarchical Level of Organizations

Overview

AAuth for Laravel

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Hierarchical Rol-Permission Based Laravel Auth Package with Limitless Hierarchical Level of Organizations

Features

  • Organization Based Access Controllable (OrBAC) Eloquent Models
  • Role Based Access Control (RoBAC)
  • Permissions Based Access Control
  • Lean & Non-Complex Architecture
  • PolyMorphic Relationships of Model & Organization Node
  • Built-in Blade Directives for permission control inside Blade files
  • Mysql, MariaDB, Postgres Support
  • Community Driven and Open Source Forever

Installation

You can install the package via composer:

composer require aurorawebsoftware/aauth

You must add AAuthUser Trait to the User Model.

use Illuminate\Foundation\Auth\User as Authenticatable;
use AuroraWebSoftware\AAuth\Traits\AAuthUser;

class User extends Authenticatable
{
    use AAuthUser;

    // ...
}

You can publish and run the migrations with:

php artisan migrate

You can publish the sample data seeder with:

php artisan vendor:publish --tag="aauth-seeders"
php artisan db:seed --class=SampleDataSeeder

Optionally, You can seed the sample data with:

php artisan db:seed --class=SampleDataSeeder

You can publish the config file with:

php artisan vendor:publish --tag="aauth-config"

This is the example contents of the published config file:

return [
    'permissions' => [
            'system' => [
                'edit_something_for_system' => 'aauth/system.edit_something_for_system',
                'create_something_for_system' => 'aauth/system.create_something_for_system',
            ],
            'organization' => [
                'edit_something_for_organization' => 'aauth/organization.edit_something_for_organization',
                'create_something_for_organization' => 'aauth/organization.create_something_for_organization',
            ],
        ],
];

Main Philosophy

In computer system security, there are several approaches to restrict system access to authorized users.

Most used and known access control method is Rol Based Access Control (RoBAC).

In most circumstances, it's sufficient for software projects. Basically; Roles and Permissions are assigned to the Users, The data can be accessed horizontally as single level

What if your data access needs are further more than one level? and what if you need to restrict and filter the data in organizational and hierarchical manner?

Let's assume we need to implement a multi-zone, multi-level school system and be our structure like this.

  • Türkiye
    • A High School
      • Class 1A
      • Class 2A
    • B High School
      • Class 1A
  • Germany
    • X High School
      • Class 1B
      • Class 2B

How can you restrict A High School's data from X High School Principal and Teachers?

How can you give permissions to a Class Teacher to see their students only ?

What if we need another level of organization in the future like this? and want to give access to see students data under their responsibility only for Europe Zone Principal, Türkiye Principal dynamically without writing one line of code?

  • Europe
    • Türkiye
      • A High School
        • Class 1A
        • Class 2A
      • B High School
        • Class 1A
    • Germany
      • X High School
        • Class 1B
        • Class 2B
  • America
    • USA
      • ....
      • ....
    • Canada
      • .....

AAuth may be your first class assistant package.


If you don't need organizational roles, AAuth may not be suitable for your work.


AAuth Terminology

Before using AAuth its worth to understand the main terminology of AAuth. AAuth differs from other Auth Packages due to its organizational structure.

What is Organization?

Organization is a kind of term which refers to hierarchical arrangement of eloquent models in sequential tree.

It consists of a central root organization node, and sub organization nodes, which are connected via edges. We can also say that organization tree has one root node, many sub organization nodes polymorphic-connected with one eloquent model.

Organization Scope

In Organization Tree, each node has an organization scope. Organization scope has a level property to determine the level of the organization node in the tree.

Organization Node

Each node in the organization tree means organization node. Each Organization Node is an Eloquent Model. Organization Node can be polymorphic-related with an Eloquent Model.

Permission

In This Package there are 2 types of Permissions.

  1. System Permissions
  2. Organization Permissions

System Permission is plain permission non-related to the organization which is useful for system related access controls like backup_db, edit_website_logo, edit_contact_info etc.. A System permission can only be assigned to a System Role. System Permissions should be added inside aauth.php config file's permission['system'] array.

Organization Permission is hierarchical controllable permission. An Organization permission can only be assigned to an Organization Role. Organization Permissions should be added inside aauth.php config file's permission['organization'] array.

Role

Roles are assigned to users. Each User can have multiple roles.

In This Package there are 2 types of Roles.

  1. System Roles
  2. Organization Roles

System Role is plain role for non-related to the organization which is useful for system related users like system admin, super admin etc..

Organization Role is hierarchical position of a User in Organization Tree. An Organization Role can be assigned to a user with 3 parameters.

  • user_id (related user's id)
  • role_id
  • organization_node_id (id of the organization node which defines the position of the user's role on the organization Tree)

! it can be a little overwhelming at the first, but it is not complex lol. :)

User

Just a usual Laravel User. AAuthUser trait must be added to Default User Model.

Permission Config File

Permissions are stored inside config/aauth.php which is published after installing.

Model - Organization Node Relations

Each Organization Node can have a polymorphic relationship with an Eloquent Model. By doing this, an Eloquent Model can be an organization node and can be access controllable.

It means that; Only Authorized User Role can be access the relating model, or in other words, Each role only can access the models which is on Authenticated Sub-Organization Tree of User's Role.

Usage

Before using this, please make sure that you published the config files.

AAuth Services, Service Provider and roleId Session and Facade

AAuth Services are initialized inside AAuthService Provider.

roleId session must be set before initializing AAuth Service. AAuthServiceProvider.php

$this->app->singleton('aauth', function ($app) {
    return new AAuth(
        Auth::user(),
        Session::get('roleId')
    );
});

there is also a AAuth Facade to access AAuth Service class statically. Example;

AAuth::can();

OrganizationService

Organization Service is used for organization related jobs. The service can be initialized as

$organizationService = new OrganizationService()

or via dependency injecting

public function index(OrganizationService $organizationService)
{
    .....
}

Creating an Organization Scope

$data = [
    'name' => 'Org Scope1',
    'level' => 5,
    'status' => 'active',
];

$organizationService->createOrganizationScope($data);

Updating an Organization Scope

the contributors' space

Deleting an Organization Scope

the contributors' space

Creating an Organization Node without Model Relationship

$orgScope = OrganizationScope::first();

$data = [
    'name' => 'Created Org Node 1',
    'organization_scope_id' => $orgScope->id,
    'parent_id' => 1,
];

$organizationService->createOrganizationNode($data);

Updating an Organization Node

the contributors' space

Deleting an Organization Node

the contributors' space

Role Permission Service

This Service is used for role related jobs. The service can be initialized as

$rolePermissionService = new RolePermissionService()

or via dependency injecting

public function index(RolePermissionService $rolePermissionService)
{
    .....
}

Creating a Role

$organizationScope = OrganizationScope::whereName('Root Scope')->first();

$data = [
    'organization_scope_id' => $organizationScope->id,
    'type' => 'system',
    'name' => 'Created System Role 1',
    'status' => 'active',
];

$createdRole = $rolePermissionService->createRole($data);

Updating a Role

...

Deleting a Role

....

Attaching a Role to a User

$role = Role::whereName('System Role 1')->first();
$permissionName = 'test_permission1';

$rolePermissionService->attachPermissionToRole($permissionName, $role->id);

Syncing All Permissions for a Role

$role = Role::whereName('System Role 1')->first();
$permissionName1 = 'test_permission1';
$permissionName2 = 'test_permission2';
$permissionName3 = 'test_permission3';

$rolePermissionService->syncPermissionsOfRole(
    compact('permissionName1', 'permissionName2', 'permissionName3'),
    $role->id
);

Detaching Permission from a Role

$rolePermissionService->detachSystemRoleFromUser($role->id, $user->id);

Creating an Organization Role and Attaching to a User

$organizationScope = OrganizationScope::whereName('Root Scope')->first();
$organizationNode = OrganizationNode::whereName('Root Node')->first();

$data = [
    'organization_scope_id' => $organizationScope->id,
    'type' => 'organization',
    'name' => 'Created Organization Role 1 for Attaching',
    'status' => 'active',
];

$createdRole = $rolePermissionService->createRole($data);
$rolePermissionService->attachOrganizationRoleToUser($organizationNode->id, $createdRole->id, $user->id);

Creating a System Role and Attaching to a User

....

Using AAuth Interface and Trait with Eloquent Models

To turn an Eloquent Model into an AAuth Organization Node; Model must implement AAuthOrganizationNodeInterface and use AAuthOrganizationNode Trait. After adding AAuthOrganizationNode trait, you will be able to use AAuth methods within the model

namespace App\Models\ExampleModel;

use AuroraWebSoftware\AAuth\Interfaces\AAuthOrganizationNodeInterface;
use AuroraWebSoftware\AAuth\Traits\AAuthOrganizationNode;
use Illuminate\Database\Eloquent\Model;

class ExampleModel extends Model implements AAuthOrganizationNodeInterface
{
    use AAuthOrganizationNode;
    
    // implementation
}

AAuth Service and Facade Methods

Current Roles All Permissions

current user's selected roles permissions with AAuth Facade

$permissions = AAuth::permissions();

Check allowed permission with can() method

AAuth::can('create_something_for_organization');
if (AAuth::can('create_something_for_organization')) {
    // codes here
}

Check permission and abort if not user and current allowed

AAuth::passOrAbort('create_something_for_organization');

Get all permitted organization nodes

it will return OrganizationNode collection.

organizationNodes(bool $includeRootNode = false, ?string $modelType = null): \Illuminate\Support\Collection

$organizationNodes = AAuth::organizationNodes();

Get one specified organization node

.....

Descendant nodes can be checked

with this method you can check is a organization node is descendant of another organization node. in other words, checks if node is sub-node of specified node.

$isDescendant = AAuth::descendant(1, 3);

Creating an Organization Node-able Model and Related Org. Node

with this method, you can create a model and organization node with relationship together.

$data = ['name' => 'Test Organization Node-able Example'];

$createdModel = ExampleModel::createWithAAuthOrganizationNode($data, 1, 2);

Getting Related Organization Node of Model

$exampleModel = ExampleModel::find(1);
$relatedOrganizationModel = $exampleModel->relatedAAuthOrganizationNode()

Getting allowed Organization Nodes Only.

after adding AAuthOrganizationNode trait to your model, you are adding a global scope which filters the permitted data.

Thus you can simply use any eloquent model method without adding anything

ExampleModel::all();

Getting All Model Collection without any access control

ExampleModel::withoutGlobalScopes()->all()

that's all.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

// todo ? Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Dynamic ACL is a package that handles Access Control Level on your Laravel Application.

Dynamic ACL Dynamic ACL is a package that handles Access Control Level on your Laravel Application. It's fast to running and simple to use. Install an

Light-weight role-based permissions system for Laravel 6+ built in Auth system.

Kodeine/Laravel-ACL Laravel ACL adds role based permissions to built in Auth System of Laravel 8.0+. ACL middleware protects routes and even crud cont

Configurable Basic Auth based on Pimcore Documents

CORS Property Basic Auth This bundles allows to add basic auth based on Properties on Pimcore Documents. Simply use these properties password_enabled

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.
Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system. Built on Bootstrap 4.

Set up Laravel Auth guards using Eloquent in seconds

Nightguard Set up Auth guards using Eloquent in seconds. Introduction Laravel guards provide a super convenient way of authorizing different areas of

Laravel starter kit with Livewire & Bootstrap 5 auth scaffolding.

Laravel Livewire Auth Laravel starter kit with Livewire & Bootstrap 5 auth scaffolding. Requirements NPM Installation Create a new Laravel app: larave

JWT auth for Laravel and Lumen
JWT auth for Laravel and Lumen

JWT Artisan Token auth for Laravel and Lumen web artisans JWT is a great solution for authenticating API requests between various services. This packa

Comments
Releases(1.1.1)
Owner
Aurora Web Software Team
Aurora Web Software Team
CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

Cake Development Corporation 24 Sep 23, 2022
A Native PHP MVC With Auth. If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo.

If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo. Auth system is implemented. Works with bootstrap 5. Composer with autoload are implemented too for future composer require.

null 2 Jun 6, 2022
This package helps you to associate users with permissions and permission groups with laravel framework

Laravel ACL This package allows you to manage user permissions and groups in a database, and is compatible with Laravel v5.8 or higher. Please check t

Mateus Junges 537 Dec 28, 2022
User role and Permission Management system with Paticie package

User role and Permission Management system with Paticie package Installation instruction Download or git clone https://github.com/KKOO727/User-role-ma

Ninja 2 Mar 4, 2022
The easiest and most intuitive way to add access management to your Filament Resource Models through `spatie/laravel-permission`

Filament Shield The easiest and most intuitive way to add access management to your Filament Resource Models (more coming soon ?? ) One Plugin to rule

Bezhan Salleh 329 Jan 2, 2023
permission generation for all your declared routes with corresponding controller action

Permissions Generator This package add some artisan command to help generating permissions for your declared routes. Each route should have an alias (

Diagana Mouhamed Fadel 4 Nov 30, 2022
A user, group, role and permission management for Codeigniter 4

CI4-Auth CI4-Auth is a user, group, role and permission management library for Codeigniter 4. CI4-Auth is based on the great Myth-Auth library for Cod

George Lewe 15 Dec 16, 2022
Nginx FastCGI Fix Permission

Nginx FastCGI Fix Permission Table of Contents About How it works Installation Changelog Contributing License About This library was born with the obj

Ejetar 3 Mar 14, 2022
Yet another asynchronous permission management plugin for PocketMine-MP.

GroupsAPI Yet another asynchronous permission management plugin for PocketMine-MP. Features Developer-friendly API Temporary rank/group support Multip

null 19 Nov 28, 2022
Tools for checking malware, permission of file php and any on website

webtools Tools for checking malware, permission of file php and any on website You can use the webtools.php file directly. All features can be accesse

ForDeveloperTools 3 Jun 14, 2022