使用新字段覆盖AuthController中的postLogin

时间:2015-03-23 10:04:00

标签: php laravel laravel-4 laravel-5

我已经覆盖了postLogin以检查用户状态的尝试方法以及用户名和密码

我的更新代码是:

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

    $credentials = $request->only('username', 'password', 'status' = 1);

    if ($this->auth->attempt($credentials, $request->has('remember')))
    {
        return redirect()->intended($this->redirectPath());
    }

    return redirect($this->loginPath())
                ->withInput($request->only('username', 'remember'))
                ->withErrors([
                    'username' => 'These credentials do not match our records.',
                ]);
}

但不起作用,用户状态为0,他可以登录。

我的错在哪里?

2 个答案:

答案 0 :(得分:3)

你做错了。如果您想在登录过程中添加其他检查,则无需覆盖postLogin()

相反,您需要添加middleware,以便在请求后检查状态:

  1. artisan make:middleware UserStatusMiddleware

  2. 编辑中间件以在请求后检查状态:

  3. class UserStatusMiddleware {
    
        /**
         * The Guard implementation.
         *
         * @var Guard
         */
        protected $auth;
    
        /**
         * Create a new filter instance.
         *
         * @param  Guard  $auth
         * @return void
         */
        public function __construct(Guard $auth)
        {
            $this->auth = $auth;
        }
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $user = $this->auth->getUser();
    
            if ($user->status === 1) {
                return Redirect::to('home');
    
            } else {
                $this->auth->logout(); 
                return Redirect::to('auth/login');
            }
        }
    }
    
    1. 通过将中间件添加到app/Http/Kernel.php
    2. 来激活它
      protected $routeMiddleware = [
          'status' => 'App\Http\Middleware\UserStatusMiddleware',
      ];
      
      1. 将中间件添加到您的路线:
      2. $router->post("/auth/login", "Auth\AuthController@postLogin", ['middleware' => 'status']);
        

答案 1 :(得分:0)

试试吧

$credentials = $request->only('username', 'password');
if(empty($credentials['status'])){
   $credentials['status'] = 1;
}