GithubHelp home page GithubHelp logo

chiiya / filament-access-control Goto Github PK

View Code? Open in Web Editor NEW
187.0 4.0 24.0 295 KB

Admin user, role and permission management for Laravel Filament

License: MIT License

PHP 97.15% Blade 2.67% Just 0.18%
php laravel filament permissions roles

filament-access-control's Introduction

filament-access-control

Filament Access Control

Latest Version on Packagist GitHub Code Style Action Status Total Downloads

Opinionated setup for managing admin users, roles and permissions within Laravel Filament

Features

  • Separate database table for filament admin users (separate model, separate guard, separate password broker)
  • Uses spatie/laravel-permission for roles and permissions
  • Fully localized
  • CRUD resources for admin users, roles and permissions
  • Admin users may belong to one role
  • Admin users can have direct permissions or indirect permissions through their role
  • When creating admin users through the admin interface, no password is specified. Instead, the user receives an email prompting them to set their password
  • Optional account expiry for admin users. Expired accounts are no longer able to log in
  • Optional email based two-factor authentication.

Installation

  1. Install the package via composer:
composer require chiiya/filament-access-control
  1. Update your Filament Panel ServiceProvider and register the plugin:
use Chiiya\FilamentAccessControl\FilamentAccessControlPlugin;

return $panel
    ->default()
    ->id('admin')
    ->path('admin')
    ->plugin(FilamentAccessControlPlugin::make())

You may remove any calls to login() or other methods that configure the authentication process, since the plugin takes care of that.

  1. Publish the migrations and config, then run the migrations. Make sure you also publish and run the spatie/laravel-permission migrations if you haven't done so yet.
php artisan vendor:publish --tag="filament-access-control-migrations"
php artisan vendor:publish --tag="filament-access-control-config"
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate
  1. To seed the necessary base data (role & permissions), run php artisan filament-access-control:install or call the Chiiya\FilamentAccessControl\Database\Seeders\FilamentAccessControlSeeder seeder in your database seeder.

  2. Create an admin user using php artisan filament-access-control:user. If you create users programmatically (e.g. in your database seeder), make sure to assign them the super-admin role if you want them to be able to access the role and user management.

Optionally, you can publish the translations with:

php artisan vendor:publish --tag="filament-access-control-translations"

Optionally, you can publish the views with:

php artisan vendor:publish --tag="filament-access-control-views"

Usage

Authorizing Resources, Pages & Actions

Authorizing Resources

To authorize access to resources, use policies as described in the Filament documentation.

class ProductPolicy
{
    public function viewAny(FilamentUser $user): bool
    {
        return $user->can('products.view');
    }
    
    // ...
}

Authorizing Pages

This package comes with a simple trait that you can use to authorize access to custom pages based on a permission.

use Chiiya\FilamentAccessControl\Traits\AuthorizesPageAccess;

class MyPage extends Page
{
    use AuthorizesPageAccess;
    
    public static string $permission = 'my-page.view';
    
    public function mount(): void
    {
        static::authorizePageAccess();
    }
}

Authorizing Actions

One way to authorize actions is to use the visible() method:

ButtonAction::make('exports')
    ->visible(fn () => Filament::auth()->user()->can('exports.view'))

Localizing Role & Permission Names

Roles and permissions should have names that make them easy to use in code (e.g. admin-users.update). For the admin you may however wish to localize them or make them more readable. You can do so by simply adding a JSON translation entry for the given role or permission name (e.g. lang/en.json):

{
    "admin-users.update": "Admin Users → Edit"
}

Feature: Account Expiry

With the optional account expiry feature, all accounts require an expiration date. When accounts are expired, they can no longer log in. To enable the account expiry feature, enable the feature flag in the config file:

'features' => [
    \Chiiya\FilamentAccessControl\Enumerators\Feature::ACCOUNT_EXPIRY,
],

You will also need to add the EnsureAccountIsNotExpired middleware to your filament auth middleware config in your panel service provider:

use Chiiya\FilamentAccessControl\Http\Middleware\EnsureAccountIsNotExpired;

...
->authMiddleware([
    Authenticate::class,
    EnsureAccountIsNotExpired::class,
]);

Feature: Two-Factor Authentication

With the optional two-factor authentication feature, users must enter a verification code sent via email upon login. To enable the two-factor authentication feature, enable the feature flag in the config file:

'features' => [
    \Chiiya\FilamentAccessControl\Enumerators\Feature::TWO_FACTOR,
],

Custom User Model

To use your own custom user model for the admin (instead of Chiiya\FilamentAccessControl\Models\FilamentUser), point the value of user_model in the filament-access-control config file to your own model.

'user_model' => CustomFilamentUser::class,

Please make sure that your model either extends the FilamentUser base case or implements the Chiiya\FilamentAccessControl\Contracts\AccessControlUser interface.

use Chiiya\FilamentAccessControl\Models\FilamentUser;
use Chiiya\FilamentAccessControl\Contracts\AccessControlUser;
use Filament\Models\Contracts\FilamentUser as FilamentUserInterface;
use Filament\Models\Contracts\HasName;
use Illuminate\Foundation\Auth\User as Authenticatable;

class CustomFilamentUser extends FilamentUser
{
    // ...
}

// Or alternatively
class CustomFilamentUser extends Authenticatable implements AccessControlUser, FilamentUserInterface, HasName
{
    // ...
}

Extending Resources

To extend the resources used for managing admin users, roles and permissions, you can adjust the resources config value:

    /*
    |--------------------------------------------------------------------------
    | Resources
    |--------------------------------------------------------------------------
    | Resources used for managing users, roles and permissions.
    */
    'resources' => [
        'user' => FilamentUserResource::class,
        'role' => RoleResource::class,
        'permission' => PermissionResource::class,
    ]

The easiest way to extend the resources is to create your own resource classes that extend the default ones, and overwrite the following methods:

    public static function insertBeforeFormSchema(): array
    {
        return [];
    }

    public static function insertAfterFormSchema(): array
    {
        return [];
    }

    public static function insertBeforeTableSchema(): array
    {
        return [];
    }

    public static function insertAfterTableSchema(): array
    {
        return [];
    }

Screenshots

Screenshot of Admin Users - View Screenshot of Roles - Edit Screenshot of Account Expired Screenshot of Two-Factor Authentication

Changelog

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

Contributing

Please see CONTRIBUTING for details.

License

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

filament-access-control's People

Contributors

bashgeek avatar chiiya avatar dependabot[bot] avatar github-actions[bot] avatar halowahyudi avatar jemcdo avatar magarrent avatar shibomb avatar stephenjude avatar vzool avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

filament-access-control's Issues

Custom FilamentUser class

This is really a requested feature, not a bug report (getting 404 when trying to create a request feature post). It would be great if the package user could specify what class to use in the config file so we could add our own traits (among other things) to it in order to extend the functionality.

Optionally enabling 2FA per user

Would you consider adding an option for toggling 2FA on or off on a per-user-basis?

So, "User A" might have 2FA enabled and will be prompted to confirm the code as how you've got it now. However, "User B" might have 2FA disabled and after logging in, will be logged straight in.

I can create a PR if you're open to this feature request.

Cannot Create User On Filament Admin

When creating users through the filament form in the admin panel, you cannot create a new user unless you assign them no role.
You have to save the user without, then edit the role after save.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'model_id' cannot be null (Connection: mysql, SQL: insert into `model_has_roles` (`model_id`, `model_type`, `role_id`) values (?, Chiiya\FilamentAccessControl\Models\FilamentUser, 2))

php artisan optimize command fails

I ran

php artisan optimize which is also run php artisan config:cache as part of it's commands.

on my terminal and i got a LogicException:

`LogicException : Your configuration files are not serializable.

at C:\xampp\htdocs{PROJECT}\vendor\laravel\framework\src\Illuminate\Foundation\Console\ConfigCacheCommand.php:68

64| require $configPath;
65| } catch (Throwable $e) {
66| $this->files->delete($configPath);
67|
68| throw new LogicException('Your configuration files are not serializable.', 0, $e);
69| }
70|
71| $this->info('Configuration cached successfully!');
72| }

Exception trace:

1 Error::("Call to undefined method Closure::__set_state()")
C:\xampp\htdocs{PROJECT}\bootstrap\cache\config.php:241

2 require()
C:\xampp\htdocs{PROJECT}\vendor\laravel\framework\src\Illuminate\Foundation\Console\ConfigCacheCommand.php:64

Please use the argument -v to see more details.`

after doing some debugging and search on what the error was i came across this post on stackoverflow that explains what might be causing this error.

and after searching i found what I feel is the cause:
/* |-------------------------------------------------------------------------- | Password Rules |-------------------------------------------------------------------------- | Rules for the password set during the passwort reset flow. */ 25| 'password_rules' => [Password::min(8)],

in the config file of the package at vendor\chiiya\filament-access-control\config\filament-access-control.php

reason for error:

Closure serialization is not allowed in Laravel and PHP at large. Look through your configuration files for any file where you used Closures and rewrite that piece of code using traditional functions.

Compatibility with filament-logger

In order for the activity log exposed by filament-logger to show users managed by this package, the FilamentUser model needs a method like so:

    /**
     * Return a name.
     *
     * Needed for compatibility with filament-logger.
     */
    public function getNameAttribute(): string
    {
        return $this->getFilamentName();
    }

It's a really minor thing, but it ensures that the user who caused an event is clearly visible.

Custom User model causes Adminsitration menu to be lost

To implement Laravel Sanctum and specifically the Filament Sanctum plugin (https://github.com/devtical/filament-sanctum) I need to add the HasApiTokens trait to the FilamentUser model.

I have tried the two approaches supported for custom user models, but the simplest for me is to use extend the FilamentUser base class. This works fine, however, as soon as I set a custom user_model class in the configuration, the entire "Administration" section in the side panel disappears. It seems the FilamentUserResource is only rendering properly when the original user model is specified.

Sanctum FilamentUser Error

Good afternoon everyone; The system presents an error when api sanctum token is requested for administrative users, as shown in the image below:

image

The resolution is to add the HasApiToken in the Model FilamentUser. As the default installation of Laravel 9x Sanctum is installed I will upload a PR correcting it and adding it to the Model.

Filament 3.* support

Project looks very intense and it says it requires filament ^3.0 but it is not supporting right now. You can clearly see when you install it. It tries to go to a function named getDomains which is removed in filament 3.*.
Have a nice day!

Missing notification on forgotten password screen

Hi,

on route /admin/password/request after you submit your email, there is no notification that the email was sent and also the email stays in the form - probably should be cleared.

Thanks for a nice package.

[ISSUE] Spatie\Permission\Exceptions\GuardDoesNotMatch with message 'The given role or permission should use guard `web` instead of `filament`.'

>>> $user = User::find(11);
=> App\Models\User {#5313
     id: 11,
     email: "[email protected]",
     #password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
     first_name: "مستخدم",
     last_name: "للإختبار",
     expires_at: null,
     two_factor_expires_at: null,
     two_factor_code: null,
     #remember_token: "NkUmKbJWD0j827WHpgFPBc5DkFCgdvNIh07mbxTaBlP9SB8pEYyzXrtAKPYL",
     created_at: "2022-10-04 02:15:20",
     updated_at: "2022-10-04 02:15:20",
   }

>>> $role = Spatie\Permission\Models\Role::first()
=> Spatie\Permission\Models\Role {#5300
     id: 1,
     name: "super-admin",
     guard_name: "filament",
     created_at: "2022-10-04 03:41:23",
     updated_at: "2022-10-04 03:41:23",
   }

>>> $user->assignRole($role);
Spatie\Permission\Exceptions\GuardDoesNotMatch with message 'The given role or permission should use guard `web` instead of `filament`.'
>>> 

How this can be resolved?

Argument #1 ($user) must be of type FilamentUser

Chiiya\FilamentAccessControl\Policies\FilamentUserPolicy::viewAny(): Argument #1 ($user) must be of type Chiiya\FilamentAccessControl\Models\FilamentUser, App\Models\User given, called in

i have already updated filament config file auth.pages.login value with \Chiiya\FilamentAccessControl\Http\Livewire\Login::class

Adding this plugin to filamentphp.com

Hey! Hope you don't mind me opening an issue about this. I'm one of the maintainers of Filament.

Today, we're launching a new Plugins list on filamentphp.com, and I'd love to see this plugin alongside our others. Hopefully it will serve as great advertising for your work, to our community.

If you'd like to submit your plugin, create an account here. If you're not interested, feel free to close this issue, no hard feelings :)

Dan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.