简体   繁体   中英

How do I validate User role on Laravel 5.8s Built in Authentication?

I've a User Role column on my User's table.

  • stands for Super Admin,
  • stands for other users

I've checked a lot of Laravel Tutorials and none of them has helped me about solving this issue.

I've found ways like replacing the whole Laravel's Login Controller and replacing Authenticate Users trait with ours own. I want to solve my problem with minimal code change. Is it possible?

How do I implement it with minimal code changes in this Trait method?

public function login(Request $request)
{
    $this->validateLogin($request);


    if (method_exists($this, 'hasTooManyLoginAttempts') &&
        $this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }


    $this->incrementLoginAttempts($request);

    return $this->sendFailedLoginResponse($request);
}

You could do something as supersimple as adding a isSuperAdmin function to the User model. After logging in you just call this function on the user whenever you need to check.

In model User.php

  public function isSuperAdmin()
  {
      return $this->user_role == 1;
  }

Then you could also make a middleware that's using this function.

php artisan make:middleware SuperAdmin

In the handle function of this middleware ( app/http/middleware/SuperAdmin.php ):

public function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->isSuperAdmin()) {
        return $next($request);
    }
    return redirect('some-route-for-unauthorized-users');

}

Then in your routes (probably web.php), you can use this middleware to protect routes:

Route::group(['middleware' => ['auth', 'superadmin']], function () {
    ... put protected routes here ...
});

Solution

        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct() {
            $this->middleware('guest')->except('logout');
        }

        protected function credentials(Request $request)
        {
            $credentials = $request->only($this->username(), 'password');
            $credentials['role'] = '1';
            return $credentials;
        }

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