php - 将 laravel 5 内置认证扩展为仅登录 "if user == active"

标签 php authentication laravel-5

我使用 laravel 5.1.6 包含的身份验证,想知道如何扩展它,使其像这样工作:

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

如果用户不是“活跃的”,登录应该是不可能的。我在用户表中有一个“事件”列,值为 0 或 1。我如何在仍然使用带有登录限制的内置身份验证的同时执行此操作。

编辑:

我在 AuthController 中没有 postLogin 函数,只有一个 use AuthenticatesAndRegistersUsers, ThrottlesLogins;,一个 __construct(),一个 validator() 和一个 create() 函数。我是否必须更改 Illuminate\Foundation\Auth\.. 中的特征,或者我是否必须在 AuthController 中添加 postLogin() 函数?

最佳答案

您只需重写 AuthController 中的 getCredentials() 方法即可:

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers;

    public function getCredentials($request)
    {
        $credentials = $request->only($this->loginUsername(), 'password');

        return array_add($credentials, 'active', '1');
    }
}

这将在尝试对用户进行身份验证时添加 active = 1 约束。

编辑:如果您想要一个单独的错误消息,例如 BrokenBinary说,然后 Laravel 允许您定义一个名为 authenticated 的方法,该方法在用户通过身份验证之后但在重定向之前调用,允许您进行任何登录后处理。因此,您可以通过检查经过身份验证的用户是否处于事件状态来利用它,如果不是,则抛出异常或显示错误消息:

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers;

    public function authenticated(Request $request, User $user)
    {
        if ($user->active) {
            return redirect()->intended($this->redirectPath());
        } else {
            // Raise exception, or redirect with error saying account is not active
        }
    }
}

不要忘记导入 Request 类和 User 模型类。

关于php - 将 laravel 5 内置认证扩展为仅登录 "if user == active",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31244748/

相关文章:

php - 我如何反转 mysqli 查询的结果顺序

excel - Azure Active Directory - 为什么没有注册的浏览器可以进行身份​​验证,但不是第一方应用程序?

authentication - NTLM 身份验证和智能卡

php - Laravel 5 - 重定向不起作用

php - 根据Mysql查询结果显示

php mysql优化

php - 在从 MySQL 查询返回的 PHP 中循环遍历数组

java - 使用多个 Twitter4j 帐户发送多条推文(提及)

javascript - Vuejs ajax GET 请求未在 Laravel 5.1 Blade 模板中返回数据

javascript - Laravel 5.5 和 vue-typeahead - 防止在 onHit 方法中自动提交表单