Patrick Obafemi
Patrick Obafemi

Reputation: 1066

How to throw an error if user role is not allowed Laravel

I am trying to leverage the Laravel auth system and add logic that does not allow you to log in if you have the user role of user. I want to extend authenticate users.

protected function sendLoginResponse(Request $request)
{
    $user = $this->guard()->user();

    $request->session()->regenerate();
    if ($user->role != 'admin') {
        return redirect()->back()->with('error', 'You do not have permissions to view this page');

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }
}

The issue is it still logs me in. How can I make this logic work?

Upvotes: 0

Views: 169

Answers (1)

MrEvers
MrEvers

Reputation: 1072

Add this function to your LoginController, it will override the default function and add an extra constraint for logging in:

/**
 * override to add check
 * 
 * @param \Illuminate\Http\Request $request
 * @return array
 */
protected function credentials(Request $request)
{
    $credentials = $request->only($this->username(), 'password');
    $credentials['role'] = 'admin'; //only login admin

    return $credentials;
}

Upvotes: 2

Related Questions