/** * Get user permissions and restrictions * * @param User $user * * @return array */ public function getPermissionsAndRestrictions(User $user) { $permissions = array(); $restrictions = array(); $username = $user->getUsername(); try { $roles = Config::app('roles'); } catch (NotReadableError $e) { Logger::error('Can\'t get permissions and restrictions for user \'%s\'. An exception was thrown:', $username, $e); return array($permissions, $restrictions); } $userGroups = $user->getGroups(); foreach ($roles as $role) { if ($this->match($username, $userGroups, $role)) { $permissions = array_merge($permissions, array_diff(String::trimSplit($role->permissions), $permissions)); $restrictionsFromRole = $role->toArray(); unset($restrictionsFromRole['users']); unset($restrictionsFromRole['groups']); unset($restrictionsFromRole['permissions']); foreach ($restrictionsFromRole as $name => $restriction) { if (!isset($restrictions[$name])) { $restrictions[$name] = array(); } $restrictions[$name][] = $restriction; } } } return array($permissions, $restrictions); }
public function testWhetherSearchProvidesHintWhenSearchStringIsEmpty() { $user = new User('test'); $user->setPermissions(array('*' => '*')); $dashboard = new SearchDashboard(); $dashboard->setUser($user); $dashboard = $dashboard->search(); $result = $dashboard->getPane('search')->hasDashlet('Ready to search'); $this->assertTrue($result, 'Dashboard::search() could not get hint for search'); }
/** * Get config file * * @return string */ public function getConfigFile() { if ($this->user === null) { throw new ProgrammingError('Can\'t load dashboards. User is not set'); } return Config::resolvePath('dashboards/' . $this->user->getUsername() . '/dashboard.ini'); }
/** * Whether an authenticated user has a given permission * * @param string $permission Permission name * * @return bool True if the user owns the given permission, false if not or if not authenticated */ public function hasPermission($permission) { if (!$this->isAuthenticated()) { return false; } return $this->user->can($permission); }
/** * Authenticate the given user and return true on success, false on failure and null on error * * @param User $user * @param string $password * * @return bool|null * @throws AuthenticationException */ public function authenticate(User $user, $password) { try { $salt = $this->getSalt($user->getUsername()); if ($salt === null) { return false; } if ($salt === '') { throw new Exception('Cannot find salt for user ' . $user->getUsername()); } $select = new Zend_Db_Select($this->conn->getConnection()); $row = $select->from('account', array(new Zend_Db_Expr(1)))->where('username = ?', $user->getUsername())->where('active = ?', true)->where('password = ?', $this->hashPassword($password, $salt))->query()->fetchObject(); return $row !== false ? true : false; } catch (Exception $e) { throw new AuthenticationException(sprintf('Failed to authenticate user "%s" against backend "%s". An exception was thrown:', $user->getUsername(), $this->getName()), 0, $e); } }
/** * Authenticate the given user and return true on success, false on failure and null on error * * @param User $user * @param string $password * * @return bool|null * @throws AuthenticationException */ public function authenticate(User $user, $password) { try { return $this->conn->testCredentials($this->conn->fetchDN($this->createQuery($user->getUsername())), $password); } catch (Exception $e) { throw new AuthenticationException(sprintf('Failed to authenticate user "%s" against backend "%s". An exception was thrown:', $user->getUsername(), $this->getName()), 0, $e); } }
/** * List all dashboard configuration files that match the given user * * @param User $user * * @return string[] */ public static function listConfigFilesForUser(User $user) { $files = array(); $dashboards = static::resolvePath('dashboards'); if ($handle = @opendir($dashboards)) { while (false !== ($entry = readdir($handle))) { if ($entry[0] === '.' || !is_dir($dashboards . '/' . $entry)) { continue; } if (strtolower($entry) === strtolower($user->getUsername())) { $files[] = $dashboards . '/' . $entry . '/dashboard.ini'; } } closedir($handle); } return $files; }
/** * Authenticate the given user * * @param User $user * @param string $password * * @return bool True on success, false on failure * * @throws AuthenticationException In case authentication is not possible due to an error */ public function authenticate(User $user, $password = null) { if (isset($_SERVER['REMOTE_USER'])) { $username = $_SERVER['REMOTE_USER']; $user->setRemoteUserInformation($username, 'REMOTE_USER'); if ($this->stripUsernameRegexp) { $stripped = preg_replace($this->stripUsernameRegexp, '', $username); if ($stripped !== false) { // TODO(el): PHP issues a warning when PHP cannot compile the regular expression. Should we log an // additional message in that case? $username = $stripped; } } $user->setUsername($username); return true; } return false; }
/** * Instantiate front controller * * @return $this */ private function setupFrontController() { $this->frontController = Zend_Controller_Front::getInstance(); $this->frontController->setRequest($this->getRequest()); $this->frontController->setControllerDirectory($this->getApplicationDir('/controllers')); $displayExceptions = $this->config->get('global', 'show_stacktraces', true); if ($this->user !== null && $this->user->can('application/stacktraces')) { $displayExceptions = $this->user->getPreferences()->getValue('icingaweb', 'show_stacktraces', $displayExceptions); } $this->frontController->setParams(array('displayExceptions' => $displayExceptions)); return $this; }
/** * Return the groups the given user is a member of * * @param User $user * * @return array */ public function getMemberships(User $user) { $result = $this->select()->fetchAll(); $groups = array(); foreach ($result as $group) { $groups[$group->group_name] = $group->parent; } $username = strtolower($user->getUsername()); $memberships = array(); foreach ($result as $group) { if ($group->users && !in_array($group->group_name, $memberships)) { $users = array_map('strtolower', String::trimSplit($group->users)); if (in_array($username, $users)) { $memberships[] = $group->group_name; $parent = $groups[$group->group_name]; while ($parent !== null) { $memberships[] = $parent; $parent = isset($groups[$parent]) ? $groups[$parent] : null; } } } } return $memberships; }
/** * Tries to authenticate the user from the session, and then from the REMOTE_USER superglobal, that can be set by * an external authentication provider. */ public function authenticateFromRemoteUser() { $this->fromRemoteUser = true; $this->authenticateFromSession(); if ($this->user !== null) { if (array_key_exists('REMOTE_USER', $_SERVER) && $this->user->getUsername() !== $_SERVER["REMOTE_USER"]) { // Remote user has changed, clear all sessions $this->removeAuthorization(); } return; } if (array_key_exists('REMOTE_USER', $_SERVER) && $_SERVER["REMOTE_USER"]) { $this->user = new User($_SERVER["REMOTE_USER"]); $this->persistCurrentUser(); } }
/** * {@inheritdoc} */ public function authenticate(User $user, $password = null) { if (!empty($_SERVER['HTTP_FROM'])) { $email = $_SERVER['HTTP_FROM']; $user->setUsername($email); $user->setEmail($email); $user->setExternalUserInformation($email, 'HTTP_FROM'); if (!empty($_SERVER['HTTP_X_GIVEN_NAME'])) { $user->setFirstname($_SERVER['HTTP_X_GIVEN_NAME']); } if (!empty($_SERVER['HTTP_X_GROUPS'])) { $user->setGroups(explode(',', $_SERVER['HTTP_X_GROUPS'])); } if (!empty($_SERVER['HTTP_X_FAMILY_NAME'])) { $user->setLastname($_SERVER['HTTP_X_FAMILY_NAME']); } return true; } return false; }
public function testPermissions() { $user = new User('test'); $user->setPermissions(array('test', 'test/some/specific', 'test/more/*', 'test/wildcard-with-wildcard/*', 'test/even-more/specific-with-wildcard/*')); $this->assertTrue($user->can('test')); $this->assertTrue($user->can('test/some/specific')); $this->assertTrue($user->can('test/more/everything')); $this->assertTrue($user->can('test/wildcard-with-wildcard/*')); $this->assertTrue($user->can('test/wildcard-with-wildcard/sub/sub')); $this->assertTrue($user->can('test/even-more/*')); $this->assertFalse($user->can('not/test')); $this->assertFalse($user->can('test/some/not/so/specific')); $this->assertFalse($user->can('test/wildcard2/*')); }
/** * {@inheritdoc} */ public function authenticate(User $user, $password = null) { list($username, $field) = static::getRemoteUserInformation(); if ($username !== null) { $user->setExternalUserInformation($username, $field); if ($this->stripUsernameRegexp) { $stripped = @preg_replace($this->stripUsernameRegexp, '', $username); if ($stripped === false) { Logger::error('Failed to strip external username. The configured regular expression is invalid.'); return false; } $username = $stripped; } $user->setUsername($username); return true; } return false; }
/** * Return the groups the given user is a member of * * @param User $user * * @return array */ public function getMemberships(User $user) { $groupQuery = $this->ds->select()->from(array('g' => $this->prependTablePrefix('group')), array('group_name' => 'g.name', 'parent_name' => 'gg.name'))->joinLeft(array('gg' => $this->prependTablePrefix('group')), 'g.parent = gg.id', array()); $groups = array(); foreach ($groupQuery as $group) { $groups[$group->group_name] = $group->parent_name; } $membershipQuery = $this->select()->from('group_membership', array('group_name'))->where('user_name', $user->getUsername()); $memberships = array(); foreach ($membershipQuery as $membership) { $memberships[] = $membership->group_name; $parent = $groups[$membership->group_name]; while ($parent !== null) { $memberships[] = $parent; // Usually a parent is an existing group, but since we do not have a constraint on our table.. $parent = isset($groups[$parent]) ? $groups[$parent] : null; } } return $memberships; }
/** * @depends testWhetherCreatePaneCreatesAPane */ public function testLoadPaneItemsProvidedByEnabledModules() { $user = new User('test'); $user->setPermissions(array('*' => '*')); $dashboard = new Dashboard(); $dashboard->setUser($user); $dashboard->load(); $this->assertCount(1, $dashboard->getPanes(), 'Dashboard::load() could not load panes from enabled modules'); }
/** * Return the groups the given user is a member of * * @param User $user * * @return array */ public function getMemberships(User $user) { if ($this->isMemberAttributeAmbiguous()) { $queryValue = $user->getUsername(); } elseif (($queryValue = $user->getAdditional('ldap_dn')) === null) { $userQuery = $this->ds->select()->from($this->userClass)->where($this->userNameAttribute, $user->getUsername())->setBase($this->userBaseDn)->setUsePagedResults(false); if ($this->userFilter) { $userQuery->setNativeFilter($this->userFilter); } if (($queryValue = $userQuery->fetchDn()) === null) { return array(); } } if ($this->nestedGroupSearch) { $groupMemberAttribute = $this->groupMemberAttribute . ':1.2.840.113556.1.4.1941:'; } else { $groupMemberAttribute = $this->groupMemberAttribute; } $groupQuery = $this->ds->select()->from($this->groupClass, array($this->groupNameAttribute))->where($groupMemberAttribute, $queryValue)->setBase($this->groupBaseDn); if ($this->groupFilter) { $groupQuery->setNativeFilter($this->groupFilter); } $groups = array(); foreach ($groupQuery as $row) { $groups[] = $row->{$this->groupNameAttribute}; } return $groups; }
/** * Setup internationalization using gettext * * Uses the preferred user language or the configured default and system default, respectively. * * @return self */ protected function setupInternationalization() { parent::setupInternationalization(); if ($this->user !== null && $this->user->getPreferences() !== null && ($locale = $this->user->getPreferences()->get('app.language') !== null)) { try { Translator::setupLocale($locale); } catch (Exception $error) { Logger::warning('Cannot set locale "' . $locale . '" configured in ' . 'preferences of user "' . $this->user->getUsername() . '"'); } } return $this; }
/** * Unshare the given navigation item * * @param string $name * @param string $parent * * @return Config The new config of the given navigation item * * @throws NotFoundError In case no navigation item with the given name is found * @throws IcingaException In case the navigation item has a parent assigned to it */ public function unshare($name, $parent = null) { $config = $this->getShareConfig(); if (!$config->hasSection($name)) { throw new NotFoundError('No navigation item called "%s" found', $name); } $itemConfig = $config->getSection($name); if ($parent === null) { $parent = $itemConfig->parent; } if ($parent && $this->hasBeenShared($parent)) { throw new IcingaException($this->translate('Unable to unshare navigation item "%s". It is dependent from item "%s".' . ' Dependent items can only be unshared by unsharing their parent'), $name, $parent); } $children = $this->getFlattenedChildren($name); $config->removeSection($name); $this->secondaryConfig = $config; if (!$itemConfig->owner || $itemConfig->owner === $this->getUser()->getUsername()) { $config = $this->getUserConfig(); } else { $owner = new User($itemConfig->owner); $config = $owner->loadNavigationConfig(); } foreach ($children as $child) { $childConfig = $this->secondaryConfig->getSection($child); unset($childConfig->owner); $this->secondaryConfig->removeSection($child); $config->setSection($child, $childConfig); } unset($itemConfig->owner); unset($itemConfig->users); unset($itemConfig->groups); $config->setSection($name, $itemConfig); $this->setIniConfig($config); return $config; }
/** * Getter for groups belonged to authenticated user * * @return array * @see User::getGroups */ public function getGroups() { return $this->user->getGroups(); }
/** * Authenticate the given user * * @param User $user * @param string $password * * @return bool True on success, false on failure * * @throws AuthenticationException In case authentication is not possible due to an error */ public function authenticate(User $user, $password) { try { $passwordHash = $this->getPasswordHash($user->getUsername()); $passwordSalt = $this->getSalt($passwordHash); $hashToCompare = $this->hashPassword($password, $passwordSalt); return $hashToCompare === $passwordHash; } catch (Exception $e) { throw new AuthenticationException('Failed to authenticate user "%s" against backend "%s". An exception was thrown:', $user->getUsername(), $this->getName(), $e); } }
/** * Authenticate the given user * * @param User $user * @param string $password * * @return bool True on success, false on failure * * @throws AuthenticationException In case authentication is not possible due to an error */ public function authenticate(User $user, $password) { try { $userDn = $this->select()->where('user_name', str_replace('*', '', $user->getUsername()))->getQuery()->setUsePagedResults(false)->fetchDn(); if ($userDn === null) { return false; } return $this->ds->testCredentials($userDn, $password); } catch (LdapException $e) { throw new AuthenticationException('Failed to authenticate user "%s" against backend "%s". An exception was thrown:', $user->getUsername(), $this->getName(), $e); } }
/** * Return the groups the given user is a member of * * @param User $user * * @return array */ public function getMemberships(User $user) { if ($this->isAmbiguous($this->groupClass, $this->groupMemberAttribute)) { $queryValue = $user->getUsername(); } elseif (($queryValue = $user->getAdditional('ldap_dn')) === null) { $userQuery = $this->ds->select()->from($this->userClass)->where($this->userNameAttribute, $user->getUsername())->setBase($this->userBaseDn)->setUsePagedResults(false); if ($this->userFilter) { $userQuery->where(new Expression($this->userFilter)); } if (($queryValue = $userQuery->fetchDn()) === null) { return array(); } } $groupQuery = $this->ds->select()->from($this->groupClass, array($this->groupNameAttribute))->where($this->groupMemberAttribute, $queryValue)->setBase($this->groupBaseDn); if ($this->groupFilter) { $groupQuery->where(new Expression($this->groupFilter)); } $groups = array(); foreach ($groupQuery as $row) { $groups[] = $row->{$this->groupNameAttribute}; } return $groups; }
/** * Return the groups the given user is a member of * * @param User $user * * @return array */ public function getMemberships(User $user) { if ($this->groupClass === 'posixGroup') { // Posix group only uses simple user name $userDn = $user->getUsername(); } else { // LDAP groups use the complete DN if (($userDn = $user->getAdditional('ldap_dn')) === null) { $userQuery = $this->ds->select()->from($this->userClass)->where($this->userNameAttribute, $user->getUsername())->setBase($this->userBaseDn)->setUsePagedResults(false); if ($this->userFilter) { $userQuery->where(new Expression($this->userFilter)); } if (($userDn = $userQuery->fetchDn()) === null) { return array(); } } } $groupQuery = $this->ds->select()->from($this->groupClass, array($this->groupNameAttribute))->where($this->groupMemberAttribute, $userDn)->setBase($this->groupBaseDn); if ($this->groupFilter) { $groupQuery->where(new Expression($this->groupFilter)); } Logger::debug('Fetching groups for user %s using filter %s.', $user->getUsername(), $groupQuery->__toString()); $groups = array(); foreach ($groupQuery as $row) { $groups[] = $row->{$this->groupNameAttribute}; } Logger::debug('Fetched %d groups: %s.', count($groups), join(', ', $groups)); return $groups; }