Giter Site home page Giter Site logo

filament-authentication's Introduction

Latest Version on Packagist Semantic Release Total Downloads

Filament User Authentication

User Resource For Filament Admin along with Roles & Permissions using Spatie

Package Installation

You can install the package via composer:

composer require phpsa/filament-authentication

and run the install command

php artisan filament-authentication:install

this will publish the config file and migrations

optionally publish views / translations

artisan vendor:publish --tag=filament-authentication-views
artisan vendor:publish --tag=filament-authentication-translations

Spatie Roles & Permissions

If you have not yet configured this package it is automatically added by this installer, run the following steps:

  1. You should publish the migration and the config/permission.php config file with:
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate
  1. Add the Spatie\Permission\Traits\HasRoles trait to your Users model

  2. Add Roles & Permissions as required

For more see: https://spatie.be/docs/laravel-permission/v6/introduction

Setup & Config

in your Filament panel file you need to add the following to the Plugins section

add the resources

 public function panel(Panel $panel): Panel
    {
        return $panel
            ...
            ->plugins([
                \Phpsa\FilamentAuthentication\FilamentAuthentication::make(),
            ])
            ...

You can configure this via either the config file or the plugin.

Features

1. Widgets

LatestUsersWidget can be added to your dashboard by adding it to your panel widgets area..

 LatestUsersWidget::class

Note that it is also attached to the UserPolicy::viewAny policy value if the policy exists

2. Laravel Impersonate

If you have not configured this package it is automatically added by this install, run the following steps:

  1. Add the trait Lab404\Impersonate\Models\Impersonate to your User model.
  2. edit the config file and set impersonate->enabled to true

Defining impersonation authorization

By default all users can impersonate an user. You need to add the method canImpersonate() to your user model:

    /**
     * @return bool
     */
    public function canImpersonate()
    {
        // For example
        return $this->is_admin == 1;
    }

By default all users can be impersonated. You need to add the method canBeImpersonated() to your user model to extend this behavior:

    /**
     * @return bool
     */
    public function canBeImpersonated()
    {
        // For example
        return $this->can_be_impersonated == 1;
    }

Protect From Impersonation

You can use the middleware impersonate.protect to protect your routes against user impersonation. This middleware can be useful when you want to protect specific pages like users subscriptions, users credit cards, ...

Router::get('/my-credit-card', function() {
    echo "Can't be accessed by an impersonator";
})->middleware('impersonate.protect');

Events There are two events available that can be used to improve your workflow:

  • TakeImpersonation is fired when an impersonation is taken.
  • LeaveImpersonation is fired when an impersonation is leaved.

Each events returns two properties $event->impersonator and $event->impersonated containing User model instance.

3. Password Renewal

Introduced in V4.2.0 - this allows you to enforce a user to change their password every X days.

Enable this & configure this as Follows:

  1. add the Phpsa\FilamentAuthentication\Traits\CanRenewPassword trait to your user model
  2. configure the options for pruning and renewal day period in the config file
  3. if not published, publish migration artisan vendor:publish --tag filament-authentication-migrations

this will force a user to update their password, note -- all existing users will initially be foreced to, this can be ignored by running the following command:

Authentication Log

Introduced in V4.2.0 - this allows you to log each user login attempt.

Enable this & configure this as follows:

  1. add the Phpsa\FilamentAuthentication\Traits\LogsAuthentication trait to your user model
  2. configure the options for prune in the authentication_log section of the config
  3. optionally enable the resource in navigation section of the config file.
  4. if not published, publish migration artisan vendor:publish --tag filament-authentication-migrations

this will now log login and logouts on the system.

Security

Roles & Permissions can be secured using Laravel Policies, create your policies and register then in the AuthServiceProvider

 protected $policies = [
        Role::class       => RolePolicy::class,
        Permission::class => PermissionPolicy::class,
        CustomPage::class => CustomPagePolicy::class,
        SettingsPage::class => SettingsPagePolicy::class
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

We have a Custom Page Trait: Phpsa\FilamentAuthentication\Traits\PagePolicyTrait and a Spatie Settings Page Trait Phpsa\FilamentAuthentication\Traits\SettingsPage\PolicyTrait that you can add to your pages / settings pages. By defining a model and mapping it with a viewAny($user) method you can define per policies whether or not to show the page in navigation.

Events

Phpsa\FilamentAuthentication\Events\UserCreated is triggered when a user is created via the Resource

Phpsa\FilamentAuthentication\Events\UserUpdated is triggered when a user is updated via the Resource

Future Plans

  • MFA Authentication
  • Socialite Authentication
  • Biometrics Athentication

Changelog

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

Credits

License

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

filament-authentication's People

Contributors

chengkangzai avatar craigatcd avatar danie1net0 avatar datlechin avatar dpetrovaliev avatar eelco2k avatar falconnl93 avatar moskoweb avatar nguyentranchung avatar phpsa avatar rickatcd avatar semantic-release-bot avatar shibomb avatar tiagof avatar z4nder 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  avatar  avatar  avatar  avatar  avatar

filament-authentication's Issues

Class "App\Models\User" not found

Hello,

I do not use the User inside the folder, because it is an older project, and even defining the right path in the configuration file, it gives an error when accessing the users page.

How to correct? And how to set permission of who can access the pages?

Email confirmation

Is there any option to send an email confirmation to the user after creating the account?

Handle teams

Hi @phpsa ,

Is there any option to handle teams with this package (I can't find any things about teams in the documentation)?

thanks for your reply, best regards:
Peter

modify role CRUD

I want to add extra field to roles and accordingly modify role create form and roles save update (Controller)

Double Entry in navigation menu

Hello,
After I successfully installed this plugin, It was working fine with default user model. but when I create UserResource again, the double entry is displaying as in screenshot. It may be my fault also. can you please guide me please. I want only one user menu item in the navigation group.
Screenshot 2022-10-18 182222

select only one role ?

hi

thanks for your work

if there any method to force the selection of only one role ?
i tried to change the BelongsToManyMultiSelect to BelongsToSelect but i get a error

TypeError
PHP 8.1.2
9.11.0
Filament\Forms\Components\BelongsToSelect::getRelationship(): Return value must be of type ?Illuminate\Database\Eloquent\Relations\BelongsTo, Illuminate\Database\Eloquent\Relations\MorphToMany returned

Role not assigned in User

Hello,

I installed the package in a project, and to my surprise, the role assigned to users before installing the package disappeared from all users, the package seems not to have recognized the roles that users had before installing it, and so, the users became permissions.

Needing to assign permissions again to each user, would you like to understand if it's a configuration error, or is it really necessary to reassign the roles?

Captura de Tela 2023-06-22 aΜ€s 12 05 57

ImpersonateLink return error

The return type of ImpersonateLink:: impersonate() is wrong, getting this error
"Phpsa\FilamentAuthentication\Actions\ImpersonateLink::impersonate(): Return value must be of type Livewire\Redirector|Illuminate\Http\RedirectResponse|bool, Livewire\Features\SupportRedirects\Redirector returned"

usage question

hi

could you please some usage examples in the documentation.

i understand how to use model policies but how i could protect filament resources that don't have models ?
traing to block access to the route of this package for example https://github.com/z3d0x/filament-logger

sorry if i don't make much sense i'm new to laravel and filament and learning

thanks in advance for your help

Undifined Method resources()

i got this error when i wanted to load resources as document :
Call to undefined method Phpsa\FilamentAuthentication\FilamentAuthentication::resources() {"exception":"[object] (Error(code: 0): Call to undefined method Phpsa\\FilamentAuthentication\\FilamentAuthentication::resources() at ***/public_html/app/Providers/Filament/AdminPanelProvider.php:37)

How to selectively hide navigation?

Hi,
Is there a way that I can selectively show/hide the navigation group? For example, if a user belongs to admin, then show navigation, otherwise hide it.

Also is it possible to move the navigation to the bottom instead?

Screenshot 2023-02-19 at 5 35 18 PM

Custom UserResource

I try to change the UserResource class to modify the tables elements, but always return the default table.

In the config file put that

use App\Filament\Resources\MyUserResource;
// ...
return [
    'resources' => [
        'UserResource' => MyUserResource::class,
        'RoleResource' => \Phpsa\FilamentAuthentication\Resources\RoleResource::class,
       'PermissionResource' => \Phpsa\FilamentAuthentication\Resources\PermissionResource::class,
    ],
    'pages' => [
        'Profile' => \Phpsa\FilamentAuthentication\Pages\Profile::class
    ],
    'user_timezone' => 'Pacific/Auckland',
    'preload_roles' => true

And modify the table method, but always get the original table

Error on new user

Getting this error when pressing the "new user" button in the user screen.

Filament\Support\Services\RelationshipJoiner::prepareQueryForNoConstraints(): Argument #1 ($relationship) must be of type Illuminate\Database\Eloquent\Relations\Relation, null given, called in C:\Websites\SDA2.0\SDA\vendor\filament\forms\src\Components\Select.php on line 773

When pressing "view" or "edit" in the user list this error comes: Call to a member function getResults() on null

PHP 8.3.2
10.43.0

phpsa attach permission dialog bug

dialog closes itself when attach permission or role.
in the browser console there is the following error log:

select.js?v=3.2.27.0:1 Uncaught (in promise) Could not find Livewire component in DOM tree
(anonymous) @ select.js?v=3.2.27.0:1
await in (anonymous) (async)
(anonymous) @ livewire.js?id=a27c4ca2:815

Screen.Recording.2024-02-09.at.10.40.30.mov

Typo in readme

Under Package Installation

This line:
php artisan filament-authentication::install

has double ':', and should be changed to:
php artisan filament-authentication:install

remove LatestUsersWidget ?

hi

i didn't add the class to filament.php widgets register i removed it from filament-authentication.php and it still appears in the admin any idea how i could get rid of it ?

Forgot and reset Password

I just noticed there is no reset password functionality, is there a plan to add it later on?

thanks

Track password history

As a system admin I want to prevent a user from reusing the same 2 passwords every set amount of time.

Background
I want the user to update their password every 90 days. The current behaviour is that the user can save its password to "password" and then after 90 days to "password1" and then back again to "password".

Allow an setting config to track the last X passwords, so when a user updates the password, the system will prevent the user from updating the new password if it was set the the last X passwords.

Does not appears Users page

After command php artisan migrate:fresh there is no users page

I have created new user manually in DB. I logged in as the user but the users page does not appears on sidebar.
Even I have tried to enter bu url ../admin/users but there is error like 403 Forbiddin. It seems I dont have permission.

So How to create new user with admin permissions and get access to users?

image

Avoid registering middlewares and routes if feature is disabled and add opt-out

If a specific feature is disabled from the config file, there's no reason to load specific middlewares and routes.

I am referring to:

  1. ImpersonatingMiddleware
  2. RenewPasswordMiddleware

$panel->middleware([ImpersonatingMiddleware::class, RenewPasswordMiddleware::class]);

And for the routes:

Route::get('/impersonate/stop', fn () => ImpersonateLink::leave())

It would be also cool to have the option to disable from the config file the password_renewal feature. If disabled, the specific route and middleware should not be loaded in the application.

Would you accept a PR having those modifications? Do you see any issues in implementing those features?

Thank you πŸ‘

Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, Illuminate\Routing\Redirector given, called in ./vendor/laravel/framework/src/Illuminate/Http/Response.php on line 72

When using the Impersonate Action Link i'm getting this error:

TypeError
PHP 8.2.12
10.39.0
Phpsa\FilamentAuthentication\Actions\ImpersonateLink::impersonate(): Return value must be of type 
Livewire\Redirector|Illuminate\Http\RedirectResponse|bool, Livewire\Features\SupportRedirects\Redirector returned

changing this in ImpersonateLink.php removes the error:

// use Livewire\Redirector;
Livewire\Features\SupportRedirects\Redirector

the other way around, I also get another error (pressing the "Leave" button):

TypeError
PHP 8.2.12
10.39.0
Symfony\Component\HttpFoundation\Response::setContent(): Argument #1 ($content) must be of type ?string, 
Illuminate\Routing\Redirector given, called in ./vendor/laravel/framework/src/Illuminate/Http/Response.php on line 72

I'm using Filament v 3.1.33

Impersonate Action

Hi,
Action for impersonate user in UserResource it's not visible.
I'm looking into source code and i found (row 22 FilamentAuthentication class)
protected bool $impersonate = false;
I'm not found configuration fon change this behaviour

Error accessing the Dashboard

I get this error after trying to add the LatestUsers widget to the dashboard.
I even tried to remove the widget and clear the artisan cache but nothing seems to work.
I can access all other pages I have created.

TypeError
Phpsa\FilamentAuthentication\Widgets\LatestUsersWidget::getTableQuery(): Return value must be of type Illuminate\Contracts\Database\Eloquent\Builder, Illuminate\Database\Eloquent\Builder returned (View: C:\laragon\www\Laravel-Test\vendor\filament\filament\resources\views\components\widgets.blade.php)

Thanks

Asking for a "roles" relationship in the users model

I installed filament over a fresh install of laravel Jetstream.
Installed the filament-authentication plugin as oriented in readme...
When I try to access Users resource in the admin panel, I am receiving this message:

Call to undefined relationship [roles] on model [App\Models\User].

Is there any other package I need to install ?

Thanks in advance.
Rodolfo

PS: I create a roles function in User.php returning an empty array [].
And now, the error is:
Call to a member function addEagerConstraints() on array

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Missing package.json file.

A package.json file at the root of your project is required to release on npm.

Please follow the npm guideline to create a valid package.json file.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Question: should permissions be deletable?

Hi, this is kinda of a conceptual question:
Currently permissions can be delete (Via the relationship table in the Roles' edit page).
Should be allowed?

The point is that when checking if a user has a particular permission, an exception is thrown if that permission does not exist. So deleting permissions is not really recommended

In addition, when considering roles, maybe they should not be deletable if assigned to at least 1 role... ?

Thanks.

ps: Happy to provide PRs to tackle this if it makes sense.

Roles and Permission not work for defaults modules

HI! i have fresh install of laravel, filament and filament-authentication package.
First of thank you for this all-in-one package.
But i found there is some issue. please look following :

i have 2 Roles : 1) Super Admin 2) Filament-User
i have given full permission to Super Admin & Filament-User has not any permission even though Users, Roles & Permission.
Show i am login with Filament-User Role's User, they can also access the default 2 resources (Users, Roles & Permission.)
that user has only one role Filament-User.

ex

  1. John User (Role: SuperAdmin - Full Permission All checked)
  2. Wiliam User (Role Filament-User - Nothing Permission - Empty Permission List)

But login with Wiliam i am able to access all three modules.
Please let me know this is bug or want to do extra configuration for this.

Target class [translator] does not exist with PR36

I commented out the following in my attempt to use the PR36 feature.

'section' => [
        'group' => __('Settings')
    ]

Then I got the error Target class [translator] does not exist..

It seems that I cannot use the __() function in filament-authentication.php.
How can I solve this?

Global Scope on User returns a blank page

When I add a global scope on the user model, the routes relating to users all return a blank page. No error, no info in logs just a blank white page on the browser. Anything I should know?

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.