Search code examples
laravelrestlaravel-passportlaravel-permission

How to add Spatie Role Condition in Login using Laravel


I am using Laravel-8, laravel-passport and spatie-permission for restful api. Already, I have this code in the Controller.

I have this controller for the Admin:

public function adminLogin(Request $request)
{
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success, 'User login successfully.');
    }
    else{
        return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
    }
}

I want only 'Super Admin' to be able to use the Admin Controller to Login. If not 'Super Admin', it should indicate unathorized.

How do I include the code below to what I already have above or any other best way?

    if($user->hasRole('Super Admin'))
        $res = User::with(['roles', 'employee', 'company'])->find($user->id);
    else
        $res = User::with('roles')->find($user->id);

Solution

  • You can check the user's role after attempting authentication.

    public function adminLogin(Request $request)
    {
        if (Auth::attempt($request->only('email', 'password'))) {
            $user = Auth::user();
    
            if (!$user->hasRole('Super Admin') {
                Auth::logout();
    
                return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
            }
    
            $success['token'] =  $user->createToken('MyApp')-> accessToken;
            $success['name'] =  $user->name;
    
            return $this->sendResponse($success, 'User login successfully.');
        }
    
        return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
    }