adithwidhiantara/laravel-anyauth

Auth from Anywhere!

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/adithwidhiantara/laravel-anyauth

1.0.0 2026-01-26 08:47 UTC

This package is auto-updated.

Last update: 2026-01-26 08:51:03 UTC


README

codecov

The Flexible, Schema-Agnostic, and Multi-Provider Authorization Package for Laravel.

Laravel AnyAuth is not just another permission package. Unlike traditional solutions that force a specific database structure upon you, AnyAuth adapts to your existing database schema. It also introduces a "Virtual Provider" system, allowing you to fetch permissions from APIs, Microservices, or Config files, not just the database.

🚀 Key Features

  • Schema Agnostic: Use your existing legacy tables (user_groups, rights, etc.). No need to migrate data to new tables.
  • Multi-Provider Chain: Check permissions from multiple sources (Config -> API -> Database) in a prioritized chain.
  • Virtual Permissions: Fetch permissions from external APIs (SSO, Microservices) with built-in caching.
  • Time-Bound Roles: Assign temporary roles that expire automatically (e.g., "VIP for 7 days").
  • Role Hierarchy: Supports recursive role inheritance (Parent -> Child roles).
  • Transactional Safety: Atomic operations for assigning/removing roles.
  • Fail-Fast Architecture: Detects configuration errors immediately without crashing your runtime unnecessarily.

📦 Installation

Install the package via composer:

composer require adith-widhiantara/laravel-anyauth

Publish the configuration file (Crucial step):

php artisan vendor:publish --tag=anyauth-config

(Optional) If you don't have existing tables and want a fresh start, publish the default migrations:

php artisan vendor:publish --tag=anyauth-migrations
php artisan migrate

⚙️ Configuration (The Magic Part)

The power of AnyAuth lies in config/anyauth.php. Here you map the package logic to your database structure.

1. Mapping Your Database

If you have an existing database, simply point the config to your table names:

// config/anyauth.php

'tables' => [
    'roles' => 'master_jabatan',             // Your roles table
    'permissions' => 'master_hak_akses',     // Your permissions table
    'model_has_roles' => 'users_jabatan',    // Your pivot table
    'role_has_permissions' => 'jabatan_hak', // Your pivot table
],

'columns' => [
    'role_name' => 'nama_jabatan',           // Column for role name (e.g., 'manager')
    'permission_name' => 'kode_akses',       // Column for permission slug (e.g., 'edit-post')
    'model_morph_key' => 'user_id',          // Foreign key for User
    'role_foreign_key' => 'jabatan_id',      // Foreign key for Role
    
    // Advanced Features
    'pivot_expires_at' => 'valid_until',     // Column for expiration date (optional)
    'role_parent_key' => 'parent_id',        // Column for hierarchy (optional)
],

2. Defining Providers

You can define the order of authority. The system checks providers from top to bottom.

'providers' => [
    // 1. Check Config (God Mode)
    \AnyAuth\Providers\ConfigPermissionProvider::class,

    // 2. Check External API (Custom Provider)
    \App\Providers\YourCompanySsoProvider::class,

    // 3. Check Database (Default)
    \AnyAuth\Providers\DatabasePermissionProvider::class,
],

📖 Basic Usage

1. Setup Model

Add the HasDynamicPermissions trait to your User model.

use Illuminate\Foundation\Auth\User as Authenticatable;
use AnyAuth\Traits\HasDynamicPermissions;

class User extends Authenticatable
{
    use HasDynamicPermissions;
}

2. Checking Permissions

AnyAuth hooks directly into Laravel's Gate. You can use standard Laravel authorization methods.

// In Controller
if ($user->can('edit-post')) {
    // ...
}

// In Blade
@can('edit-post')
    <button>Edit</button>
@endcan

3. Assigning Roles (Write Access)

You can assign roles to users using the trait methods. This works regardless of your table names.

// Assign a role
$user->assignRole('manager');

// Remove a role
$user->removeRole('intern');

🔥 Advanced Features

⏳ Time-Bound Permissions (Temporary Access)

Give a user a role for a specific duration. Once the time passes, can() will automatically return false.

// Grant 'editor' role for 7 days only
$user->assignRole('editor', now()->addDays(7));

Note: Ensure your pivot table has the expiration column defined in config/anyauth.php.

🌳 Role Hierarchy

If your roles table has a parent-child relationship (e.g., parent_id), AnyAuth can resolve permissions recursively.

  • Scenario: Director is parent of Manager. Manager is parent of Staff.
  • Result: A user assigned as Director automatically inherits all permissions from Manager and Staff.

Enable this in config:

'settings' => [
    'enable_hierarchy' => true,
],

⚡ Super Admin (God Mode)

You can define emails that have access to everything, bypassing database checks. Useful for developers.

// config/anyauth.php
'super_admins' => [
    'dev@yourcompany.com',
    'root@localhost',
],

🔌 Virtual Providers (External APIs)

Need to check permissions from an external Microservice or SSO? You don't need to sync data to your local database. Use a Virtual Provider.

1. Generate a Provider

Run the artisan command to create a boilerplate provider:

php artisan anyauth:make-provider YourCompanySsoProvider

2. Implement Logic

Edit app/Providers/YourCompanySsoProvider.php. AnyAuth handles caching automatically for you!

namespace App\Providers;

use AnyAuth\Providers\AbstractApiPermissionProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\Http;

class YourCompanySsoProvider extends AbstractApiPermissionProvider
{
    protected function fetchPermissions(Authenticatable $user): array
    {
        // Example: Call external API
        $response = Http::withToken($user->token)->get('https://api.internal.com/my-access');
        
        // Return simple array of permission strings
        // e.g., ['can_edit', 'can_delete']
        return $response->json('data.permissions', []);
    }
}

3. Register It

Add your new class to the providers array in config/anyauth.php.

🧠 Architecture Concepts

Chain of Responsibility

AnyAuth uses a prioritized chain. Each provider returns one of three states:

  1. TRUE: Access Granted. Stop checking.
  2. FALSE: Access Denied. Stop checking.
  3. NULL: Neutral / Abstain. Continue to the next provider.

Performance

  • No Eloquent Overhead: Database checks use raw fluent queries (DB::table), making it significantly faster than loading Eloquent models.
  • Auto-Caching: API Providers implement automatic caching (TTL configurable) to prevent slowing down your request lifecycle.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

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