/**
  * Checks the given token for validity and sets the token authentication status
  * accordingly (success, wrong credentials or no credentials given).
  *
  * @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.', 1217339840);
     }
     /** @var $account \TYPO3\Flow\Security\Account */
     $account = NULL;
     $credentials = $authenticationToken->getCredentials();
     if (is_array($credentials) && isset($credentials['username'])) {
         $providerName = $this->name;
         $accountRepository = $this->accountRepository;
         $this->securityContext->withoutAuthorizationChecks(function () use($credentials, $providerName, $accountRepository, &$account) {
             $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($credentials['username'], $providerName);
         });
     }
     if (is_object($account)) {
         if ($this->hashService->validatePassword($credentials['password'], $account->getCredentialsSource())) {
             $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);
     }
 }
 /**
  * @test
  */
 public function authenticationFailsWithWrongCredentialsInAnUsernamePasswordToken()
 {
     $this->mockHashService->expects($this->once())->method('validatePassword')->with('wrong password', '8bf0abbb93000e2e47f0e0a80721e834,80f117a78cff75f3f73793fd02aa9086')->will($this->returnValue(FALSE));
     $this->mockAccount->expects($this->once())->method('getCredentialsSource')->will($this->returnValue('8bf0abbb93000e2e47f0e0a80721e834,80f117a78cff75f3f73793fd02aa9086'));
     $this->mockAccountRepository->expects($this->once())->method('findActiveByAccountIdentifierAndAuthenticationProviderName')->with('admin', 'myProvider')->will($this->returnValue($this->mockAccount));
     $this->mockToken->expects($this->once())->method('getCredentials')->will($this->returnValue(array('username' => 'admin', 'password' => 'wrong password')));
     $this->mockToken->expects($this->once())->method('setAuthenticationStatus')->with(\TYPO3\Flow\Security\Authentication\TokenInterface::WRONG_CREDENTIALS);
     $this->persistedUsernamePasswordProvider->authenticate($this->mockToken);
 }
Beispiel #3
0
 /**
  * Renders hidden form fields for referrer information about
  * the current request.
  *
  * @return string Hidden fields with referrer information
  */
 protected function renderHiddenReferrerFields()
 {
     $tagBuilder = new TagBuilder('input');
     $tagBuilder->addAttribute('type', 'hidden');
     $tagBuilder->addAttribute('name', $this->prefixFieldName('__state'));
     $serializedFormState = base64_encode(serialize($this->arguments['object']->getFormState()));
     $tagBuilder->addAttribute('value', $this->hashService->appendHmac($serializedFormState));
     return $tagBuilder->render();
 }
 public function getEncryptedPasswordAndRemoveNonencryptedVersion()
 {
     if (!$this->arePasswordsEqual()) {
         throw new Exception('Passwords are not equal; so it is not allowed to call getEncryptedPassword().', 1464087097);
     }
     $encrypted = $this->hashService->hashPassword($this->password);
     $this->password = null;
     $this->passwordConfirmation = null;
     return $encrypted;
 }
 /**
  * Extracts the WidgetContext from the given $httpRequest.
  * If the request contains an argument "__widgetId" the context is fetched from the session (AjaxWidgetContextHolder).
  * Otherwise the argument "__widgetContext" is expected to contain the serialized WidgetContext (protected by a HMAC suffix)
  *
  * @param Request $httpRequest
  * @return WidgetContext
  */
 protected function extractWidgetContext(Request $httpRequest)
 {
     if ($httpRequest->hasArgument('__widgetId')) {
         return $this->ajaxWidgetContextHolder->get($httpRequest->getArgument('__widgetId'));
     } elseif ($httpRequest->hasArgument('__widgetContext')) {
         $serializedWidgetContextWithHmac = $httpRequest->getArgument('__widgetContext');
         $serializedWidgetContext = $this->hashService->validateAndStripHmac($serializedWidgetContextWithHmac);
         return unserialize(base64_decode($serializedWidgetContext));
     }
     return null;
 }
 /**
  * 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 validateAndStripHmacReturnsTheStringWithoutHmac()
 {
     $string = ' Some arbitrary string with special characters: öäüß!"§$ ';
     $hashedString = $this->hashService->appendHmac($string);
     $actualResult = $this->hashService->validateAndStripHmac($hashedString);
     $this->assertSame($string, $actualResult);
 }
 /**
  * @param string $emailAddress
  * @param string $requirement
  *
  * @throws \Exception
  *
  * @return string
  */
 public function resetPasswordAction($emailAddress, $requirement = '')
 {
     if ($requirement !== '') {
         throw new \Exception('Bot detection', 12393182738);
     }
     $locale = new Locale('nl');
     $account = $this->accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($emailAddress, 'DefaultProvider');
     if ($account instanceof Account) {
         try {
             /** @var Person $profile */
             $profile = $this->profileService->getProfileNodeOfAccount($account);
             $password = $this->randomPassword();
             $hashedPassword = $this->hashService->hashPassword($password, 'default');
             $this->mailerService->sendEmail(array('email' => $emailAddress, 'name' => $profile->getDisplayName()), 'Nieuw wachtwoord', 'Packages/Application/BuJitsuDo.Authentication/Resources/Private/Templates/Email/PasswordReset.html', array('password' => $password, 'profile' => $profile));
             $account->setCredentialsSource($hashedPassword);
             $this->accountRepository->update($account);
             $this->persistenceManager->persistAll();
         } catch (\Exception $exception) {
             return $exception->getMessage();
         }
     } else {
         $this->response->setHeader('Notification', $this->translator->translateById('profile.reset.password.response.failure', [], NULL, $locale, 'Main', 'BuJitsuDo.Authentication'));
         $this->response->setHeader('NotificationType', 'alert');
         return '';
     }
     $this->response->setHeader('Notification', $this->translator->translateById('profile.reset.password.response.success', [], NULL, $locale, 'Main', 'BuJitsuDo.Authentication'));
     $this->response->setHeader('NotificationType', 'success');
     return '';
 }
Beispiel #9
0
 /**
  * @return string
  * @throws \TYPO3\Flow\Security\Exception\InvalidArgumentForHashGenerationException
  */
 public function getJWTToken()
 {
     /** @var \TYPO3\Flow\Security\Account $account */
     $account = $this->securityContext->getAccount();
     $this->apiToken = $this->securityContext->getAuthenticationTokensOfType('RFY\\JWT\\Security\\Authentication\\Token\\JwtToken')[0];
     if ($account->getAuthenticationProviderName() !== $this->apiToken->getAuthenticationProviderName()) {
         // TODO: Currently you can get only 1 tokenAccount because of the duplication restraint based on accountIdentifier & AuthenticationProviderName
         $account = $this->accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($account->getAccountIdentifier(), $this->apiToken->getAuthenticationProviderName());
         if ($account === NULL) {
             $account = $this->generateTokenAccount();
         }
     }
     $payload = array();
     $payload['identifier'] = $account->getAccountIdentifier();
     $payload['partyIdentifier'] = $this->persistenceManager->getIdentifierByObject($account->getParty());
     $payload['user_agent'] = $this->request->getHeader('User-Agent');
     $payload['ip_address'] = $this->request->getClientIpAddress();
     if ($account->getCreationDate() instanceof \DateTime) {
         $payload['creationDate'] = $account->getCreationDate()->getTimestamp();
     }
     if ($account->getExpirationDate() instanceof \DateTime) {
         $payload['expirationDate'] = $account->getExpirationDate()->getTimestamp();
     }
     // Add hmac
     $hmac = $this->hashService->generateHmac($this->signature);
     return JWT::encode($payload, $hmac);
 }
 /**
  * Returns an ActionRequest which referred to this request, if any.
  *
  * The referring request is not set or determined automatically but must be
  * explicitly set through the corresponding internal argument "__referrer".
  * This mechanism is used by Flow's form and validation mechanisms.
  *
  * @return ActionRequest the referring request, or NULL if no referrer found
  */
 public function getReferringRequest()
 {
     if ($this->referringRequest !== null) {
         return $this->referringRequest;
     }
     if (!isset($this->internalArguments['__referrer'])) {
         return null;
     }
     if (is_array($this->internalArguments['__referrer'])) {
         $referrerArray = $this->internalArguments['__referrer'];
         $referringRequest = new ActionRequest($this->getHttpRequest());
         $arguments = array();
         if (isset($referrerArray['arguments'])) {
             $serializedArgumentsWithHmac = $referrerArray['arguments'];
             $serializedArguments = $this->hashService->validateAndStripHmac($serializedArgumentsWithHmac);
             $arguments = unserialize(base64_decode($serializedArguments));
             unset($referrerArray['arguments']);
         }
         $referringRequest->setArguments(Arrays::arrayMergeRecursiveOverrule($arguments, $referrerArray));
         return $referringRequest;
     } else {
         $this->referringRequest = $this->internalArguments['__referrer'];
     }
     return $this->referringRequest;
 }
 public function setUp()
 {
     $this->mockRole = $this->getMockBuilder('TYPO3\\Flow\\Security\\Policy\\Role')->disableOriginalConstructor()->getMock();
     $this->mockRole->expects($this->any())->method('getIdentifier')->will($this->returnValue('TYPO3.Flow:TestRoleIdentifier'));
     $this->mockPolicyService = $this->getMockBuilder('TYPO3\\Flow\\Security\\Policy\\PolicyService')->disableOriginalConstructor()->getMock();
     $this->mockPolicyService->expects($this->any())->method('getRole')->with('TYPO3.Flow:TestRoleIdentifier')->will($this->returnValue($this->mockRole));
     $this->mockHashService = $this->getMockBuilder('TYPO3\\Flow\\Security\\Cryptography\\HashService')->disableOriginalConstructor()->getMock();
     $expectedPassword = $this->testKeyClearText;
     $expectedHashedPasswordAndSalt = $this->testKeyHashed;
     $this->mockHashService->expects($this->any())->method('validatePassword')->will($this->returnCallback(function ($password, $hashedPasswordAndSalt) use($expectedPassword, $expectedHashedPasswordAndSalt) {
         return $hashedPasswordAndSalt === $expectedHashedPasswordAndSalt && $password === $expectedPassword;
     }));
     $this->mockFileBasedSimpleKeyService = $this->getMockBuilder('TYPO3\\Flow\\Security\\Cryptography\\FileBasedSimpleKeyService')->disableOriginalConstructor()->getMock();
     $this->mockFileBasedSimpleKeyService->expects($this->any())->method('getKey')->with('testKey')->will($this->returnValue($this->testKeyHashed));
     $this->mockToken = $this->getMockBuilder('TYPO3\\Flow\\Security\\Authentication\\Token\\PasswordToken')->disableOriginalConstructor()->getMock();
 }
 /**
  * Renders hidden form fields for referrer information about
  * the current controller and action.
  *
  * @return string Hidden fields with referrer information
  * @todo filter out referrer information that is equal to the target (e.g. same packageKey)
  */
 protected function renderHiddenReferrerFields()
 {
     $result = chr(10);
     $request = $this->controllerContext->getRequest();
     $argumentNamespace = NULL;
     if (!$request->isMainRequest()) {
         $argumentNamespace = $request->getArgumentNamespace();
         $referrer = array('@package' => $request->getControllerPackageKey(), '@subpackage' => $request->getControllerSubpackageKey(), '@controller' => $request->getControllerName(), '@action' => $request->getControllerActionName(), 'arguments' => $this->hashService->appendHmac(base64_encode(serialize($request->getArguments()))));
         foreach ($referrer as $referrerKey => $referrerValue) {
             $referrerValue = \htmlspecialchars($referrerValue);
             $result .= '<input type="hidden" name="' . $argumentNamespace . '[__referrer][' . $referrerKey . ']" value="' . $referrerValue . '" />' . chr(10);
         }
         $request = $request->getParentRequest();
     }
     $arguments = $request->getArguments();
     if ($argumentNamespace !== NULL && isset($arguments[$argumentNamespace])) {
         // A sub request was there; thus we can unset the sub requests arguments,
         // as they are transferred separately via the code block shown above.
         unset($arguments[$argumentNamespace]);
     }
     $referrer = array('@package' => $request->getControllerPackageKey(), '@subpackage' => $request->getControllerSubpackageKey(), '@controller' => $request->getControllerName(), '@action' => $request->getControllerActionName(), 'arguments' => $this->hashService->appendHmac(base64_encode(serialize($arguments))));
     foreach ($referrer as $referrerKey => $referrerValue) {
         $result .= '<input type="hidden" name="__referrer[' . $referrerKey . ']' . '" value="' . htmlspecialchars($referrerValue) . '" />' . chr(10);
     }
     return $result;
 }
Beispiel #13
0
 /**
  * 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 JwtToken) {
         throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1417040168);
     }
     /** @var $account Account */
     $account = NULL;
     $credentials = $authenticationToken->getCredentials();
     if (!is_array($credentials) || !isset($credentials['token'])) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::NO_CREDENTIALS_GIVEN);
         return;
     }
     $hmac = $this->hashService->generateHmac($this->signature);
     $payload = NULL;
     try {
         $payload = (array) JWT::decode($credentials['token'], $hmac, array('HS256'));
     } catch (\Exception $exception) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
     }
     if (isset($credentials['username'])) {
         $providerName = $this->name;
         $accountRepository = $this->accountRepository;
         $this->securityContext->withoutAuthorizationChecks(function () use($credentials, $providerName, $accountRepository, &$account) {
             $account = $accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($credentials['username'], $providerName);
         });
         if ($this->hashService->validatePassword($credentials['password'], $account->getCredentialsSource())) {
             $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
             $authenticationToken->setAccount($account);
             return;
         } else {
             $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
             return;
         }
     }
     if ($credentials['user_agent'] === $payload['user_agent'] && $credentials['ip_address'] === $payload['ip_address']) {
         $this->securityContext->withoutAuthorizationChecks(function () use($payload, &$account) {
             $account = $this->accountRepository->findActiveByAccountIdentifierAndAuthenticationProviderName($payload['identifier'], $this->name);
         });
     }
     if (is_object($account)) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
         $authenticationToken->setAccount($account);
         return;
     }
     $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
     return;
 }
 /**
  * Sets a new password for the given user
  *
  * @param User $user The user to set the password for
  * @param string $password A new password
  * @return void
  */
 public function setUserPassword(User $user, $password)
 {
     foreach ($user->getAccounts() as $account) {
         /** @var Account $account */
         $account->setCredentialsSource($this->hashService->hashPassword($password, 'default'));
         $this->accountRepository->update($account);
     }
 }
 /**
  * An advice which intercepts the original route() method if a widget AJAX request
  * was identified.
  *
  * If the HTTP request contains an argument hinting on an AJAX request directed
  * to a widget, this method will create a matching ActionRequest rather than
  * invoking the whole routing mechanism.
  *
  * @Flow\Around("method(TYPO3\Flow\Mvc\Routing\Router->route())")
  * @param \TYPO3\Flow\Aop\JoinPointInterface $joinPoint
  * @return \TYPO3\Flow\Mvc\ActionRequest
  */
 public function routeAjaxWidgetRequestAdvice(JoinPointInterface $joinPoint)
 {
     $httpRequest = $joinPoint->getMethodArgument('httpRequest');
     if ($httpRequest->hasArgument('__widgetId') || $httpRequest->hasArgument('__widgetContext')) {
         $actionRequest = $httpRequest->createActionRequest();
         $widgetId = $actionRequest->getInternalArgument('__widgetId');
         if ($widgetId !== NULL) {
             $widgetContext = $this->ajaxWidgetContextHolder->get($widgetId);
         } else {
             $serializedWidgetContextWithHmac = $actionRequest->getInternalArgument('__widgetContext');
             $serializedWidgetContext = $this->hashService->validateAndStripHmac($serializedWidgetContextWithHmac);
             $widgetContext = unserialize($serializedWidgetContext);
         }
         $actionRequest->setArgument('__widgetContext', $widgetContext);
         $actionRequest->setControllerObjectName($widgetContext->getControllerObjectName());
         return $actionRequest;
     } else {
         return $joinPoint->getAdviceChain()->proceed($joinPoint);
     }
 }
 /**
  * Persists a key to the file system
  *
  * @param string $name
  * @param string $password
  * @return void
  * @throws \TYPO3\Flow\Security\Exception
  */
 protected function persistKey($name, $password)
 {
     $hashedPassword = $this->hashService->hashPassword($password, $this->passwordHashingStrategy);
     $keyPathAndFilename = $this->getKeyPathAndFilename($name);
     if (!is_dir($this->getPath())) {
         Files::createDirectoryRecursively($this->getPath());
     }
     $result = file_put_contents($keyPathAndFilename, $hashedPassword);
     if ($result === false) {
         throw new \TYPO3\Flow\Security\Exception(sprintf('The key could not be stored ("%s").', $keyPathAndFilename), 1305812921);
     }
 }
 /**
  * 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 web accessible URI pointing to the specified persistent resource
  *
  * @param Resource $resource Resource object
  * @return string The URI
  * @throws Exception
  */
 public function getPublicPersistentResourceUri(Resource $resource)
 {
     $resourceData = array('resourceIdentifier' => $resource->getSha1());
     if ($this->shouldIncludeSecurityContext()) {
         $resourceData['securityContextHash'] = $this->securityContext->getContextHash();
     } elseif (!empty($this->options['tokenLifetime'])) {
         $expirationDateTime = clone $this->now;
         $expirationDateTime = $expirationDateTime->modify(sprintf('+%d seconds', $this->options['tokenLifetime']));
         $resourceData['expirationDateTime'] = $expirationDateTime->format(\DateTime::ISO8601);
     }
     $encodedResourceData = base64_encode(json_encode($resourceData));
     $signedResourceData = $this->hashService->appendHmac($encodedResourceData);
     return $this->detectResourcesBaseUri() . '?__protectedResource=' . $signedResourceData;
 }
 /**
  * @test
  */
 public function extractWidgetContextDecodesSerializedWidgetContextIfPresent()
 {
     $ajaxWidgetComponent = $this->getAccessibleMock(\TYPO3\Fluid\Core\Widget\AjaxWidgetComponent::class, array('dummy'));
     $this->inject($ajaxWidgetComponent, 'hashService', $this->mockHashService);
     $mockWidgetContext = 'SomeWidgetContext';
     $mockSerializedWidgetContext = base64_encode(serialize($mockWidgetContext));
     $mockSerializedWidgetContextWithHmac = $mockSerializedWidgetContext . 'HMAC';
     $this->mockHttpRequest->expects($this->at(0))->method('hasArgument')->with('__widgetId')->will($this->returnValue(false));
     $this->mockHttpRequest->expects($this->at(1))->method('hasArgument')->with('__widgetContext')->will($this->returnValue(true));
     $this->mockHttpRequest->expects($this->atLeastOnce())->method('getArgument')->with('__widgetContext')->will($this->returnValue($mockSerializedWidgetContextWithHmac));
     $this->mockHashService->expects($this->atLeastOnce())->method('validateAndStripHmac')->with($mockSerializedWidgetContextWithHmac)->will($this->returnValue($mockSerializedWidgetContext));
     $actualResult = $ajaxWidgetComponent->_call('extractWidgetContext', $this->mockHttpRequest);
     $this->assertEquals($mockWidgetContext, $actualResult);
 }
 /**
  * @param ComponentContext $componentContext
  * @return void
  * @throws FileNotFoundException|AccessDeniedException|FlowException
  */
 public function handle(ComponentContext $componentContext)
 {
     $httpRequest = $componentContext->getHttpRequest();
     if (!$httpRequest->hasArgument('__protectedResource')) {
         return;
     }
     try {
         $encodedResourceData = $this->hashService->validateAndStripHmac($httpRequest->getArgument('__protectedResource'));
     } catch (InvalidHashException $exception) {
         throw new AccessDeniedException('Invalid HMAC!', 1421241393, $exception);
     }
     $tokenData = json_decode(base64_decode($encodedResourceData), TRUE);
     $this->verifyExpiration($tokenData);
     $this->verifySecurityContextHash($tokenData, $httpRequest);
     $resource = $this->resourceManager->getResourceBySha1($tokenData['resourceIdentifier']);
     if ($resource === NULL) {
         throw new FileNotFoundException(sprintf('Unknown resource!%sCould not find resource with identifier "%s"', chr(10), $tokenData['resourceIdentifier']), 1429621743);
     }
     // TODO there should be a better way to determine the absolute path of the resource? Resource::createTemporaryLocalCopy() is too expensive
     $resourcePathAndFilename = Files::concatenatePaths(array($this->options['basePath'], $tokenData['resourceIdentifier'][0], $tokenData['resourceIdentifier'][1], $tokenData['resourceIdentifier'][2], $tokenData['resourceIdentifier'][3], $tokenData['resourceIdentifier']));
     if (!is_file($resourcePathAndFilename)) {
         throw new FileNotFoundException(sprintf('File not found!%sThe file "%s" does not exist', chr(10), $resourcePathAndFilename), 1429702284);
     }
     if (!isset($this->options['serveStrategy'])) {
         throw new FlowException('No "serveStrategy" configured!', 1429704107);
     }
     $fileServeStrategy = $this->objectManager->get($this->options['serveStrategy']);
     if (!$fileServeStrategy instanceof FileServeStrategyInterface) {
         throw new FlowException(sprintf('The class "%s" does not implement the FileServeStrategyInterface', get_class($fileServeStrategy)), 1429704284);
     }
     $httpResponse = $componentContext->getHttpResponse();
     $httpResponse->setHeader('Content-Type', $resource->getMediaType());
     $this->emitResourceServed($resource, $httpRequest);
     $fileServeStrategy->serve($resourcePathAndFilename, $httpResponse);
     $componentContext->setParameter('TYPO3\\Flow\\Http\\Component\\ComponentChain', 'cancel', TRUE);
 }
 /**
  * @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');
 }
 /**
  * Initialize the property mapping configuration in $controllerArguments if
  * the trusted properties are set inside the request.
  *
  * @param \TYPO3\Flow\Mvc\ActionRequest $request
  * @param \TYPO3\Flow\Mvc\Controller\Arguments $controllerArguments
  * @return void
  */
 public function initializePropertyMappingConfigurationFromRequest(\TYPO3\Flow\Mvc\ActionRequest $request, \TYPO3\Flow\Mvc\Controller\Arguments $controllerArguments)
 {
     $trustedPropertiesToken = $request->getInternalArgument('__trustedProperties');
     if (!is_string($trustedPropertiesToken)) {
         return;
     }
     $serializedTrustedProperties = $this->hashService->validateAndStripHmac($trustedPropertiesToken);
     $trustedProperties = unserialize($serializedTrustedProperties);
     foreach ($trustedProperties as $propertyName => $propertyConfiguration) {
         if (!$controllerArguments->hasArgument($propertyName)) {
             continue;
         }
         $propertyMappingConfiguration = $controllerArguments->getArgument($propertyName)->getPropertyMappingConfiguration();
         $this->modifyPropertyMappingConfiguration($propertyConfiguration, $propertyMappingConfiguration);
     }
 }
 /**
  * Set a new password for the given user
  *
  * @param string $username user to modify
  * @param string $password new password
  * @param string $authenticationProvider Name of the authentication provider to use for finding the user. Default: "Sandstorm.UserManagement:Login".
  * @return void
  */
 public function setPasswordCommand($username, $password, $authenticationProvider = 'Sandstorm.UserManagement:Login')
 {
     // If we're in Neos context, we simply forward the command to the Neos command controller.
     if ($this->shouldUseNeosService()) {
         $cliRequest = new Request($this->request);
         $cliRequest->setControllerObjectName(UserCommandController::class);
         $cliRequest->setControllerCommandName('setPassword');
         $cliRequest->setArguments(['username' => $username, 'password' => $password, 'authenticationProvider' => $authenticationProvider]);
         $cliResponse = new Response($this->response);
         $this->dispatcher->dispatch($cliRequest, $cliResponse);
         $this->quit(0);
     }
     // Otherwise, we use our own logic.
     $account = $this->accountRepository->findByAccountIdentifierAndAuthenticationProviderName($username, $authenticationProvider);
     if ($account === null) {
         $this->outputLine('The user <b>' . $username . '</b> could not be found with auth provider <b>' . $authenticationProvider . '</b>.');
         $this->quit(1);
     }
     $encrypted = $this->hashService->hashPassword($password);
     $account->setCredentialsSource($encrypted);
     $this->accountRepository->update($account);
     $this->outputLine('Password for user <b>' . $username . '</b> changed.');
 }
Beispiel #24
0
 /**
  * @param string $password,
  * @param string $passwordconfirm
  * @param string $code
  * @return string|void
  */
 public function changePasswordAction($password = NULL, $passwordconfirm = NULL, $code = NULL)
 {
     if ($code !== NULL) {
         $cryptJson = $code;
         $cryptKey = md5($this->providerName);
         $uncryptJson = base64_decode($cryptJson);
         $uncryptJson = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $cryptKey, $uncryptJson, MCRYPT_MODE_CBC, md5($cryptKey));
         $uncryptJson = rtrim($uncryptJson, "");
         $json = json_decode($uncryptJson);
     } else {
         $json = NULL;
     }
     $this->view->assign('code', $code);
     // @TODO Check if User has random number
     if ($json != NULL) {
         if ($this->time->getTimestamp() - $json->date > 86400) {
             $this->flashMessageContainer->addMessage(new \TYPO3\Flow\Error\Error($this->translator->translateById('login.messages.registration.not_valid', array(), NULL, NULL, 'Main', 'Incvisio.LostFound')));
             $this->redirect('index', 'Standard', NULL, array());
         } else {
             $account = $this->accountRepository->findByAccountIdentifierAndAuthenticationProviderName($json->username, $this->providerName);
             if ($password == $passwordconfirm && $password !== NULL) {
                 $account->setExpirationDate(NULL);
                 $account->setCredentialsSource($this->hashService->hashPassword($password, 'default'));
                 $this->accountRepository->update($account);
                 $this->flashMessageContainer->addMessage(new Message($this->translator->translateById('login.login.update', array(), NULL, NULL, 'Main', 'Incvisio.LostFound')));
                 $this->redirect('index', 'Standard', NULL, array());
             } else {
                 if ($password !== NULL) {
                     $this->flashMessageContainer->addMessage(new \TYPO3\Flow\Error\Error("Sorry"));
                 }
             }
         }
     } else {
         $this->flashMessageContainer->addMessage(new \TYPO3\Flow\Error\Error($this->translator->translateById('login.messages.registration.not_valid', array(), NULL, NULL, 'Main', 'Incvisio.LostFound')));
         $this->redirect('index', 'Standard', NULL, array());
     }
 }
Beispiel #25
0
 /**
  * Sends an email to a user with the new password
  *
  * @param \TYPO3\Flow\Security\Account $account
  * @param array $settings
  * @param string $newEnteredPassword
  * @return boolean $success
  */
 public function sendMail(Account $account, $settings, $newEnteredPassword = NULL)
 {
     if ($newEnteredPassword !== NULL) {
         $newPassword = $newEnteredPassword;
     } else {
         $newPassword = $this->algorithms->generateRandomString(10);
         $account->setCredentialsSource($this->hashService->hashPassword($newPassword, 'default'));
         $this->accountRepository->update($account);
     }
     // @TODO: Localize the email format
     $mailBody[] = 'Dear %1$s';
     $mailBody[] = '';
     $mailBody[] = 'Your password for First Visit.';
     $mailBody[] = 'The password is %2$s';
     $mailBody[] = '';
     $mailBody[] = 'If you haven\'t requested this information, please change your password at once';
     $mailBody[] = 'as others might be able to access your account';
     $success = FALSE;
     $message = new SwiftMessage();
     if ($message->setTo(array($account->getAccountIdentifier() => $account->getParty()->getName()))->setFrom(array($settings['PasswordRecovery']['Sender']['Email'] => $settings['PasswordRecovery']['Sender']['Name']))->setSubject($settings['PasswordRecovery']['Subject'])->setBody(vsprintf(implode(PHP_EOL, $mailBody), array($account->getParty()->getName(), $newPassword)))->send()) {
         $success = TRUE;
     }
     return $success;
 }
 /**
  * Get the URI for an AJAX Request.
  *
  * @return string the AJAX URI
  * @throws WidgetContextNotFoundException
  */
 protected function getAjaxUri()
 {
     $action = $this->arguments['action'];
     $arguments = $this->arguments['arguments'];
     if ($action === NULL) {
         $action = $this->controllerContext->getRequest()->getControllerActionName();
     }
     $arguments['@action'] = $action;
     if (strlen($this->arguments['format']) > 0) {
         $arguments['@format'] = $this->arguments['format'];
     }
     /** @var $widgetContext WidgetContext */
     $widgetContext = $this->controllerContext->getRequest()->getInternalArgument('__widgetContext');
     if ($widgetContext === NULL) {
         throw new WidgetContextNotFoundException('Widget context not found in <f:widget.uri>', 1307450639);
     }
     if ($this->arguments['includeWidgetContext'] === TRUE) {
         $serializedWidgetContext = base64_encode(serialize($widgetContext));
         $arguments['__widgetContext'] = $this->hashService->appendHmac($serializedWidgetContext);
     } else {
         $arguments['__widgetId'] = $widgetContext->getAjaxWidgetIdentifier();
     }
     return '?' . http_build_query($arguments, NULL, '&');
 }
 /**
  * Set a new password for the given account
  *
  * This allows for setting a new password for an existing user account.
  *
  * @param Account $account
  * @param $password
  * @param string $passwordHashingStrategy
  *
  * @return boolean
  */
 public function resetPassword(Account $account, $password, $passwordHashingStrategy = 'default')
 {
     $account->setCredentialsSource($this->hashService->hashPassword($password, $passwordHashingStrategy));
     $this->accountRepository->update($account);
     return TRUE;
 }
 /**
  * Sets a new password for the given user
  *
  * This method will iterate over all accounts owned by the given user and, if the account uses a UsernamePasswordToken,
  * sets a new password accordingly.
  *
  * @param User $user The user to set the password for
  * @param string $password A new password
  * @return void
  * @api
  */
 public function setUserPassword(User $user, $password)
 {
     $tokens = $this->authenticationManager->getTokens();
     $indexedTokens = array();
     foreach ($tokens as $token) {
         /** @var TokenInterface $token */
         $indexedTokens[$token->getAuthenticationProviderName()] = $token;
     }
     foreach ($user->getAccounts() as $account) {
         /** @var Account $account */
         $authenticationProviderName = $account->getAuthenticationProviderName();
         if (isset($indexedTokens[$authenticationProviderName]) && $indexedTokens[$authenticationProviderName] instanceof UsernamePassword) {
             $account->setCredentialsSource($this->hashService->hashPassword($password));
             $this->accountRepository->update($account);
         }
     }
 }
Beispiel #29
0
 /**
  * @param string $phrase
  * @return string
  */
 protected function hashPhrase($phrase)
 {
     $phraseBuilder = new \Gregwar\Captcha\PhraseBuilder();
     return $this->hashService->generateHmac($this->salt . "::" . $phraseBuilder->niceize($phrase));
 }
Beispiel #30
0
 /**
  * @param string $newPassword
  * @param \TYPO3\Flow\Security\Cryptography\HashService $hashService
  * @throws \InvalidArgumentException
  */
 public function changePassword($newPassword, $hashService)
 {
     $newPassword = trim($newPassword);
     if (empty($newPassword)) {
         throw new \InvalidArgumentException('Password must be set.');
     }
     $this->edits++;
     $this->login->setCredentialsSource($hashService->hashPassword($newPassword, 'default'));
 }