Example #1
0
 /**
  * Make a collection of role ids from provided roles
  * 
  * @param string|array|\Illuminate\Support\Collection $roles A role or list of roles to add to user.
  * 
  * @return \Illuminate\Support\Collection
  * 
  * @throws RollerException
  */
 public static function makeRoleIds($roles)
 {
     $roles = Support::makeCollection($roles);
     return $roles->map(function ($role) {
         if (is_string($role)) {
             try {
                 $role = Role::whereName($role)->firstOrFail();
             } catch (ModelNotFoundException $e) {
                 $role = Role::create(['name' => $role]);
             }
         } elseif (!$role instanceof Role) {
             throw new RollerException('Provided role is not a string or Role instance');
         }
         return $role->id;
     });
 }
Example #2
0
 /**
  * Check if user has roles. If a resource is provided, roles are checked against that resource domain.
  * Resource can be a class name or Eloquent Model instance.
  *
  * @param string|array|\Illuminate\Support\Collection $roles A role or list of roles to add to user.
  * @param string|\Illuminate\Database\Eloquent\Model|null $resource The resource instance, or its type if parameter is a string.
  *
  * @return boolean
  *
  * @throws RollerException
  */
 public function hasRoles($roles, $resource = null)
 {
     $resource = $this->makeArrayResource($resource);
     $roles = Support::makeRoleIds($roles);
     // Normally check if user has role, regarding resource
     $rrus = RRU::whereUserId($this->getKey())->whereResourceType($resource['type'])->whereResourceId($resource['id'])->whereIn('role_id', $roles)->get();
     if ($rrus and $rrus->count() > 0) {
         return true;
     }
     // But if resource is provided, we should also check if user has that global role or not
     if (!is_null($resource['id'])) {
         // Check if user has role on resource type only
         $rrus = RRU::whereUserId($this->getKey())->where(function ($query) use($resource) {
             $query->whereResourceType($resource['type']);
             $query->orWhere('resource_type', null);
         })->whereResourceId(null)->whereIn('role_id', $roles)->get();
         if ($rrus and $rrus->count() > 0) {
             return true;
         }
     } elseif (!is_null($resource['type'])) {
         // Check if user has global role only
         $rrus = RRU::whereUserId($this->getKey())->whereResourceType(null)->whereResourceId(null)->whereIn('role_id', $roles)->get();
         if ($rrus and $rrus->count() > 0) {
             return true;
         }
     }
     return false;
 }