Felix Blome
Felix Blome

Reputation: 61

Customise Laravel auth middleware

In my users table, I have a column rank which corresponds to the permissions of users. If rank > 0, the user may log in and proceed, since 0 in rank means they're (temporarily) blocked or inactive. So what I'd need is to customise the auth middleware so only rank > 0 are going to be authenticated whatsoever.

I did some research on it but didn't find where to put my code exactly.

EDIT: I earlier found how to manually authenticate a user featuring additional requirements (e.g. rank > 0), however, I'm using laravels built-in feature, so that doesn't help much:

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // The user is active, not suspended, and exists.
}

(it's active in this case (source: laravel documentation), but could be adjusted).

Upvotes: 5

Views: 10089

Answers (2)

Luka Isailovic
Luka Isailovic

Reputation: 126

There is middleware in your app/http/middleware called RedirectIfAuthenticated

You will have to edit it to something like this:

if (Auth::check() && Auth::user()->rank > 0) {
    return $next($request);
}
return redirect('/home');

Also if you want to manually authenticate user like you wrote, you can check if rank and password on user object and then just use

Auth::login($user)

Upvotes: 1

Mustafa Akçakaya
Mustafa Akçakaya

Reputation: 1229

There is a credentials() method in Illuminate\Foundation\Auth\AuthenticatesUsers trait that you can override in your app/Http/Controllers/Auth/LoginController.php. So, just add this to your LoginController:

/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{
    return [
        'email' => $request->{$this->username()},
        'password' => $request->password,
        'active' => 1, // yep, not rank, read below
    ];
}

If rank field has different values than 0 and 1, do not use it for this purpose and add an active field. Otherwise if you block a user, which means you set rank field to 0, how do you know what was the old rank when you unblock the user?

Upvotes: 1

Related Questions