简体   繁体   中英

Laravel 5.1 extra field for authentication

I'm making my first big project using Laravel 5.1 and I'd like to add an extra check during user login to see if the user has activated their account.

This is the schema of the users table

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('username');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->boolean('is_admin')->default(true);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

I've tried adding a $credentials['is_active'] = true; after $credentials = $this->getCredentials($request); in AutheticatesUser@postLogin and it works but I want to have a custom error if the user's account isn't active because the default one( These credentials do not match our records. ) is not that intuitive for the user.

Any suggestions in achieving that? Thank you!

You can override the postLogin method in your AuthController and check whether the user is active or not like this.

class AuthController extends Controller
{
public function postLogin(Request $request){
    $this->validate($request, [
          'email' => 'required|email', 'password' => 'required',
    ]);
   $credentials = $this->getCredentials($request);
  // This section is the only change
  if (Auth::validate($credentials)) {
      $user = Auth::getLastAttempted();
      if ($user->is_active) {
          Auth::login($user, $request->has('remember'));
          return redirect()->intended($this->redirectPath());
      } else {
         return redirect($this->loginPath()) // Change this to redirect elsewhee
        ->withInput($request->only('email', 'remember'))
        ->withErrors([
            'active' => 'Please active your account'
          ]);
      }
  }
   return redirect($this->loginPath())
      ->withInput($request->only('email', 'remember'))
      ->withErrors([
          'email' => $this->getFailedLoginMessage(),
   ]);
  }
}

You can check following way

 if(Auth::attempt(['email'=>$email,'password'=>$password,'is_admin'=>1]))
       {
            return redirect()->intended('admin/dashboard');
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM