Search code examples
phpauthenticationlaravel-5laravel-5.1laravel-authorization

Laravel 5.1 - When registering user App redirects to /dashboard but doesn't check if account is confirmed


When my users register in my app it automatically redirects them to /dashboard which is technically fine, but it isn't checking to see if the confirmed column in the database has a value of 1 or 0, it's just logging in based on the username and password.

I will happily include code but right now I don't actually know what code you guys need to see.

I need it to check the confirmed column and if it's a 0, not to log them in and throw and error.

thanks for any info,

Andy


Solution

  • I achieve this by utilizing middleware:

    My routes.php:

    Route::get('home', ['middleware' => 'auth', function ()    {
    
        return "This is just an example";
    
    }]);
    

    My Kernel.php:

    protected $routeMiddleware = [
    
            'auth' => \App\Http\Middleware\Authenticate::class,
    
        ];
    

    My Authenticate.php middleware:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Contracts\Auth\Guard;
    
    class Authenticate
    {
        /**
         * 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)
        {
            if ($this->auth->guest()) {
                if ($request->ajax()) {
                    return response('Unauthorized.', 401);
                } else {
                    return redirect()->guest('auth/login');
                }  
            }
    
            $user = $this->auth->user();
            if (!$user->confirmed) {
                $this->auth->logout();
                return redirect()->guest('auth/login')->with('error', 'Please confirm your e-mail address to continue.');
            }
    
            if (!$user->type) {
                $this->auth->logout();
                return redirect()->guest('auth/login')->with('error', 'A user configuration error has occurred. Please contact an administrator for assistance.');
            }    
    
            return $next($request);
        }
    }
    

    I tried to cut this down as much as possible for you.