2

I'm using Spatie's "Laravel Permission" Package for the ACL. Everything is working perfectly. I now want to allow only the User roles 2 and 3 to Login.

Previously, before using "Laravel Permission" package I had only this "role" column on my table and I could easily Log In a user with this line of code on Login Controller's credentials method.

protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
//$credentials['role'] = '1';
return $credentials;
}
$credentials = $request->only($this->username(), 'password');
$credentials['role'] = '1';

How do I allow Login only for the 2 and 3 User Roles?

apokryfos
  • 38,771
  • 9
  • 70
  • 114
ask_alab
  • 59
  • 1
  • 1
  • 7

3 Answers3

2

You can override authenticated() in LoginController and check user role. Pretty simple.

protected function authenticated(Request $request, $user)
{
    //Check user role, if it is not admin then logout
    if(!$user->hasRole(['Admin', 'Super-Admin']))
    {
        $this->guard()->logout();
        $request->session()->invalidate();
        return redirect('/login')->withErrors('You are unauthorized to login');
    }
}
Rizwan Saleem
  • 376
  • 4
  • 17
1

You could go with the workaround as follow:

If you're using the default LoginController from the App\Http\Controllers\Auth folder, then override its attemptLogin() method that comes from the Trait used.

    protected function attemptLogin(Request $request)
    {
        if( $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        ) ) { // Credential auth was successful
            // Get user model
            $user = Auth::user();
            return $user->hasRole([2, 3]); // Check if user has role ids 2 or 3
        }

        return false;
    }

hasRoles() method comes from the HasRoles trait used for the User model.

David Buck
  • 3,752
  • 35
  • 31
  • 35
Thepeanut
  • 3,074
  • 1
  • 17
  • 23
  • Thanks ☺, the same applies for role names `return $user->hasRole(['admin', 'stack overflower']);` – Pathros Dec 03 '19 at 19:10
0

Or you could override the Laravel credentials during login. In your default LoginController from the App\Http\Controllers\Auth folder, then override its credentials(Request $request) method that comes from the Trait used.

Override it to look something similar to this

protected function credentials(Request $request)
{

 return [ 'email' => $request-> { this-> username() }, 'password' -> $request -> password, 'role_id'  => [ '1', '2' ] ];

This is presuming you have a role_id in your user model. Worked for me.return

David Buck
  • 3,752
  • 35
  • 31
  • 35