/** * @test */ public function createAccountWithPasswordCreatesANewAccountWithTheGivenIdentifierPasswordRolesAndProviderName() { $factory = new \TYPO3\Flow\Security\AccountFactory(); $actualAccount = $factory->createAccountWithPassword('username', 'password', array('TYPO3.Flow:Administrator', 'TYPO3.Flow:Customer'), 'OtherProvider'); $this->assertEquals('username', $actualAccount->getAccountIdentifier()); $this->assertEquals('OtherProvider', $actualAccount->getAuthenticationProviderName()); $this->assertTrue($actualAccount->hasRole($this->policyService->getRole('TYPO3.Flow:Administrator'))); $this->assertTrue($actualAccount->hasRole($this->policyService->getRole('TYPO3.Flow:Customer'))); }
/** * Convert an object from $source to an object. * * @param mixed $source * @param string $targetType * @param array $convertedChildProperties * @param PropertyMappingConfigurationInterface $configuration * @return object the target type */ public function convertFrom($source, $targetType, array $convertedChildProperties = array(), PropertyMappingConfigurationInterface $configuration = null) { try { $role = $this->policyService->getRole($source); } catch (NoSuchRoleException $exception) { return new Error('Could not find a role with the identifier "%s".', 1397212327, array($source)); } return $role; }
/** * Creates a new account and sets the given password and roles * * @param string $identifier Identifier of the account, must be unique * @param string $password The clear text password * @param array $roleIdentifiers Optionally an array of role identifiers to assign to the new account * @param string $authenticationProviderName Optional name of the authentication provider the account is affiliated with * @param string $passwordHashingStrategy Optional password hashing strategy to use for the password * @return \TYPO3\Flow\Security\Account A new account, not yet added to the account repository */ public function createAccountWithPassword($identifier, $password, $roleIdentifiers = array(), $authenticationProviderName = 'DefaultProvider', $passwordHashingStrategy = 'default') { $account = new \TYPO3\Flow\Security\Account(); $account->setAccountIdentifier($identifier); $account->setCredentialsSource($this->hashService->hashPassword($password, $passwordHashingStrategy)); $account->setAuthenticationProviderName($authenticationProviderName); $roles = array(); foreach ($roleIdentifiers as $roleIdentifier) { $roles[] = $this->policyService->getRole($roleIdentifier); } $account->setRoles($roles); return $account; }
/** * @test */ public function everybodyRoleCanHaveExplicitDenies() { $mockPrivilegeClassName = get_class($this->mockPrivilege); $this->mockPolicyConfiguration = ['privilegeTargets' => [$mockPrivilegeClassName => ['Some.PrivilegeTarget:Identifier' => ['matcher' => 'someMatcher()'], 'Some.OtherPrivilegeTarget:Identifier' => ['matcher' => 'someMatcher()']]], 'roles' => ['TYPO3.Flow:Everybody' => ['privileges' => [['privilegeTarget' => 'Some.PrivilegeTarget:Identifier', 'permission' => 'DENY']]], 'Some.Other:Role' => ['privileges' => [['privilegeTarget' => 'Some.PrivilegeTarget:Identifier', 'permission' => 'GRANT']]]]]; $everybodyRole = $this->policyService->getRole('TYPO3.Flow:Everybody'); $this->assertTrue($everybodyRole->getPrivilegeForTarget('Some.PrivilegeTarget:Identifier')->isDenied()); }
/** * Check if department of logged in User match with department property of page node and hide this node if true * * @param \TYPO3\Flow\AOP\JoinPointInterface $joinPoint * @Flow\Around("method(TYPO3\TYPO3CR\Security\Authorization\Privilege\Node\___NotUse___EditNodePrivilege->matchesSubject(PrivilegeSubjectInterface $subject))") * @return boolean */ public function checkMatchesSubjectForCreatingNodes($joinPoint) { $matchesSubject = $joinPoint->getMethodArgument('subject'); $result = $joinPoint->getAdviceChain()->proceed($joinPoint); // if ($matchesSubject instanceof \TYPO3\Flow\Security\Authorization\Privilege\Method\CreateNodePrivilegeSubject === false) return false; if ($result) { if ($this->securityContext->getParty() instanceof User) { // get access rights depending on matching users and pages department if ($this->getPropertyRecursive($matchesSubject->getNode(), 'departmentName') == $this->securityContext->getParty()->getDepartment()) { return false; } else { return true; } } else { $role = $this->policyService->getRole('TYPO3.Neos:Administrator'); if ($role) { foreach ($this->securityContext->getParty()->getAccounts() as $account) { if ($account->hasRole($role)) { return false; } } } } } return $result; }
/** * renders <f:then> child if the role could be found in the security context, * otherwise renders <f:else> child. * * @param string $role The role or role identifier * @param string $packageKey PackageKey of the package defining the role * @param Account $account If specified, this subject of this check is the given Account instead of the currently authenticated account * @return string the rendered string * @api */ public function render($role, $packageKey = null, Account $account = null) { if (is_string($role)) { $roleIdentifier = $role; if (in_array($roleIdentifier, array('Everybody', 'Anonymous', 'AuthenticatedUser'))) { $roleIdentifier = 'TYPO3.Flow:' . $roleIdentifier; } if (strpos($roleIdentifier, '.') === false && strpos($roleIdentifier, ':') === false) { if ($packageKey === null) { $request = $this->controllerContext->getRequest(); $roleIdentifier = $request->getControllerPackageKey() . ':' . $roleIdentifier; } else { $roleIdentifier = $packageKey . ':' . $roleIdentifier; } } $role = $this->policyService->getRole($roleIdentifier); } if ($account instanceof Account) { $hasRole = $account->hasRole($role); } else { $hasRole = $this->securityContext->hasRole($role->getIdentifier()); } if ($hasRole) { return $this->renderThenChild(); } else { return $this->renderElseChild(); } }
/** * Authenticates against a crowd instance. * * @param \TYPO3\Flow\Security\Authentication\TokenInterface $authenticationToken The token to be authenticated * @return void * @throws \TYPO3\Flow\Security\Exception\UnsupportedAuthenticationTokenException */ public function authenticate(TokenInterface $authenticationToken) { if (!$authenticationToken instanceof UsernamePassword) { throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339845); } $credentials = $authenticationToken->getCredentials(); if (is_array($credentials) && isset($credentials['username']) && isset($credentials['password'])) { $crowdAuthenticationResponse = $this->crowdClient->authenticate($credentials['username'], $credentials['password']); if ($crowdAuthenticationResponse !== NULL) { /** @var $account \TYPO3\Flow\Security\Account */ $account = NULL; $providerName = $this->name; $accountRepository = $this->accountRepository; $this->securityContext->withoutAuthorizationChecks(function () use($credentials, $providerName, $accountRepository, &$account) { $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($credentials['username'], $providerName); }); if ($account === NULL) { $account = new Account(); $account->setAuthenticationProviderName($providerName); $account->setAccountIdentifier($credentials['username']); $this->accountRepository->add($account); } $authenticateRole = $this->policyService->getRole($this->options['authenticateRole']); if ($account->hasRole($authenticateRole) === FALSE) { $account->addRole($authenticateRole); } $crowdUser = $this->partyService->getAssignedPartyOfAccount($account); if ($crowdUser instanceof Person) { if ($crowdUser->getName()->getFirstName() !== $crowdAuthenticationResponse['first-name']) { $crowdUser->getName()->setFirstName($crowdAuthenticationResponse['first-name']); $this->partyRepository->update($crowdUser); } if ($crowdUser->getName()->getLastName() !== $crowdAuthenticationResponse['last-name']) { $crowdUser->getName()->setLastName($crowdAuthenticationResponse['last-name']); $this->partyRepository->update($crowdUser); } if ($crowdUser->getPrimaryElectronicAddress()->getIdentifier() !== $crowdAuthenticationResponse['email']) { $crowdUser->getPrimaryElectronicAddress()->setIdentifier($crowdAuthenticationResponse['email']); $this->partyRepository->update($crowdUser); } } else { $crowdUser = new Person(); $crowdUser->setName(new PersonName('', $crowdAuthenticationResponse['first-name'], '', $crowdAuthenticationResponse['last-name'])); $email = new ElectronicAddress(); $email->setIdentifier($crowdAuthenticationResponse['email']); $email->setType(ElectronicAddress::TYPE_EMAIL); $crowdUser->setPrimaryElectronicAddress($email); $this->partyRepository->add($crowdUser); $this->partyService->assignAccountToParty($account, $crowdUser); } $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); $authenticationToken->setAccount($account); } else { $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS); } } elseif ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); } }
/** * @param ACLCheckerDto $dto * @return array */ protected function getRolesByDto(ACLCheckerDto $dto) { $roles = []; foreach ($dto->getRoles() as $roleIdentifier) { try { $roles[] = $this->policyService->getRole($roleIdentifier); } catch (NoSuchRoleException $e) { } } return $roles; }
/** * Returns the processed Configuration * * @param \TYPO3\TYPO3CR\Domain\Model\NodeType $nodeType (uninitialized) The node type to process * @param array $configuration input configuration * @param array $options The processor options * @return void */ public function process(NodeType $nodeType, array &$configuration, array $options) { if ($this->securityContext->canBeInitialized()) { /* Check if user is logged in */ if ($this->securityContext->getAccount()) { $admin = false; $role = $this->policyService->getRole('TYPO3.Neos:Administrator'); if ($role && $this->securityContext->getAccount()->hasRole($role)) { $admin = true; } if (!$admin) { // foreach ($configuration['properties']['departmentName']['ui']['inspector']['editorOptions']['values'] as $key => $val) { // $configuration['properties']['departmentName']['ui']['inspector']['editorOptions']['values'][$key]['disabled'] = TRUE; // } // if ($nodeType->getName() == 'TYPO3.Neos.NodeTypes:Page') { // $configuration['constraints']['nodeTypes']['TYPO3.Neos.NodeTypes:Page'] = FALSE; // } unset($configuration['properties']['departmentName']); } } } }
/** * Creates a new account, assigns it the given roles and authenticates it. * The created account is returned for further modification, for example for attaching a Party object to it. * * @param array $roleNames A list of roles the new account should have * @return Account The created account */ protected function authenticateRoles(array $roleNames) { // FIXME this is currently needed in order to correctly import the roles. Otherwise RepositoryInterface::isConnected() returns FALSE and importing is skipped in PolicyService::initializeRolesFromPolicy() $this->objectManager->get('TYPO3\\Flow\\Security\\AccountRepository')->countAll(); $account = new Account(); $account->setAccountIdentifier('TestAccount'); $roles = array(); foreach ($roleNames as $roleName) { $roles[] = $this->policyService->getRole($roleName); } $account->setRoles($roles); $this->authenticateAccount($account); return $account; }
/** * Initializes the roles field by fetching the role objects referenced by the roleIdentifiers * * @return void */ protected function initializeRoles() { if ($this->roles !== null) { return; } $this->roles = []; foreach ($this->roleIdentifiers as $key => $roleIdentifier) { // check for and clean up roles no longer available if ($this->policyService->hasRole($roleIdentifier)) { $this->roles[$roleIdentifier] = $this->policyService->getRole($roleIdentifier); } else { unset($this->roleIdentifiers[$key]); } } }
/** * @param \DLigo\Animaltool\Domain\Model\User $user * @param array $username * @Flow\Validate(argumentName="$username", type="notEmpty") * @param array $password * @param string $role * @Flow\Validate(argumentName="$password", type="\DLigo\Animaltool\Validation\Validator\PasswordValidator", options={"allowEmpty"=true}) * @Flow\Validate(argumentName="$username", type="\DLigo\Animaltool\Validation\Validator\AccountExistsValidator") * @return void */ public function updateAction(User $user, $username, $password = null, $role = null) { if ($role) { $roleObj = $this->policyService->getRole($role); foreach ($user->getAccounts() as $account) { $account->setRoles(array($role => $roleObj)); $account->setAccountIdentifier($username['new']); $account->setCredentialsSource($this->hashService->hashPassword($password[0], 'default')); $this->accountRepository->update($account); } } $this->userRepository->update($user); $this->addFlashMessage('Updated the user.', '', \TYPO3\Flow\Error\Message::SEVERITY_OK, array(), 'flash.user.update'); $this->redirect('index'); }
/** * @param Account $account * @param array $userdata * @return \TYPO3\Flow\Security\Account */ protected function updateAccount(Account $account, array $userdata) { $person = $this->partyService->getAssignedPartyOfAccount($account); if ($person === null) { $person = new Person(); $this->partyRepository->add($person); $this->partyService->assignAccountToParty($account, $person); } if (!$account->getRoles()) { $account->setRoles(array($this->policyService->getRole('T3DD.Backend:Authenticated'))); } $this->updatePerson($person, $userdata); $this->accountRepository->update($account); $this->persistenceManager->persistAll(); return $account; }
/** * Sets the roles for the LDAP account. * Extend this Provider class and implement this method to update the party * * @param Account $account * @param array $ldapSearchResult * @return void */ protected function setRoles(Account $account, array $ldapSearchResult) { if (is_array($this->rolesConfiguration)) { $contextVariables = array('ldapUser' => $ldapSearchResult); if (isset($this->defaultContext) && is_array($this->defaultContext)) { foreach ($this->defaultContext as $contextVariable => $objectName) { $object = $this->objectManager->get($objectName); $contextVariables[$contextVariable] = $object; } } foreach ($this->rolesConfiguration['default'] as $roleIdentifier) { $role = $this->policyService->getRole($roleIdentifier); $account->addRole($role); } $eelContext = new Context($contextVariables); if (isset($this->partyConfiguration['dn'])) { $dn = $this->eelEvaluator->evaluate($this->partyConfiguration['dn'], $eelContext); foreach ($this->rolesConfiguration['userMapping'] as $roleIdentifier => $userDns) { if (in_array($dn, $userDns)) { $role = $this->policyService->getRole($roleIdentifier); $account->addRole($role); } } } elseif (!empty($this->rolesConfiguration['userMapping'])) { $this->logger->log('User mapping found but no party mapping for dn set', LOG_ALERT); } if (isset($this->partyConfiguration['username'])) { $username = $this->eelEvaluator->evaluate($this->partyConfiguration['username'], $eelContext); $groupMembership = $this->directoryService->getGroupMembership($username); foreach ($this->rolesConfiguration['groupMapping'] as $roleIdentifier => $remoteRoleIdentifiers) { foreach ($remoteRoleIdentifiers as $remoteRoleIdentifier) { $role = $this->policyService->getRole($roleIdentifier); if (isset($groupMembership[$remoteRoleIdentifier])) { $account->addRole($role); } } } } elseif (!empty($this->rolesConfiguration['groupMapping'])) { $this->logger->log('Group mapping found but no party mapping for username set', LOG_ALERT); } } }
/** * @param string $username Crowd Username * @param string $providerName Name of the authentication provider, this account should be used with * @return Account */ public function getLocalAccountForCrowdUser($username, $providerName) { $accountRepository = $this->accountRepository; $this->securityContext->withoutAuthorizationChecks(function () use($username, $providerName, $accountRepository, &$account) { $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($username, $providerName); }); if ($account === NULL) { if ($this->getUser($username) === NULL) { return NULL; } $account = new Account(); $account->setAuthenticationProviderName($providerName); $account->setAccountIdentifier($username); $roleIdentifier = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'TYPO3.Flow.security.authentication.providers.' . $providerName . '.providerOptions.authenticateRole'); $account->addRole($this->policyService->getRole($roleIdentifier)); $this->accountRepository->add($account); $this->persistenceManager->persistAll(); } return $account; }
/** * Update a given account * * @param Account $account The account to update * @param array $roleIdentifiers A possibly updated list of roles for the user's primary account * @param array $password Expects an array in the format array('<password>', '<password confirmation>') * @Flow\Validate(argumentName="password", type="\TYPO3\Neos\Validation\Validator\PasswordValidator", options={ "allowEmpty"=1, "minimum"=1, "maximum"=255 }) * @return void */ public function updateAccountAction(Account $account, array $roleIdentifiers, array $password = array()) { $user = $this->userService->getUser($account->getAccountIdentifier(), $account->getAuthenticationProviderName()); if ($user === $this->currentUser) { $roles = array(); foreach ($roleIdentifiers as $roleIdentifier) { $roles[$roleIdentifier] = $this->policyService->getRole($roleIdentifier); } if (!$this->privilegeManager->isPrivilegeTargetGrantedForRoles($roles, 'TYPO3.Neos:Backend.Module.Administration.Users')) { $this->addFlashMessage('With the selected roles the currently logged in user wouldn\'t have access to this module any longer. Please adjust the assigned roles!', 'Don\'t lock yourself out', Message::SEVERITY_WARNING, array(), 1416501197); $this->forward('edit', null, null, array('user' => $this->currentUser)); } } $password = array_shift($password); if (strlen(trim(strval($password))) > 0) { $this->userService->setUserPassword($user, $password); } $this->userService->setRolesForAccount($account, $roleIdentifiers); $this->addFlashMessage('The account has been updated.', 'Account updated', Message::SEVERITY_OK); $this->redirect('edit', null, null, array('user' => $user)); }
/** * Returns Collection of roles. * * @param string $providerName Provider name to fetch roles from. * @param array $casAttributes * * @throws \Exception * @throws Exception\WrongMappingConfigurationException * * @return \Doctrine\Common\Collections\Collection<\TYPO3\Flow\Security\Policy\Role> */ public function getRoles($providerName, array $casAttributes) { $rolesSettings = $this->settings[$providerName]['Roles']; $rolesCollection = new ArrayCollection(); $iterator = 0; foreach ($rolesSettings as $roleSettings) { // Map Cas Attributes if (empty($roleSettings['staticIdentifier']) && !empty($roleSettings['identifier']) && is_string($roleSettings['identifier'])) { $roleIdentifier = ArraysUtility::getValueByPath($casAttributes, $roleSettings['identifier']); if (!is_string($roleIdentifier) && !is_int($roleIdentifier)) { throw new WrongMappingConfigurationException(sprintf('Cas attribute catched by path "%s" from CAS-Attributes array defined at ....%s.providerOptions.Mapping.Roles.%s.identifier must be a string but "%s" is given.', $roleSettings['identifier'], $providerName, $iterator, gettype($roleIdentifier)), 1371209193); } if (isset($roleSettings['rewriteRoles'])) { $roleIdentifier = $this->rewriteRole($roleIdentifier, $roleSettings['rewriteRoles']); } } // Map static Role if (isset($roleSettings['staticIdentifier']) && is_string($roleSettings['staticIdentifier'])) { $roleIdentifier = $roleSettings['staticIdentifier']; if (isset($roleSettings['rewriteRoles'])) { $roleIdentifier = $this->rewriteRole($roleIdentifier, $roleSettings['rewriteRoles']); } } if (is_string($roleIdentifier) || is_int($roleIdentifier)) { try { $role = $this->policyService->getRole($roleSettings['packageKey'] . ':' . $roleIdentifier); } catch (NoSuchRoleException $exc) { /* @var $exc \Exception */ if ($exc->getCode() === 1353085860) { $role = $this->policyService->createRole($roleSettings['packageKey'] . ':' . $roleIdentifier); } else { throw new \Exception('Unknown exception by PolicyService->getRole(). Message: ' . $exc->getMessage() . ' Code: ' . $exc->getCode(), 1371211532); } } } $rolesCollection->add($role); $iterator++; } return $rolesCollection; }
/** * Sets isAuthenticated to TRUE for all tokens. * * @param TokenInterface $authenticationToken The token to be authenticated * @return void * @throws UnsupportedAuthenticationTokenException */ public function authenticate(TokenInterface $authenticationToken) { if (!$authenticationToken instanceof PasswordToken) { throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339840); } $credentials = $authenticationToken->getCredentials(); if (is_array($credentials) && isset($credentials['password'])) { if ($this->hashService->validatePassword($credentials['password'], $this->fileBasedSimpleKeyService->getKey($this->options['keyName']))) { $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); $account = new Account(); $roles = array(); foreach ($this->options['authenticateRoles'] as $roleIdentifier) { $roles[] = $this->policyService->getRole($roleIdentifier); } $account->setRoles($roles); $authenticationToken->setAccount($account); } else { $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS); } } elseif ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); } }
/** * Returns the roles of all authenticated accounts, including inherited roles. * * If no authenticated roles could be found the "Anonymous" role is returned. * * The "TYPO3.Flow:Everybody" roles is always returned. * * @return Role[] */ public function getRoles() { if ($this->initialized === false) { $this->initialize(); } if ($this->roles === null) { $this->roles = array('TYPO3.Flow:Everybody' => $this->policyService->getRole('TYPO3.Flow:Everybody')); if ($this->authenticationManager->isAuthenticated() === false) { $this->roles['TYPO3.Flow:Anonymous'] = $this->policyService->getRole('TYPO3.Flow:Anonymous'); } else { $this->roles['TYPO3.Flow:AuthenticatedUser'] = $this->policyService->getRole('TYPO3.Flow:AuthenticatedUser'); /** @var $token \TYPO3\Flow\Security\Authentication\TokenInterface */ foreach ($this->getAuthenticationTokens() as $token) { if ($token->isAuthenticated() !== true) { continue; } $account = $token->getAccount(); if ($account === null) { continue; } if ($account !== null) { $accountRoles = $account->getRoles(); /** @var $currentRole Role */ foreach ($accountRoles as $currentRole) { if (!in_array($currentRole, $this->roles)) { $this->roles[$currentRole->getIdentifier()] = $currentRole; } /** @var $currentParentRole Role */ foreach ($currentRole->getAllParentRoles() as $currentParentRole) { if (!in_array($currentParentRole, $this->roles)) { $this->roles[$currentParentRole->getIdentifier()] = $currentParentRole; } } } } } } } return $this->roles; }
/** * Shows the effective policy rules currently active in the system * * @param boolean $grantsOnly Only list methods effectively granted to the given roles * @return void */ public function showEffectivePolicyCommand($grantsOnly = FALSE) { $roles = array(); $roleIdentifiers = $this->request->getExceedingArguments(); if (empty($roleIdentifiers) === TRUE) { $this->outputLine('Please specify at leas one role, to calculate the effective privileges for!'); $this->quit(1); } foreach ($roleIdentifiers as $roleIdentifier) { if ($this->policyService->hasRole($roleIdentifier)) { $currentRole = $this->policyService->getRole($roleIdentifier); $roles[$roleIdentifier] = $currentRole; foreach ($this->policyService->getAllParentRoles($currentRole) as $parentRoleIdentifier => $parentRole) { if (!isset($roles[$parentRoleIdentifier])) { $roles[$parentRoleIdentifier] = $parentRole; } } } } if (count($roles) === 0) { $this->outputLine('The specified role(s) do not exist.'); $this->quit(1); } $this->outputLine(PHP_EOL . 'The following roles will be used for calculating the effective privileges (retrieved from the configured roles hierarchy):' . PHP_EOL); foreach ($roles as $roleIdentifier => $role) { $this->outputLine($roleIdentifier); } $dummySecurityContext = new DummyContext(); $dummySecurityContext->setRoles($roles); $accessDecisionManager = new AccessDecisionVoterManager($this->objectManager, $dummySecurityContext); if ($this->policyCache->has('acls')) { $classes = array(); $acls = $this->policyCache->get('acls'); foreach ($acls as $classAndMethodName => $aclEntry) { if (strpos($classAndMethodName, '->') === FALSE) { continue; } list($className, $methodName) = explode('->', $classAndMethodName); $className = $this->objectManager->getCaseSensitiveObjectName($className); $reflectionClass = new \ReflectionClass($className); foreach ($reflectionClass->getMethods() as $casSensitiveMethodName) { if ($methodName === strtolower($casSensitiveMethodName->getName())) { $methodName = $casSensitiveMethodName->getName(); break; } } $runtimeEvaluationsInPlace = FALSE; foreach ($aclEntry as $role => $resources) { if (in_array($role, $roles) === FALSE) { continue; } if (!isset($classes[$className])) { $classes[$className] = array(); } if (!isset($classes[$className][$methodName])) { $classes[$className][$methodName] = array(); $classes[$className][$methodName]['resources'] = array(); } foreach ($resources as $resourceName => $privilege) { $classes[$className][$methodName]['resources'][$resourceName] = $privilege; if ($privilege['runtimeEvaluationsClosureCode'] !== FALSE) { $runtimeEvaluationsInPlace = TRUE; } } } if ($runtimeEvaluationsInPlace === FALSE) { try { $accessDecisionManager->decideOnJoinPoint(new JoinPoint(NULL, $className, $methodName, array())); } catch (AccessDeniedException $e) { $classes[$className][$methodName]['effectivePrivilege'] = $e->getMessage(); } if (!isset($classes[$className][$methodName]['effectivePrivilege'])) { $classes[$className][$methodName]['effectivePrivilege'] = 'Access granted'; } } else { $classes[$className][$methodName]['effectivePrivilege'] = 'Could not be calculated. Runtime evaluations in place!'; } } foreach ($classes as $className => $methods) { $classNamePrinted = FALSE; foreach ($methods as $methodName => $resources) { if ($grantsOnly === TRUE && $resources['effectivePrivilege'] !== 'Access granted') { continue; } if ($classNamePrinted === FALSE) { $this->outputLine(PHP_EOL . PHP_EOL . ' <b>' . $className . '</b>'); $classNamePrinted = TRUE; } $this->outputLine(PHP_EOL . ' ' . $methodName); if (isset($resources['resources']) === TRUE && is_array($resources['resources']) === TRUE) { foreach ($resources['resources'] as $resourceName => $privilege) { switch ($privilege['privilege']) { case PolicyService::PRIVILEGE_GRANT: $this->outputLine(' Resource "<i>' . $resourceName . '</i>": Access granted'); break; case PolicyService::PRIVILEGE_DENY: $this->outputLine(' Resource "<i>' . $resourceName . '</i>": Access denied'); break; case PolicyService::PRIVILEGE_ABSTAIN: $this->outputLine(' Resource "<i>' . $resourceName . '</i>": Vote abstained (no acl entry for given roles)'); break; } } } $this->outputLine(' <b>Effective privilege for given roles: ' . $resources['effectivePrivilege'] . '</b>'); } } } else { $this->outputLine('Could not find any policy entries, please warmup caches...'); } }
/** * Removes the specified role from the given account and potentially carries out further actions which are needed to * properly reflect these changes. * * @param Account $account The account to remove roles from * @param string $roleIdentifier A fully qualified role identifier, or a role identifier relative to the TYPO3.Neos namespace * @return integer How often this role has been removed from the given account (effectively can be 1 or 0) * @api */ public function removeRoleFromAccount(Account $account, $roleIdentifier) { $roleIdentifier = $this->normalizeRoleIdentifier($roleIdentifier); $role = $this->policyService->getRole($roleIdentifier); /** @var Account $account */ if ($account->hasRole($role)) { $account->removeRole($role); $this->accountRepository->update($account); $this->emitRolesRemoved($account, array($role)); return 1; } return 0; }
/** * Creates a new account, assigns it the given roles and authenticates it. * The created account is returned for further modification, for example for attaching a Party object to it. * * @param array $roleNames A list of roles the new account should have * @return \TYPO3\Flow\Security\Account The created account * @api */ protected function authenticateRoles(array $roleNames) { $account = new \TYPO3\Flow\Security\Account(); $roles = array(); foreach ($roleNames as $roleName) { $roles[] = $this->policyService->getRole($roleName); } $account->setRoles($roles); $this->authenticateAccount($account); return $account; }
/** * Returns an array with all roles of a user's accounts, including parent roles, the "Everybody" role and the * "AuthenticatedUser" role, assuming that the user is logged in. * * @param User $user The user * @return array */ protected function getAllRoles(User $user) { $roles = array('TYPO3.Flow:Everybody' => $this->policyService->getRole('TYPO3.Flow:Everybody'), 'TYPO3.Flow:AuthenticatedUser' => $this->policyService->getRole('TYPO3.Flow:AuthenticatedUser')); /** @var Account $account */ foreach ($user->getAccounts() as $account) { $accountRoles = $account->getRoles(); /** @var $currentRole Role */ foreach ($accountRoles as $currentRole) { if (!in_array($currentRole, $roles)) { $roles[$currentRole->getIdentifier()] = $currentRole; } /** @var $currentParentRole Role */ foreach ($currentRole->getAllParentRoles() as $currentParentRole) { if (!in_array($currentParentRole, $roles)) { $roles[$currentParentRole->getIdentifier()] = $currentParentRole; } } } } return $roles; }
/** * Shows a list of all defined privilege targets and the effective permissions * * @param string $privilegeType The privilege type ("entity", "method" or the FQN of a class implementing PrivilegeInterface) * @param string $roles A comma separated list of role identifiers. Shows policy for an unauthenticated user when left empty. */ public function showEffectivePolicyCommand($privilegeType, $roles = '') { $systemRoleIdentifiers = array('TYPO3.Flow:Everybody', 'TYPO3.Flow:Anonymous', 'TYPO3.Flow:AuthenticatedUser'); if (strpos($privilegeType, '\\') === false) { $privilegeType = sprintf('\\TYPO3\\Flow\\Security\\Authorization\\Privilege\\%s\\%sPrivilegeInterface', ucfirst($privilegeType), ucfirst($privilegeType)); } if (!class_exists($privilegeType) && !interface_exists($privilegeType)) { $this->outputLine('The privilege type "%s" was not defined.', array($privilegeType)); $this->quit(1); } if (!is_subclass_of($privilegeType, PrivilegeInterface::class)) { $this->outputLine('"%s" does not refer to a valid Privilege', array($privilegeType)); $this->quit(1); } $requestedRoles = array(); foreach (Arrays::trimExplode(',', $roles) as $roleIdentifier) { try { if (in_array($roleIdentifier, $systemRoleIdentifiers)) { continue; } $currentRole = $this->policyService->getRole($roleIdentifier); $requestedRoles[$roleIdentifier] = $currentRole; foreach ($currentRole->getAllParentRoles() as $currentParentRole) { if (!in_array($currentParentRole, $requestedRoles)) { $requestedRoles[$currentParentRole->getIdentifier()] = $currentParentRole; } } } catch (NoSuchRoleException $exception) { $this->outputLine('The role %s was not defined.', array($roleIdentifier)); $this->quit(1); } } if (count($requestedRoles) > 0) { $requestedRoles['TYPO3.Flow:AuthenticatedUser'] = $this->policyService->getRole('TYPO3.Flow:AuthenticatedUser'); } else { $requestedRoles['TYPO3.Flow:Anonymous'] = $this->policyService->getRole('TYPO3.Flow:Anonymous'); } $requestedRoles['TYPO3.Flow:Everybody'] = $this->policyService->getRole('TYPO3.Flow:Everybody'); $this->outputLine('Effective Permissions for the roles <b>%s</b> ', array(implode(', ', $requestedRoles))); $this->outputLine(str_repeat('-', $this->output->getMaximumLineLength())); $definedPrivileges = $this->policyService->getAllPrivilegesByType($privilegeType); $permissions = array(); /** @var PrivilegeInterface $definedPrivilege */ foreach ($definedPrivileges as $definedPrivilege) { $accessGrants = 0; $accessDenies = 0; $permission = 'ABSTAIN'; /** @var Role $requestedRole */ foreach ($requestedRoles as $requestedRole) { $privilegeType = $requestedRole->getPrivilegeForTarget($definedPrivilege->getPrivilegeTarget()->getIdentifier()); if ($privilegeType === null) { continue; } if ($privilegeType->isGranted()) { $accessGrants++; } elseif ($privilegeType->isDenied()) { $accessDenies++; } } if ($accessDenies > 0) { $permission = '<error>DENY</error>'; } if ($accessGrants > 0 && $accessDenies === 0) { $permission = '<success>GRANT</success>'; } $permissions[$definedPrivilege->getPrivilegeTarget()->getIdentifier()] = $permission; } ksort($permissions); foreach ($permissions as $privilegeTargetIdentifier => $permission) { $formattedPrivilegeTargetIdentifier = wordwrap($privilegeTargetIdentifier, $this->output->getMaximumLineLength() - 10, PHP_EOL . str_repeat(' ', 10), true); $this->outputLine('%-70s %s', array($formattedPrivilegeTargetIdentifier, $permission)); } }