Quantcast
Channel: Login only if user is active using Laravel - Stack Overflow
Viewing all articles
Browse latest Browse all 25

Answer by Ryan Tirrell for Login only if user is active using Laravel

$
0
0

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!


Viewing all articles
Browse latest Browse all 25

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>