Laravel 用户身份验证检查 "enabled" 列以及电子邮件和密码

Laravel user auth check "enabled" column as well as email and password

我有:

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

我的用户 table 中还有另一列名为已启用。对于尝试登录的用户,这需要等于 1,否则他们应该被发送回登录屏幕,并显示一条消息,告诉他们该帐户已被禁用。

我怎样才能做到这一点?


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

我相信有人会给您 "extend it this way" 答案,但目前最简单的方法是向代码中添加另一个条件。此外,您不需要将登录尝试包装在 else 中,因为第一个 if 条件 returns 如果它触发。请参阅以下示例。

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';
}

编辑:正如 Lukas Geiter 所指出的,请注意用户仍将处于登录状态——如果适用,您还必须手动将他们注销。这解决了该问题:

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';
}

我还应该提到,您实际上可以只将 'enabled' => 1 添加到凭据中,但这样您将无法区分禁用用户和不正确的凭据。