Home > other >  Check Laravel Bouncer user roles and permissions to determine if able to login
Check Laravel Bouncer user roles and permissions to determine if able to login

Time:12-24

I'm using standard Laravel authentication and I've added the Joseph Silber Bouncer package to setup roles and abilities. On the login process I would like to check if the user has a specific role or ability. I suspect I can do this here:

Illuminate\Foundation\Auth\AuthenticatesUsers.php

I have added it to this function, but I think there might be a better way, as this is logging them in, checking their roles/abilities and then logging them out.

protected function authenticated(Request $request, $user)
{
    if($user->cannot('login'))
    {
        \Session::flash('alert-type', 'danger');
        \Session::flash('message', 'Account has Expired');
        \Auth::logout();
        return redirect('/login');
    }
}

Does anyone happen to know of a better way or this acceptable?

CodePudding user response:

As I know, authenticated, is to use it after logging in. So initializing AuthenticatesUsers trait will be overkill. What if you moved it to the controller after validate

if (\Auth::user()->cannot('login')) {
        \Session::flash('alert-type', 'danger');
        \Session::flash('message', 'Account has Expired');
        return redirect('/login');
    }

or something like

 if ($user && !Bouncer::can('login', $user)) {

just an opinion.

CodePudding user response:

You must not edit files in vendor. You can create custom class inherenting main class in vendor.

You need to create custom login controller file:

create controller using artisan

php artisan make:controller LoginController

Then in it:

LoginController extends Controller
{
  
 use AuthenticatesUsers;

   public function login(Request $request)
   {
    return $this->login($request) ;
    }

 protected function authenticated(Request $request, $user) 
{ if($user->cannot('login')) 
  { \Session::flash('alert-type', 'danger'); 
    \Session::flash('message', 'Account has 
     Expired'); 
    \Auth::logout(); 
    return redirect('/login'); }
     }
}

You need define route

Route::post('login','LoginController@login');
  • Related