Login only if user is active using Laravel

前端 未结 19 1577
孤城傲影
孤城傲影 2020-11-30 23:26

I\'m currently working on my Laravel app and to prevent spam I decided that only active users are able to login. I\'m currently using Laravel\'s login system just like in La

19条回答
  •  有刺的猬
    2020-11-30 23:48

    I'm new to Laravel, and this is aimed at newcomers too. Long-timers feel free to tell me why this is bad practice, as I genuinely don't know any better yet.

    As at 24th August 2019 - using Laravel 5.8 - This is my personal implementation.

    Assumptions made:

    1. You started out using Artisan Make:Auth
    2. You've added 'active' as a bool (tinyInt) to your User table and updated the relevant Models etc...
    3. You're trying to prevent users from gaining access to your application via standard Auth, when: 'active' = 0.

    If this is the case, you can leave your LoginController alone.

    Instead open "Illuminate/Auth/Middleware/Authenticate.php" and replace the handle() method with:

    public function handle($request, Closure $next, ...$guards)
        {
            if(!$request->user()->active){
                // either abort with simple 403 access denied page
                // abort(403, "You don't have permissions to access this area");
    
                // OR force Logout and redirect back to the login page
                return redirect('login')->with($this->auth->logout());
            }
    
            $this->authenticate($request, $guards);
            return $next($request);
        }
    

    Note: Auth::logout() won't work here, but it's already pulled in via the constructor at the top of the file.

    public function __construct(Auth $auth)
        {
            $this->auth = $auth;
        }
    

    So you can just use $this->auth->logout(); instead.

    Thinking about it - You could very easily swap 'Active' for pretty much any criteria and update this middleware the very same way! Hope this helps!

提交回复
热议问题