Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict user login in Laravel if email is not verified

I am using 'jrean' package in Laravel for verifying emails of registered users. https://packagist.org/packages/jrean/laravel-user-verification

The problem I am facing currently is even if the user is registered how can I restrict his access until the email is not verified. I have followed all the steps given in the package tutorial for implementing registration. But they don't have any steps listed for restricting login access. Any ideas?

like image 377
SanketR Avatar asked Oct 25 '25 04:10

SanketR


1 Answers

You can overwrite your login method. In L5.2 and asumming you have a verified field in your users table which is boolean you can do something like:

In your app/Http/Controllers/Auth/AuthController.php add something like:

use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Support\Facades\Auth;

    /**
       * Handle a login request to the application.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return \Illuminate\Http\Response
       */
      public function login(Request $request)
      {
        $this->validateLogin($request);
        $throttles = $this->isUsingThrottlesLoginsTrait();
        if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
          $this->fireLockoutEvent($request);
          return $this->sendLockoutResponse($request);
        }
        $credentials = $this->getCredentials($request);
        if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
          if (Auth::user()->verified == true) { // This is the most important part for you
            return $this->handleUserWasAuthenticated($request, $throttles);
          } else {
            Auth::logout();
            return $this->sendFailedLoginResponse($request, "Some message here");
          }
        }
        if ($throttles && !$lockedOut) {
          $this->incrementLoginAttempts($request);
        }
        return $this->sendFailedLoginResponse($request);
      }

You also need to add the verified field in your User eloquent model in order to use it in your modified login method.

Hope it helps!

like image 154
Julian Rodriguez Avatar answered Oct 26 '25 19:10

Julian Rodriguez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!