/** * @Flow\Session(autoStart = TRUE) */ public function step2Action() { $form = $this->request->getInternalArgument('__form'); $data = $this->requestToArray(); $captcha = $this->session->getData('captcha'); if ($captcha !== $_POST['captcha']) { $this->addFlashMessage('Kontrollcode leider falsch.', null, \TYPO3\Flow\Error\Message::SEVERITY_WARNING); $this->systemLogger->log('Wrong captcha', LOG_INFO); $this->forward('step1'); } else { if ($data === false) { $this->forward('step1'); } } $processed = $this->session->getData('processed'); if ($processed !== true) { $this->systemLogger->log('Process new form', LOG_INFO); $actions = $this->settings['forms'][$form]['actions']; foreach ($actions as $action => $config) { switch ($action) { case 'email': $this->processEmailAction($config, $data); break; } } $this->systemLogger->log('Form processed', LOG_INFO); $this->session->putData('processed', true); $this->addFlashMessage('Formular erfolgreich verarbeitet.', null, \TYPO3\Flow\Error\Message::SEVERITY_OK); } else { $this->addFlashMessage('Dieses Formular wurde schon verarbeitet und wurde aus diesem Grund nicht erneut gesendet. Vermutlich haben Sie diese Seite neu geladen.', null, \TYPO3\Flow\Error\Message::SEVERITY_NOTICE); } $this->view->assign('data', $data); $this->view->assign('form', $form); }
/** * Redirects to the Neos backend on the given site, passing a one-time login token * * @param Site $site * @return void */ public function switchSiteAction($site) { $token = Algorithms::generateRandomToken(32); $this->loginTokenCache->set($token, $this->currentSession->getId()); $siteUri = $this->linkingService->createSiteUri($this->controllerContext, $site); $loginUri = $this->controllerContext->getUriBuilder()->reset()->uriFor('tokenLogin', ['token' => $token], 'Login', 'TYPO3.Neos'); $this->redirectToUri($siteUri . $loginUri); }
/** * @param string $oauth_verifier * @return array */ public function getToken($oauth_verifier) { $connection = new \Abraham\TwitterOAuth\TwitterOAuth($this->app_key, $this->app_secret, $this->session->getData('oauth_token'), $this->session->getData('oauth_token_secret')); $access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_verifier)); $connection = new \Abraham\TwitterOAuth\TwitterOAuth($this->app_key, $this->app_secret, $access_token['oauth_token'], $access_token['oauth_token_secret']); $credentials = $connection->get('/account/verify_credentials', ['include_entities' => true, 'skip_status' => true, 'include_email' => true]); $access_token['since_id'] = $credentials; return $access_token; }
/** * Redirects to the Neos backend on the given hostname, passing a one-time login token * * @param string $hostname * @return void */ public function switchSiteAction($hostname) { $token = Algorithms::generateRandomToken(32); $this->loginTokenCache->set($token, $this->currentSession->getId()); $requestUri = $this->controllerContext->getRequest()->getHttpRequest()->getUri(); $baseUri = $this->controllerContext->getRequest()->getHttpRequest()->getBaseUri(); $uri = $this->controllerContext->getUriBuilder()->reset()->uriFor('tokenLogin', ['token' => $token], 'Login', 'TYPO3.Neos'); $uri = sprintf('%s://%s%s%s', $requestUri->getScheme(), $hostname, rtrim($baseUri->getPath(), '/'), $uri); $this->redirectToUri($uri); }
/** * Before advice for all methods annotated with "@Flow\Session(autoStart=true)". * Those methods will trigger a session initialization if a session does not exist * yet. * * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current join point * @return void * @fixme The pointcut expression below does not consider the options of the session annotation – needs adjustments in the AOP framework * @Flow\Before("methodAnnotatedWith(TYPO3\Flow\Annotations\Session)") */ public function initializeSession(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) { if ($this->session->isStarted() === TRUE) { return; } $objectName = $this->objectManager->getObjectNameByClassName(get_class($joinPoint->getProxy())); $methodName = $joinPoint->getMethodName(); $this->systemLogger->log(sprintf('Session initialization triggered by %s->%s.', $objectName, $methodName), LOG_DEBUG); $this->session->start(); }
/** * Hooks into the editable viewhelper to render those attributes needed for the package's inline editing * * @Flow\Around("method(TYPO3\Neos\Service\ContentElementEditableService->wrapContentProperty())") * @param JoinPointInterface $joinPoint the join point * @return mixed */ public function editableElementAugmentation(JoinPointInterface $joinPoint) { if (!$this->session->isStarted() || !$this->session->getData('__neosEnabled__')) { return $joinPoint->getAdviceChain()->proceed($joinPoint); } $property = $joinPoint->getMethodArgument('property'); $node = $joinPoint->getMethodArgument('node'); $content = $joinPoint->getAdviceChain()->proceed($joinPoint); $attributes = ['data-__neos-property' => $property]; if ($node !== null) { $attributes += ['data-__neos-editable-node-contextpath' => $node->getContextPath()]; } return $this->htmlAugmenter->addAttributes($content, $attributes, 'span'); }
/** * Returns the specified session. If no session with the given identifier exists, * NULL is returned. * * @param string $sessionIdentifier The session identifier * @return \TYPO3\Flow\Session\Session * @api */ public function getSession($sessionIdentifier) { if ($this->currentSession !== NULL && $this->currentSession->isStarted() && $this->currentSession->getId() === $sessionIdentifier) { return $this->currentSession; } if (isset($this->remoteSessions[$sessionIdentifier])) { return $this->remoteSessions[$sessionIdentifier]; } if ($this->metaDataCache->has($sessionIdentifier)) { $sessionInfo = $this->metaDataCache->get($sessionIdentifier); $this->remoteSessions[$sessionIdentifier] = new Session($sessionIdentifier, $sessionInfo['storageIdentifier'], $sessionInfo['lastActivityTimestamp'], $sessionInfo['tags']); return $this->remoteSessions[$sessionIdentifier]; } }
/** * Tries to authenticate the given token. Sets isAuthenticated to TRUE if authentication succeeded. * * @param \TYPO3\Flow\Security\Authentication\TokenInterface $authenticationToken The token to be authenticated * @return void * @Flow\Session(autoStart=true) */ public function authenticate(\TYPO3\Flow\Security\Authentication\TokenInterface $authenticationToken) { if (!$authenticationToken instanceof SingleSignOnToken) { throw new \TYPO3\Flow\Security\Exception\UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1351008039); } if ($authenticationToken->getAuthenticationStatus() === \TYPO3\Flow\Security\Authentication\TokenInterface::AUTHENTICATION_NEEDED) { // Verify signature with server public key $credentials = $authenticationToken->getCredentials(); $signature = $credentials['signature']; $accessTokenCipher = $credentials['accessToken']; $ssoServer = $this->createSsoServer(); if (!$ssoServer->verifyCallbackSignature($accessTokenCipher, $signature)) { throw new Exception('Could not verify signature of access token', 1351008742); } $ssoClient = $this->ssoClientFactory->create(); $accessToken = $ssoClient->decryptCallbackAccessToken($accessTokenCipher); if ($accessToken === '') { throw new Exception('Could not decrypt access token', 1351690950); } $authenticationData = $ssoServer->redeemAccessToken($ssoClient, $accessToken); // TODO Check validity of authentication data (presence of "account" and "sessionId") $account = $this->globalAccountMapper->getAccount($ssoClient, $authenticationData['account']); $globalSessionId = $authenticationData['sessionId']; $this->session->addTag('Flowpack_SingleSignOn_Client-' . $globalSessionId); $authenticationToken->setGlobalSessionId($globalSessionId); $authenticationToken->setAccount($account); $authenticationToken->setAuthenticationStatus(\TYPO3\Flow\Security\Authentication\TokenInterface::AUTHENTICATION_SUCCESSFUL); } elseif ($authenticationToken->getAuthenticationStatus() !== \TYPO3\Flow\Security\Authentication\TokenInterface::AUTHENTICATION_SUCCESSFUL) { $authenticationToken->setAuthenticationStatus(\TYPO3\Flow\Security\Authentication\TokenInterface::NO_CREDENTIALS_GIVEN); } }
/** * Shows the specified node and takes visibility and access restrictions into * account. * * @param NodeInterface $node * @return string View output for the specified node * @Flow\SkipCsrfProtection We need to skip CSRF protection here because this action could be called with unsafe requests from widgets or plugins that are rendered on the node - For those the CSRF token is validated on the sub-request, so it is safe to be skipped here * @Flow\IgnoreValidation("node") * @throws NodeNotFoundException */ public function showAction(NodeInterface $node = NULL) { if ($node === NULL) { throw new NodeNotFoundException('The requested node does not exist or isn\'t accessible to the current user', 1430218623); } if (!$node->getContext()->isLive() && !$this->privilegeManager->isPrivilegeTargetGranted('TYPO3.Neos:Backend.GeneralAccess')) { $this->redirect('index', 'Login', NULL, array('unauthorized' => TRUE)); } $inBackend = $node->getContext()->isInBackend(); if ($node->getNodeType()->isOfType('TYPO3.Neos:Shortcut') && !$inBackend) { $this->handleShortcutNode($node); } $this->view->assign('value', $node); if ($inBackend) { $this->overrideViewVariablesFromInternalArguments(); /** @var UserInterfaceMode $renderingMode */ $renderingMode = $node->getContext()->getCurrentRenderingMode(); $this->response->setHeader('Cache-Control', 'no-cache'); if ($renderingMode !== NULL) { // Deprecated TypoScript context variable from version 2.0. $this->view->assign('editPreviewMode', $renderingMode->getTypoScriptPath()); } if (!$this->view->canRenderWithNodeAndPath()) { $this->view->setTypoScriptPath('rawContent'); } } if ($this->session->isStarted() && $inBackend) { $this->session->putData('lastVisitedNode', $node->getContextPath()); } }
/** * @test */ public function logoutRefreshesTokensInSecurityContext() { $this->authenticationProviderManager = $this->getAccessibleMock(\TYPO3\Flow\Security\Authentication\AuthenticationProviderManager::class, array('emitLoggedOut'), array(), '', false); $this->inject($this->authenticationProviderManager, 'securityContext', $this->mockSecurityContext); $this->inject($this->authenticationProviderManager, 'session', $this->mockSession); $this->mockSession->expects($this->any())->method('canBeResumed')->will($this->returnValue(true)); $this->mockSession->expects($this->any())->method('isStarted')->will($this->returnValue(true)); $token = $this->createMock(\TYPO3\Flow\Security\Authentication\TokenInterface::class); $token->expects($this->any())->method('isAuthenticated')->will($this->returnValue(true)); $this->mockSecurityContext->expects($this->any())->method('getAuthenticationTokens')->will($this->returnValue(array($token))); $this->mockSecurityContext->expects($this->once())->method('refreshTokens'); $this->authenticationProviderManager->logout(); }
/** * * @param string $workspaceName * @return NodeInterface */ protected function getLastVisitedNode($workspaceName) { if (!$this->session->isStarted() || !$this->session->hasKey('lastVisitedNode')) { return null; } try { $lastVisitedNode = $this->propertyMapper->convert($this->session->getData('lastVisitedNode'), NodeInterface::class); $q = new FlowQuery([$lastVisitedNode]); $lastVisitedNodeUserWorkspace = $q->context(['workspaceName' => $workspaceName])->get(0); return $lastVisitedNodeUserWorkspace; } catch (\Exception $exception) { return null; } }
/** * Logout all active authentication tokens * * @return void */ public function logout() { if ($this->isAuthenticated() !== TRUE) { return; } $this->isAuthenticated = NULL; /** @var $token TokenInterface */ foreach ($this->securityContext->getAuthenticationTokens() as $token) { $token->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN); } $this->emitLoggedOut(); if ($this->session->isStarted()) { $this->session->destroy('Logout through AuthenticationProviderManager'); } }
/** * Is called if authentication was successful. * * @param ActionRequest $originalRequest The request that was intercepted by the security framework, NULL if there was none * @return void */ public function onAuthenticationSuccess(ActionRequest $originalRequest = null) { if ($this->view instanceof JsonView) { $this->view->assign('value', array('success' => $this->authenticationManager->isAuthenticated(), 'csrfToken' => $this->securityContext->getCsrfProtectionToken())); } else { if ($this->request->hasArgument('lastVisitedNode') && strlen($this->request->getArgument('lastVisitedNode')) > 0) { $this->session->putData('lastVisitedNode', $this->request->getArgument('lastVisitedNode')); } if ($originalRequest !== null) { // Redirect to the location that redirected to the login form because the user was nog logged in $this->redirectToRequest($originalRequest); } $this->redirect('index', 'Backend\\Backend'); } }
/** * Displays the backend interface * * @param NodeInterface $node The node that will be displayed on the first tab * @return void */ public function indexAction(NodeInterface $node = null) { $this->contentCache->flush(); $this->session->start(); $this->session->putData('__cheEnabled__', true); if ($user = $this->userService->getBackendUser()) { $workspaceName = $this->userService->getPersonalWorkspaceName(); $contentContext = $this->createContext($workspaceName); $contentContext->getWorkspace(); $this->persistenceManager->persistAll(); $siteNode = $contentContext->getCurrentSiteNode(); if ($node === null) { $node = $siteNode; } $this->view->assign('user', $user); $this->view->assign('documentNode', $node); $this->view->assign('site', $node); $this->view->assign('translations', $this->xliffService->getCachedJson(new Locale($this->userService->getInterfaceLanguage()))); return; } $this->redirectToUri($this->uriBuilder->uriFor('index', array(), 'Login', 'TYPO3.Neos')); }
/** * @test */ public function logoutEmitsLoggedOutSignalBeforeDestroyingSession() { $this->authenticationProviderManager = $this->getAccessibleMock('TYPO3\\Flow\\Security\\Authentication\\AuthenticationProviderManager', array('emitLoggedOut'), array(), '', FALSE); $this->authenticationProviderManager->_set('session', $this->mockSession); $this->mockSession->expects($this->any())->method('canBeResumed')->will($this->returnValue(TRUE)); $this->mockSession->expects($this->any())->method('isStarted')->will($this->returnValue(TRUE)); $token = $this->getMock('TYPO3\\Flow\\Security\\Authentication\\TokenInterface', array(), array(), '', FALSE); $token->expects($this->any())->method('isAuthenticated')->will($this->returnValue(TRUE)); $mockContext = $this->getMock('TYPO3\\Flow\\Security\\Context', array(), array(), '', FALSE); $mockContext->expects($this->any())->method('getAuthenticationTokens')->will($this->returnValue(array($token))); $loggedOutEmitted = FALSE; $this->authenticationProviderManager->expects($this->once())->method('emitLoggedOut')->will($this->returnCallback(function () use(&$loggedOutEmitted) { $loggedOutEmitted = TRUE; })); $this->mockSession->expects($this->once())->method('destroy')->will($this->returnCallback(function () use(&$loggedOutEmitted) { if (!$loggedOutEmitted) { \PHPUnit_Framework_Assert::fail('emitLoggedOut was not called before destroy'); } })); $this->authenticationProviderManager->setSecurityContext($mockContext); $this->authenticationProviderManager->logout(); }
/** * Returns the publish path and filename to be used to publish the specified persistent resource * * @Flow\Around("method(TYPO3\Flow\Resource\Publishing\FileSystemPublishingTarget->buildPersistentResourcePublishPathAndFilename()) && setting(TYPO3.Flow.security.enable)") * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint The current join point * @return mixed Result of the target method */ public function rewritePersistentResourcePublishPathAndFilenameForPrivateResources(\TYPO3\Flow\Aop\JoinPointInterface $joinPoint) { $resource = $joinPoint->getMethodArgument('resource'); /** @var $configuration \TYPO3\Flow\Security\Authorization\Resource\SecurityPublishingConfiguration */ $configuration = $resource->getPublishingConfiguration(); $returnFilename = $joinPoint->getMethodArgument('returnFilename'); if ($configuration === NULL || $configuration instanceof \TYPO3\Flow\Security\Authorization\Resource\SecurityPublishingConfiguration === FALSE) { return $joinPoint->getAdviceChain()->proceed($joinPoint); } $publishingPath = FALSE; $allowedRoles = $configuration->getAllowedRoles(); if (count(array_intersect($allowedRoles, $this->securityContext->getRoles())) > 0) { $publishingPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($joinPoint->getProxy()->getResourcesPublishingPath(), 'Persistent/', $this->session->getID())) . '/'; $filename = $resource->getResourcePointer()->getHash() . '.' . $resource->getFileExtension(); \TYPO3\Flow\Utility\Files::createDirectoryRecursively($publishingPath); $this->accessRestrictionPublisher->publishAccessRestrictionsForPath($publishingPath); if ($this->settings['resource']['publishing']['fileSystem']['mirrorMode'] === 'link') { foreach ($allowedRoles as $role) { $roleDirectory = \TYPO3\Flow\Utility\Files::concatenatePaths(array($this->environment->getPathToTemporaryDirectory(), 'PrivateResourcePublishing/', $role)); \TYPO3\Flow\Utility\Files::createDirectoryRecursively($roleDirectory); if (file_exists($publishingPath . $role)) { if (\TYPO3\Flow\Utility\Files::is_link(\TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role))) && realpath(\TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role))) === $roleDirectory) { continue; } unlink($publishingPath . $role); symlink($roleDirectory, \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role))); } else { symlink($roleDirectory, \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $role))); } } $publishingPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $allowedRoles[0])) . '/'; } if ($returnFilename === TRUE) { $publishingPath = \TYPO3\Flow\Utility\Files::concatenatePaths(array($publishingPath, $filename)); } } return $publishingPath; }
/** * @param \Peytz\Vote\Domain\Model\Vote $newVote * @return void */ public function registerAction(Vote $newVote) { if (!$this->session->isStarted()) { $this->session->start(); } /** @var \Peytz\Vote\Domain\Model\Vote $vote */ if ($vote = $this->voteRepository->findOneBySession($this->session->getId())) { $vote->setDate(new \DateTime()); $vote->setValue($newVote->getValue()); $this->voteRepository->update($vote); } else { $newVote->setDate(new \DateTime()); $newVote->setSession($this->session->getId()); $this->voteRepository->add($newVote); } $this->session->putData('hasVoted', true); $this->addFlashMessage('Vote registered.'); $this->redirect('index'); }
/** * @Flow\Session(autoStart = true) * @return string */ public function sessionStartAction() { return 'this action started session ' . $this->session->getId(); }
public function isRemembered() { return $this->session->hasKey("recaptcha_timestamp") && $this->session->getData("recaptcha_timestamp") > time() - (int) $this->settings["security"]["validTime"]; }
/** * @Flow\Before("method(TYPO3\Neos\Controller\Backend\BackendController->indexAction())") * @param JoinPointInterface $joinPoint the join point * @return mixed */ public function disableNewUserInterface(JoinPointInterface $joinPoint) { $this->contentCache->flush(); $this->session->start(); $this->session->putData('__cheEnabled__', false); }
public function enableNewBackend() { return $this->session->isStarted() && $this->session->getData('__cheEnabled__'); }
/** * @param string $actionName Name of the action to forward to * @param string $controllerName Unqualified object name of the controller to forward to. If not specified, the current controller is used. * @param string $packageKey Key of the package containing the controller to forward to. If not specified, the current package is assumed. * @param array $arguments Array of arguments for the target action * @param integer $delay (optional) The delay in seconds. Default is no delay. * @param integer $statusCode (optional) The HTTP status code for the redirect. Default is "303 See Other" * @param string $format The format to use for the redirect URI * @return void */ protected function unsetLastVisitedNodeAndRedirect($actionName, $controllerName = null, $packageKey = null, array $arguments = null, $delay = 0, $statusCode = 303, $format = null) { $this->session->putData('lastVisitedNode', null); parent::redirect($actionName, $controllerName, $packageKey, $arguments, $delay, $statusCode, $format); }
/** * @param string $social * @return void */ public function socialAction($social = NULL) { $args = $this->request->getArguments(); switch ($social) { case "facebook": if ($args['connectorjson'] !== NULL) { $response = json_decode($args['connectorjson'], true); $token = $response['accessToken']; $facebookAccounts = $this->facebookService->getAccounts($token); $facebookImage = "https:////graph.facebook.com/" . $facebookAccounts['id'] . "/picture?type=large"; $this->createSocialAccount('facebook-' . $facebookAccounts['id'], $facebookAccounts['id'], $facebookAccounts['id'], $facebookAccounts['first_name'], $facebookAccounts['last_name'], $facebookImage, $facebookAccounts['email'], $network = "facebook", $args['return_url']); } else { $this->addFlashMessage("access_denied"); $this->redirect('index', 'Standard'); } break; case "vk": if (isset($args['code']) && $args['code'] !== NULL) { $token = $this->vkService->getToken($args['code']); if (isset($token['error']) && $token['error'] != NULL) { $this->addFlashMessage($token['error']); $this->redirect('index', 'Standard'); } $data = json_decode($token); $vkAccounts = $this->vkService->getAccounts($data->access_token, $data->user_id); if ($args['state'] !== null) { $returnUrl = $this->base64UrlDecode($args['state']); } $this->createSocialAccount('vk-' . $vkAccounts['response'][0]['uid'], $vkAccounts['response'][0]['uid'], $vkAccounts['response'][0]['uid'], $vkAccounts['response'][0]['first_name'], $vkAccounts['response'][0]['last_name'], $vkAccounts['response'][0]['photo_big'], $data->email, $network = "vk", $returnUrl); } else { $this->addFlashMessage("access_denied"); $this->redirect('index', 'Standard'); } break; case "googleplus": if (isset($args['code']) && $args['code'] !== NULL) { $token = $this->googlePlusService->getToken($args['code']); if (!isset($token->access_token)) { $this->addFlashMessage($token->error_description); $this->redirect('index', 'Standard'); } $googleAccounts = $this->googlePlusService->getAccounts($token->access_token); if ($args['state'] !== null) { $returnUrl = $this->base64UrlDecode($args['state']); } $this->createSocialAccount('googlePlus-' . $googleAccounts['id'], $googleAccounts['id'], $googleAccounts['id'], $googleAccounts['name']['familyName'], $googleAccounts['name']['givenName'], $googleAccounts['image']['url'], $googleAccounts['emails'][0]['value'], $network = "googlePlus", $returnUrl); } else { $this->addFlashMessage("access_denied"); $this->redirect('index', 'Standard'); } break; case "twitter": if (isset($args['oauth_verifier']) && $args['oauth_verifier'] !== NULL) { $response = $this->twitterService->getToken($args['oauth_verifier']); $returnUrl = $this->base64UrlDecode($this->session->getData('return_url')); if ($response !== NULL) { $user_id = $response['user_id']; $fullName = explode(" ", $response['since_id']->name); $this->createSocialAccount('twitter-' . $user_id, $user_id, $user_id, $fullName[0], $fullName[1], $response['since_id']->profile_image_url, '', $network = "twitter", $returnUrl); } } else { $this->addFlashMessage('Something get wrong. Please, try again.', "Error", 'Error'); $this->redirect('index', 'Standard'); } break; } }
/** * @return void */ public function indexAction() { $this->session->start(); }