/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next, $role = '') { // Check if a user is logged in. if (!($user = $request->user())) { return $next($request); } $group = new \App\Group(); // Get the current route. $route = $request->route(); // Get the current route actions. $actions = $route->getAction(); //dd($actions); //save the destination path $this->path = $actions['as']; /* Check if we have any permissions to check the user has. * Check if are NOT set permissions AND permissionsDetailed * OR * check if is set permissionsDetailed AND if the actual destination * have a permission to check * */ if (!($permissions = isset($actions['permissions']) ? $actions['permissions'] : null) && !($permissionsDetailed = isset($actions['permissionsDetailed']) ? $actions['permissionsDetailed'] : null) || ($permissionsDetailed = isset($actions['permissionsDetailed']) ? $actions['permissionsDetailed'] : null) && count(array_where((array) $permissionsDetailed, function ($key, $value) { return $key == $this->path; })) == 0) { // No permissions to check, allow access. return $next($request); } /*if we have a detailed permisison, we need to gather them in the * $permissions array * */ if (isset($permissionsDetailed)) { $permissions = (array) $permissions; array_push($permissions, $permissionsDetailed[$actions['as']]); $permissions = array_flatten(array_filter($permissions)); } // Fetch all of the matching user permissions. $userPermissions = array_fetch($user->permissions()->whereIn('slug', (array) $permissions)->get()->toArray(), 'slug'); //Also look if the user has a group that have permissions $userId = $user->id; $userGroups = array_pluck($user->groups()->get()->toArray(), 'id'); // Fetch all of the matching group permissions. $groupPermissions = array(); foreach ($userGroups as $ug) { $group->id = $ug; $groupPermission = array_fetch($group->permissions()->whereIn('slug', (array) $permissions)->get()->toArray(), 'slug'); $groupPermissions = array_merge($groupPermissions, $groupPermission); } // Turn the permissions we require into an array. Even if was made before $permissions = (array) $permissions; // Check if we require all permissions, or just one. if (isset($actions['permissions_require_all'])) { // If user has EVERY permission required. if (count($permissions) == count($userPermissions) || count($permissions) == count($groupPermissions)) { // Access is granted. return $next($request); } } else { // If the user has the permission. if (count($userPermissions) >= 1 || count($groupPermissions) >= 1) { // Access is granted and the rest of the permissions are ignored. return $next($request); } } // If we reach this far, the user does not have the required permissions. return App::abort(403, 'Access denied'); }