..) for the runtime of $callback
Usage:
$this->securityContext->withoutAuthorizationChecks(function () use ($accountRepository, $username, $providerName, &$account) {
this will disable the PersistenceQueryRewritingAspect for this one call
$account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($username, $providerName)
});
public withoutAuthorizationChecks ( Closure $callback ) : void | ||
$callback | Closure | |
return | void |
/** * Add the current node and all parent identifiers to be used for cache entry tagging * * @Flow\Before("method(Neos\Flow\Mvc\Routing\RouterCachingService->extractUuids())") * @param JoinPointInterface $joinPoint The current join point * @return void */ public function addCurrentNodeIdentifier(JoinPointInterface $joinPoint) { $values = $joinPoint->getMethodArgument('values'); if (!isset($values['node']) || strpos($values['node'], '@') === false) { return; } // Build context explicitly without authorization checks because the security context isn't available yet // anyway and any Entity Privilege targeted on Workspace would fail at this point: $this->securityContext->withoutAuthorizationChecks(function () use($joinPoint, $values) { $contextPathPieces = NodePaths::explodeContextPath($values['node']); $context = $this->contextFactory->create(['workspaceName' => $contextPathPieces['workspaceName'], 'dimensions' => $contextPathPieces['dimensions'], 'invisibleContentShown' => true]); $node = $context->getNode($contextPathPieces['nodePath']); if (!$node instanceof NodeInterface) { return; } $values['node-identifier'] = $node->getIdentifier(); $node = $node->getParent(); $values['node-parent-identifier'] = array(); while ($node !== null) { $values['node-parent-identifier'][] = $node->getIdentifier(); $node = $node->getParent(); } $joinPoint->setMethodArgument('values', $values); }); }
/** * Checks the given token for validity and sets the token authentication status * accordingly (success, wrong credentials or no credentials given). * * @param TokenInterface $authenticationToken The token to be authenticated * @return void * @throws UnsupportedAuthenticationTokenException */ public function authenticate(TokenInterface $authenticationToken) { if (!$authenticationToken instanceof UsernamePassword) { throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1217339840); } /** @var $account Account */ $account = null; $credentials = $authenticationToken->getCredentials(); if ($authenticationToken->getAuthenticationStatus() !== TokenInterface::AUTHENTICATION_SUCCESSFUL) { $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); } if (!is_array($credentials) || !isset($credentials['username']) || !isset($credentials['password'])) { return; } $providerName = $this->name; $accountRepository = $this->accountRepository; $this->securityContext->withoutAuthorizationChecks(function () use($credentials, $providerName, $accountRepository, &$account) { $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($credentials['username'], $providerName); }); $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS); if ($account === null) { $this->hashService->validatePassword($credentials['password'], 'bcrypt=>$2a$14$DummySaltToPreventTim,.ingAttacksOnThisProvider'); return; } if ($this->hashService->validatePassword($credentials['password'], $account->getCredentialsSource())) { $account->authenticationAttempted(TokenInterface::AUTHENTICATION_SUCCESSFUL); $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL); $authenticationToken->setAccount($account); } else { $account->authenticationAttempted(TokenInterface::WRONG_CREDENTIALS); } $this->accountRepository->update($account); $this->persistenceManager->whitelistObject($account); }
/** * @test */ public function getContextHashReturnsStaticStringIfAuthorizationChecksAreDisabled() { $self = $this; $this->securityContext->withoutAuthorizationChecks(function () use($self) { $self->assertSame(Context::CONTEXT_HASH_UNINITIALIZED, $self->securityContext->getContextHash()); }); }
/** * Returns the static value of the given operand, this might be also a global object * * @param mixed $expression The expression string representing the operand * @return mixed The calculated value */ public function getValueForOperand($expression) { if (is_array($expression)) { $result = []; foreach ($expression as $expressionEntry) { $result[] = $this->getValueForOperand($expressionEntry); } return $result; } elseif (is_numeric($expression)) { return $expression; } elseif ($expression === true) { return true; } elseif ($expression === false) { return false; } elseif ($expression === null) { return null; } elseif (strpos($expression, 'context.') === 0) { $objectAccess = explode('.', $expression, 3); $globalObjectsRegisteredClassName = $this->globalObjects[$objectAccess[1]]; $globalObject = $this->objectManager->get($globalObjectsRegisteredClassName); $this->securityContext->withoutAuthorizationChecks(function () use($globalObject, $objectAccess, &$globalObjectValue) { $globalObjectValue = $this->getObjectValueByPath($globalObject, $objectAccess[2]); }); return $globalObjectValue; } else { return trim($expression, '"\''); } }
/** * Returns a node from the given $nodeIdentifier (disabling authorization checks) * * @param string $nodeIdentifier * @return NodeInterface */ protected function getNodeByIdentifier($nodeIdentifier) { $context = $this->contextFactory->create(); $node = null; $this->securityContext->withoutAuthorizationChecks(function () use($nodeIdentifier, $context, &$node) { $node = $context->getNodeByIdentifier($nodeIdentifier); }); $context->getFirstLevelNodeCache()->setByIdentifier($nodeIdentifier, null); return $node; }
/** * Tries to authenticate the tokens in the security context (in the given order) * with the available authentication providers, if needed. * If the authentication strategy is set to "allTokens", all tokens have to be authenticated. * If the strategy is set to "oneToken", only one token needs to be authenticated, but the * authentication will stop after the first authenticated token. The strategy * "atLeastOne" will try to authenticate at least one and as many tokens as possible. * * @return void * @throws Exception * @throws AuthenticationRequiredException */ public function authenticate() { $this->isAuthenticated = false; $anyTokenAuthenticated = false; if ($this->securityContext === null) { throw new Exception('Cannot authenticate because no security context has been set.', 1232978667); } $tokens = $this->securityContext->getAuthenticationTokens(); if (count($tokens) === 0) { throw new NoTokensAuthenticatedException('The security context contained no tokens which could be authenticated.', 1258721059); } /** @var $token TokenInterface */ foreach ($tokens as $token) { /** @var $provider AuthenticationProviderInterface */ foreach ($this->providers as $provider) { if ($provider->canAuthenticate($token) && $token->getAuthenticationStatus() === TokenInterface::AUTHENTICATION_NEEDED) { $provider->authenticate($token); if ($token->isAuthenticated()) { $this->emitAuthenticatedToken($token); } break; } } if ($token->isAuthenticated()) { if (!$token instanceof SessionlessTokenInterface) { if (!$this->session->isStarted()) { $this->session->start(); } $account = $token->getAccount(); if ($account !== null) { $this->securityContext->withoutAuthorizationChecks(function () use($account) { $this->session->addTag('TYPO3-Flow-Security-Account-' . md5($account->getAccountIdentifier())); }); } } if ($this->securityContext->getAuthenticationStrategy() === Context::AUTHENTICATE_ONE_TOKEN) { $this->isAuthenticated = true; $this->securityContext->refreshRoles(); return; } $anyTokenAuthenticated = true; } else { if ($this->securityContext->getAuthenticationStrategy() === Context::AUTHENTICATE_ALL_TOKENS) { throw new AuthenticationRequiredException('Could not authenticate all tokens, but authenticationStrategy was set to "all".', 1222203912); } } } if (!$anyTokenAuthenticated && $this->securityContext->getAuthenticationStrategy() !== Context::AUTHENTICATE_ANY_TOKEN) { throw new NoTokensAuthenticatedException('Could not authenticate any token. Might be missing or wrong credentials or no authentication provider matched.', 1222204027); } $this->isAuthenticated = $anyTokenAuthenticated; $this->securityContext->refreshRoles(); }
/** * Calls a behat step method * * @Flow\Internal * @param string $testHelperObjectName * @param string $methodName * @param boolean $withoutSecurityChecks */ public function callBehatStepCommand($testHelperObjectName, $methodName, $withoutSecurityChecks = false) { $testHelper = $this->objectManager->get($testHelperObjectName); $rawMethodArguments = $this->request->getExceedingArguments(); $mappedArguments = []; for ($i = 0; $i < count($rawMethodArguments); $i += 2) { $mappedArguments[] = $this->propertyMapper->convert($rawMethodArguments[$i + 1], $rawMethodArguments[$i]); } $result = null; try { if ($withoutSecurityChecks === true) { $this->securityContext->withoutAuthorizationChecks(function () use($testHelper, $methodName, $mappedArguments, &$result) { $result = call_user_func_array([$testHelper, $methodName], $mappedArguments); }); } else { $result = call_user_func_array([$testHelper, $methodName], $mappedArguments); } } catch (\Exception $exception) { $this->outputLine('EXCEPTION: %s %d %s in %s:%s %s', [get_class($exception), $exception->getCode(), $exception->getMessage(), $exception->getFile(), $exception->getLine(), $exception->getTraceAsString()]); return; } $this->output('SUCCESS: %s', [$result]); }
/** * Filter a node by the current context. * Will either return the node or NULL if it is not permitted in current context. * * @param NodeInterface $node * @param Context $context * @return NodeInterface|NULL */ protected function filterNodeByContext(NodeInterface $node, Context $context) { $this->securityContext->withoutAuthorizationChecks(function () use(&$node, $context) { if (!$context->isRemovedContentShown() && $node->isRemoved()) { $node = null; return; } if (!$context->isInvisibleContentShown() && !$node->isVisible()) { $node = null; return; } if (!$context->isInaccessibleContentShown() && !$node->isAccessible()) { $node = null; } }); return $node; }
/** * Imports the sub-tree from the xml reader into the given target path. * * The root node of the imported tree becomes a child of the node specified as the target path, * as the following example illustrates: * * 1. Existing Nodes Before Import: * * path * - to * - - my * - - - targetNode * - - - - A * - other * - - nodes * * 2. Sub-tree in xml to import to 'path/to/my/targetNode': * * <B> * - <B1/> * </B> * * 3. existing nodes after the import: * * path * - to * - - my * - - - targetNode * - - - - A * - - - - B * - - - - - B1 * - another * - - sub-tree * * @param \XMLReader $xmlReader The XML input to import - must be either XML as a string or a prepared \XMLReader instance containing XML data * @param string $targetPath path to the node which becomes parent of the root of the imported sub-tree * @param string $resourceLoadPath * @throws ImportException * @return void */ public function import(\XMLReader $xmlReader, $targetPath, $resourceLoadPath = null) { $this->propertyMappingConfiguration = new ImportExportPropertyMappingConfiguration($resourceLoadPath); $this->nodeNameStack = $targetPath === '/' ? array() : array_map(function ($pathSegment) { return Utility::renderValidNodeName($pathSegment); }, explode('/', $targetPath)); $formatVersion = $this->determineFormatVersion($xmlReader); switch ($formatVersion) { case self::SUPPORTED_FORMAT_VERSION: $this->securityContext->withoutAuthorizationChecks(function () use($xmlReader) { $this->importSubtree($xmlReader); }); break; case null: throw new ImportException('Failed to recognize format of the Node Data XML to import. Please make sure that you use a valid Node Data XML structure.', 1409059346); default: throw new ImportException('Failed to import Node Data XML: The format with version ' . $formatVersion . ' is not supported, only version ' . self::SUPPORTED_FORMAT_VERSION . ' is supported.', 1409059352); } }
/** * Matches a frontend URI pointing to a node (for example a page). * * This function tries to find a matching node by the given request path. If one was found, its * absolute context node path is set in $this->value and true is returned. * * Note that this matcher does not check if access to the resolved workspace or node is allowed because at the point * in time the route part handler is invoked, the security framework is not yet fully initialized. * * @param string $requestPath The request path (without leading "/", relative to the current Site Node) * @return boolean true if the $requestPath could be matched, otherwise false * @throws \Exception * @throws Exception\NoHomepageException if no node could be found on the homepage (empty $requestPath) */ protected function matchValue($requestPath) { try { /** @var NodeInterface $node */ $node = null; // Build context explicitly without authorization checks because the security context isn't available yet // anyway and any Entity Privilege targeted on Workspace would fail at this point: $this->securityContext->withoutAuthorizationChecks(function () use(&$node, $requestPath) { $node = $this->convertRequestPathToNode($requestPath); }); } catch (Exception $exception) { $this->systemLogger->log('FrontendNodeRoutePartHandler matchValue(): ' . $exception->getMessage(), LOG_DEBUG); if ($requestPath === '') { throw new Exception\NoHomepageException('Homepage could not be loaded. Probably you haven\'t imported a site yet', 1346950755, $exception); } return false; } if ($this->onlyMatchSiteNodes() && $node !== $node->getContext()->getCurrentSiteNode()) { return false; } $this->value = $node->getContextPath(); return true; }
/** * Find out if the given path exists anywhere in the CR. (internal) * If you need this functionality use \Neos\ContentRepository\Domain\Service\NodeService::nodePathExistsInAnyContext() * * @param string $nodePath * @return boolean */ public function pathExists($nodePath) { $nodePath = strtolower($nodePath); $result = null; /** @var QueryBuilder $queryBuilder */ $queryBuilder = $this->entityManager->createQueryBuilder(); $this->securityContext->withoutAuthorizationChecks(function () use($nodePath, $queryBuilder, &$result) { $queryBuilder->select('n.identifier')->from(NodeData::class, 'n')->where('n.pathHash = :pathHash')->setParameter('pathHash', md5($nodePath)); $result = count($queryBuilder->getQuery()->getResult()) > 0 ? true : false; }); return $result; }