仅在用户使用Laravel处于活动状态时登录

Mic*_*usa 24 php account login laravel laravel-5

我目前正在使用我的Laravel应用程序并防止垃圾邮件我决定只有活跃用户才能登录.我正在使用Laravel的登录系统,就像在Laravel的官方网站教程中一样,这是我的表单操作:

<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
Run Code Online (Sandbox Code Playgroud)

这完全正常,但我想检查用户的活动,如果不活动,它将被重定向到激活页面,否则它将登录.有没有一种简单的方法可以做到这一点,还是我有义务制作新的控制器,路线和更多的验证?谢谢.

编辑:忘记提及我的数据库中有一个"活动"列.

Bro*_*ary 60

Laravel 5.4/5.5

login()通过将此函数放入以下内容来覆盖默认函数LoginController:

public function login(\Illuminate\Http\Request $request) {
    $this->validateLogin($request);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);
        return $this->sendLockoutResponse($request);
    }

    // This section is the only change
    if ($this->guard()->validate($this->credentials($request))) {
        $user = $this->guard()->getLastAttempted();

        // Make sure the user is active
        if ($user->active && $this->attemptLogin($request)) {
            // Send the normal successful login response
            return $this->sendLoginResponse($request);
        } else {
            // Increment the failed login attempts and redirect back to the
            // login form with an error message.
            $this->incrementLoginAttempts($request);
            return redirect()
                ->back()
                ->withInput($request->only($this->username(), 'remember'))
                ->withErrors(['active' => 'You must be active to login.']);
        }
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);

    return $this->sendFailedLoginResponse($request);
}
Run Code Online (Sandbox Code Playgroud)

login()建议以这种方式覆盖此方法,因为它允许您仍然使用Laravel 5.4+的许多更高级的身份验证功能,例如登录限制,多个身份验证保护驱动程序/提供程序等.仍然允许您设置自定义错误消息.


Laravel 5.3

更改或覆盖您的postLogin()功能,AuthController如下所示:

public function postLogin(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email', 'password' => 'required',
    ]);

    $credentials = $this->getCredentials($request);

    // This section is the only change
    if (Auth::validate($credentials)) {
        $user = Auth::getLastAttempted();
        if ($user->active) {
            Auth::login($user, $request->has('remember'));
            return redirect()->intended($this->redirectPath());
        } else {
            return redirect($this->loginPath()) // Change this to redirect elsewhere
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'active' => 'You must be active to login.'
                ]);
        }
    }

    return redirect($this->loginPath())
        ->withInput($request->only('email', 'remember'))
        ->withErrors([
            'email' => $this->getFailedLoginMessage(),
        ]);

}
Run Code Online (Sandbox Code Playgroud)

此代码重定向回登录页面,并显示有关用户处于非活动状态的错误消息.如果要重定向到身份验证页面,您可以更改我用注释标记的行Change this to redirect elsewhere.

  • 需要注意的是,如果一个人使用了`make:auth`并进行了这里提到的更改,那么非活动用户仍然可以通过密码重置功能登录.如/sf/answers/3685697501/中所述,可以防止这种情况 (3认同)

Raj*_*han 43

在Laravel 5.4中打开Auth/LoginController.php

并添加此功能:

/**
     * Get the needed authorization credentials from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    protected function credentials(\Illuminate\Http\Request $request)
    {
        //return $request->only($this->username(), 'password');
        return ['email' => $request->{$this->username()}, 'password' => $request->password, 'status' => 1];
    }
Run Code Online (Sandbox Code Playgroud)

你完成了..!

  • 谢谢,你刚刚为我们节省了一些不必要的工作! (2认同)
  • 这是有道理的,但请注意,您不能以这种方式设置自定义消息.它将验证并返回一个通用的无法登录错误.但是,如果您需要自定义消息,例如"帐户未激活",请按[此答案](/sf/answers/2171134731/) (2认同)

Mat*_*usz 14

该解决方案基于Can Celik的想法,并使用Laravel 5.3进行了测试.

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|exists:users,' . $this->username() . ',active,1',
        'password' => 'required',
    ]);
}
Run Code Online (Sandbox Code Playgroud)

最后两个以逗号分隔的参数(active,1)充当WHERE子句(WHERE active = '1'),也可以这样写:

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => [
            'required',
            Rule::exists('users')->where(function ($query) {
                $query->where('active', 1);
            }),
        ],
        'password' => 'required'
    ]);
}
Run Code Online (Sandbox Code Playgroud)

通常,验证方法仅检查是否填写了电子邮件和密码字段.通过上面的修改,我们要求在DB行中找到给定的电子邮件地址,其active值设置为1.

更新(使用Laravel 5.5测试):

您还可以自定义消息:

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|exists:users,' . $this->username() . ',active,1',
        'password' => 'required',
    ], [
        $this->username() . '.exists' => 'The selected email is invalid or the account has been disabled.'
    ]);
}
Run Code Online (Sandbox Code Playgroud)

请注意,当给定的电子邮件地址不存在或帐户被禁用时,将显示上述消息.


小智 6

在AuthController覆盖方法getCredentials中,如下所示:

protected function getCredentials(Request $request) {

        $request['active'] = TRUE;
        return $request->only($this->loginUsername(), 'password', 'active');
}
Run Code Online (Sandbox Code Playgroud)

确保在用户表上激活了列...

  • 这是一个简单而简短的答案,唯一的问题是使用此方法,您无法在未激活时自定义错误消息.或者有没有办法可以在不活动时自定义错误消息? (4认同)

alb*_*ert 5

在 laravel 7 上,你只需要把这个方法放在 LoginController 上:

/**
 * Custom credentials to validate the status of user.
 */
public function credentials(Request $request)
{
    return [
        'email'     => $request->email,
        'password'  => $request->password,
        'is_active' => '1'
    ];
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以验证任何登录条件。