ask_alab
ask_alab

Reputation: 59

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

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

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);
}

Upvotes: 0

Views: 2447

Answers (2)

Christoffer
Christoffer

Reputation: 7777

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 ...
});

Upvotes: 1

ask_alab
ask_alab

Reputation: 59

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;
        }

Upvotes: 0

Related Questions