Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel auth to check for column before logging in

I'm using Laravel 5.4 and its built in Auth API. I've added a column to the users table called is_admin. I want to modify the login process so that login only works if is_admin == 1. I've looked in Illuminate\Foundation\Auth\AuthenticatesUsers.php (Github) and I could probably make a change there but I'd rather not disturb the core if possible. Is there a more elegant way to do this?

like image 248
GluePear Avatar asked Feb 22 '17 15:02

GluePear


4 Answers

I solved this with a solution similar to @Sagar Arora's. In the app\Http\Controllers\Auth\LoginController.php that is created when you run artisan make:auth, I overrode the attemptLogin method from AuthenticatesUsers. This is the code in LoginController.php:

protected function attemptLogin(Request $request)
{
    return (auth()->attempt(['email' => $request->email, 'password' => $request->password, 'is_admin' => 1]));
}

Now only users with is_admin == 1 will be logged in.

like image 181
GluePear Avatar answered Oct 03 '22 23:10

GluePear


Just like you mentioned, you should never touch the core file. But if you could see laravel has added the AuthenticatesUsers as trait on LoginController which means you can simply override it by adding the credentials() in LoginController like the following.

/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function credentials(Request $request)
{
    return [
        'email'    => $request->input('email'),
        'password' => $request->input('password'),
        'is_admin' => 1
    ];
}
like image 37
Saravanan Sampathkumar Avatar answered Oct 04 '22 01:10

Saravanan Sampathkumar


This solution may not be elegant, but still working.

Add this to LoginController:

protected function authenticated(Request $request, $user)
{
    if ( ! $user->is_admin ) {
        Auth::logout();
        return redirect('login')->withErrors(['is_admin' => 'Only admin users may log in']);
    }
}

Then put this in auth/login.blade.php:

@if($errors->has('is_admin'))
    <div class="alert alert-danger" role="alert">{{ $errors->first('is_admin') }}</div>
@endif

Also keep in mind, that you should disable register functionality, because after registering a user still logs in.

like image 33
Petr Reshetin Avatar answered Oct 04 '22 01:10

Petr Reshetin


You can create your login function as:

So in your login function you can check this by:

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

You check here manual login process with additional fields:

https://laravel.com/docs/5.4/authentication#authenticating-users Thanks

like image 25
Sagar Arora Avatar answered Oct 04 '22 00:10

Sagar Arora