【问题标题】:Laravel Authentication Custom RuleLaravel 身份验证自定义规则
【发布时间】:2018-05-16 22:41:00
【问题描述】:

我正在使用 laravel Auth。尝试使用电子邮件和密码添加新规则,如果状态(用户模型中的字段)= 1,则他无法登录。我找不到我应该在哪里添加这个。我在看中间件,guard.php AuthenticateUsers.php 但没有找到它..


编辑:

我已经通过创建新的中间件来检查这个字段来解决这个问题。也可以使用 Auth::attempt

【问题讨论】:

  • 这里的状态是什么?
  • @MohamedAthif 状态是用户模型中的字段(已编辑第一篇文章)
  • 如果他的状态为 1,你可以制作一个中间件并限制像管理员这样的路由
  • @MohamedAthif 如果他的状态为 1,我不希望他首先能够登录。我认为必须有检查电子邮件/密码组合是否正确的功能,所以我可以在那里再添加一行,但我找不到它

标签: php laravel authentication


【解决方案1】:

你可以试试:

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

来自Docs

如果您愿意,除了用户的电子邮件和密码之外,您还可以在身份验证查询中添加额外的条件。

【讨论】:

  • 参考文档,这应该是在 LoginController.php 但它不是。我应该在哪里添加这段代码?
  • LoginController.php 中有一个特征Illuminate\Foundation\Auth\AuthenticatesUsers 包含login() 函数。您可以根据需要在 LoginController 类中覆盖该函数。
【解决方案2】:

将此代码添加到您的 LoginController:

/**
 * Attempt to log the user with custom credentials into the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function attemptLogin(Request $request)
{
    $credentials = $this->credentials($request);

    $credentials['status'] = 1; // Additional field you want to check

    return $this->guard()->attempt(
        $credentials, $request->filled('remember')
    );
}

在这里,我们将status 字段添加为已检查凭据的一部分。如果用户的status 不等于1,认证将失败。

适用于 Laravel5.6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-11
    • 2018-02-18
    • 2015-02-23
    • 2019-02-12
    • 2016-11-22
    • 2014-03-30
    • 2016-04-18
    相关资源
    最近更新 更多