简体   繁体   中英

Laravel user auth check “enabled” column as well as email and password

I have:

if ($validator->fails()) {
            return Redirect::to('/start')->withErrors($validator);
        } else {
            if (Auth::attempt(array('email' => $input['email'], 'password' => $input['password'])))
            {
                echo 'success';
            }
        }

There is another column in my users table called enabled. This needs to equal 1 for the user attempting to log in, otherwise they should be sent back to the log in screen with a message telling them that the account is disabled.

How can I achieve this?


$details = array('email' => $input['email'], 'password' => $input['password']);
    if (Auth::user()->enabled) {
        if(Auth::attempt($details)) {
            echo 'success';
        }
    } else {
        echo 'disabled!';
    }

I'm sure somebody will give you an "extend it this way" answer, but the easiest by far is to just add another condition to the code. Also, you don't need to wrap the login attempt within an else, since the first if condition returns if it triggers. See the below example.

if ($validator->fails()) {
    return Redirect::to('/start')->withErrors($validator);
}

$details = array('email' => $input['email'], 'password' => $input['password']);
if (Auth::attempt($details) && Auth::user()->enabled) {
    echo 'success';
}

Edit: As Lukas Geiter pointed out, please note that the user will still be logged in - you'll have to manually log them out as well if applicable. This resolves that issue:

if ($validator->fails()) {
    return Redirect::to('/start')->withErrors($validator);
}

$details = array('email' => $input['email'], 'password' => $input['password']);
if (Auth::attempt($details)) {
    if (!Auth::user()->enabled) {
        Auth::logout();
        return Redirect::to('/your-login-screen-with-some-message');
    }
    echo 'success';
}

I should also mention that you could actually just add 'enabled' => 1 to the credentials, but then you would not be able to distinguish disabled users from incorrect credentials.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM