/**
  * @test
  */
 public function testUserTracing()
 {
     $account = new Account();
     $account->setAccountIdentifier('testUserTracing');
     $account->setAuthenticationProviderName('TestingProvider');
     $this->persistenceManager->add($account);
     $this->persistenceManager->persistAll();
     $this->authenticateAccount($account);
     $entity = new Entity();
     $this->entityRepository->add($entity);
     $this->persistenceManager->persistAll();
     $this->assertEquals($entity->getCreatedBy(), $account);
     $this->assertNull($entity->getUpdatedBy());
     $entity->setType('testUserTracing');
     $this->entityRepository->update($entity);
     $this->persistenceManager->persistAll();
     $this->assertEquals($entity->getUpdatedBy(), $account);
     $account2 = new Account();
     $account2->setAccountIdentifier('testUserTracing2');
     $account2->setAuthenticationProviderName('TestingProvider');
     $this->persistenceManager->add($account2);
     $this->persistenceManager->persistAll();
     $this->authenticateAccount($account2);
     $entity->setType('testUserTracing2');
     $this->entityRepository->update($entity);
     $this->persistenceManager->persistAll();
     $this->assertEquals($entity->getUpdatedBy(), $account2);
     $this->assertNotEquals($entity->getCreatedBy(), $account2);
 }
Example #2
0
 /**
  * Get the account name of an user.
  *
  * @return string
  */
 public function getAccountName()
 {
     if ($this->account == null) {
         return $this->email;
     } else {
         return $this->account->getAccountIdentifier();
     }
 }
 /**
  * @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);
 }
 /**
  * @test
  */
 public function authenticateTagsSessionWithAccountIdentifier()
 {
     $account = new Account();
     $account->setAccountIdentifier('admin');
     $securityContext = $this->getMockBuilder(\TYPO3\Flow\Security\Context::class)->setMethods(array('getAuthenticationStrategy', 'getAuthenticationTokens', 'refreshTokens', 'refreshRoles'))->getMock();
     $token = $this->createMock(\TYPO3\Flow\Security\Authentication\TokenInterface::class);
     $token->expects($this->any())->method('getAccount')->will($this->returnValue($account));
     $token->expects($this->atLeastOnce())->method('isAuthenticated')->will($this->returnValue(true));
     $securityContext->expects($this->atLeastOnce())->method('getAuthenticationTokens')->will($this->returnValue(array($token)));
     $this->mockSession->expects($this->once())->method('addTag')->with('TYPO3-Flow-Security-Account-21232f297a57a5a743894a0e4a801fc3');
     $this->authenticationProviderManager->_set('providers', array());
     $this->authenticationProviderManager->_set('securityContext', $securityContext);
     $this->authenticationProviderManager->authenticate();
 }
 /**
  * @param \TYPO3\Flow\Security\Account $account
  * @return string
  */
 public function generateDisqusRemoteAuth(\TYPO3\Flow\Security\Account $account)
 {
     /** @var \TYPO3\Party\Domain\Model\Person $person */
     $person = $account->getParty();
     $data = array('id' => $account->getAccountIdentifier(), 'username' => $person->getName()->getFullName(), 'email' => $person->getPrimaryElectronicAddress()->getIdentifier(), 'avatar' => sprintf('//typo3.org/services/userimage.php?username=%s&size=big', $account->getAccountIdentifier()));
     if (!isset($this->settings['disqusApiSecret'])) {
         throw new \InvalidArgumentException('You need to set up a disqusApiSecrect in your settings.', 1425572965);
     }
     $message = base64_encode(json_encode($data));
     $timestamp = time();
     $apiSecret = $this->settings['disqusApiSecret'];
     $hmac = $this->disqusHmacSha1($message . ' ' . $timestamp, $apiSecret);
     return $message . ' ' . $hmac . ' ' . $timestamp;
 }
Example #6
0
 /**
  * @param Account $account
  * @return void
  */
 protected function sendNotificationMail(Account $account)
 {
     $notificationMailSettings = $this->settings['notificationMail'];
     if (!$notificationMailSettings['to']) {
         return;
     }
     $httpRequest = Request::createFromEnvironment();
     $failedAttemptsThreshold = $this->settings['failedAttemptsThreshold'];
     $time = (new \DateTime())->format('Y-m-d H:i');
     $replacePlaceholders = function ($string) use($account, $httpRequest, $failedAttemptsThreshold, $time) {
         return str_replace(['{domain}', '{ip}', '{userAgent}', '{accountIdentifier}', '{failedAttemptsThreshold}', '{time}'], [$httpRequest->getUri()->getHost(), $httpRequest->getClientIpAddress(), $_SERVER['HTTP_USER_AGENT'], $account->getAccountIdentifier(), $failedAttemptsThreshold, $time], $string);
     };
     $mail = new Message();
     $mail->setFrom($replacePlaceholders($notificationMailSettings['from']['email']), $replacePlaceholders($notificationMailSettings['from']['name']))->setTo($notificationMailSettings['to'])->setSubject($replacePlaceholders($notificationMailSettings['subject']))->setBody($replacePlaceholders($notificationMailSettings['message']))->send();
 }
 /**
  * Checks if the given account is already in the account repository
  *
  * @param \TYPO3\Flow\Security\Account $account
  * @return bool
  */
 public function doesAccountExist(\TYPO3\Flow\Security\Account $account)
 {
     $accountIdentifier = $account->getAccountIdentifier();
     $authenticationProviderName = $account->getAuthenticationProviderName();
     $existingAccount = $this->accountRepository->findByAccountIdentifierAndAuthenticationProviderName($accountIdentifier, $authenticationProviderName);
     return $existingAccount !== NULL;
 }
 /**
  * Tries to authenticate the given token. Sets isAuthenticated to TRUE if authentication succeeded.
  *
  * @param TokenInterface $authenticationToken The token to be authenticated
  * @throws \TYPO3\Flow\Security\Exception\UnsupportedAuthenticationTokenException
  * @return void
  */
 public function authenticate(TokenInterface $authenticationToken)
 {
     if (!$authenticationToken instanceof AbstractClientToken) {
         throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1383754993);
     }
     $credentials = $authenticationToken->getCredentials();
     // Inspect the received access token as documented in https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
     $tokenInformation = $this->facebookTokenEndpoint->requestValidatedTokenInformation($credentials['accessToken']);
     if ($tokenInformation === FALSE) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
         return;
     }
     // Check if the permitted scopes suffice:
     $necessaryScopes = $this->options['scopes'];
     $scopesHavingPermissionFor = $tokenInformation['scopes'];
     $requiredButNotPermittedScopes = array_diff($necessaryScopes, $scopesHavingPermissionFor);
     if (count($requiredButNotPermittedScopes) > 0) {
         $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
         $this->securityLogger->log('The permitted scopes do not satisfy the required once.', LOG_NOTICE, array('necessaryScopes' => $necessaryScopes, 'allowedScopes' => $scopesHavingPermissionFor));
         return;
     }
     // From here, we surely know the user is considered authenticated against the remote service,
     // yet to check if there is an immanent account present.
     $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
     /** @var $account \TYPO3\Flow\Security\Account */
     $account = NULL;
     $providerName = $this->name;
     $accountRepository = $this->accountRepository;
     $this->securityContext->withoutAuthorizationChecks(function () use($tokenInformation, $providerName, $accountRepository, &$account) {
         $account = $accountRepository->findByAccountIdentifierAndAuthenticationProviderName($tokenInformation['user_id'], $providerName);
     });
     if ($account === NULL) {
         $account = new Account();
         $account->setAccountIdentifier($tokenInformation['user_id']);
         $account->setAuthenticationProviderName($providerName);
         $this->accountRepository->add($account);
     }
     $authenticationToken->setAccount($account);
     // request long-live token and attach that to the account
     $longLivedToken = $this->facebookTokenEndpoint->requestLongLivedToken($credentials['accessToken']);
     $account->setCredentialsSource($longLivedToken);
     $this->accountRepository->update($account);
 }
 /**
  * In this method, actually create the user / account.
  *
  * NOTE: After this method is called, the $registrationFlow is DESTROYED, so you need to store all attributes
  * in your object as you need them.
  *
  * @param RegistrationFlow $registrationFlow
  * @return void
  */
 public function createUserAndAccount(RegistrationFlow $registrationFlow)
 {
     // Create the account
     $account = new Account();
     $account->setAccountIdentifier($registrationFlow->getEmail());
     $account->setCredentialsSource($registrationFlow->getEncryptedPassword());
     $account->setAuthenticationProviderName('Sandstorm.UserManagement:Login');
     // Assign pre-configured roles
     foreach ($this->rolesForNewUsers as $roleString) {
         $account->addRole(new Role($roleString));
     }
     // Create the user
     $user = new User();
     $user->setAccount($account);
     $user->setEmail($registrationFlow->getEmail());
     if (array_key_exists('salutation', $registrationFlow->getAttributes())) {
         $user->setGender($registrationFlow->getAttributes()['salutation']);
     }
     if (array_key_exists('firstName', $registrationFlow->getAttributes())) {
         $user->setFirstName($registrationFlow->getAttributes()['firstName']);
     }
     if (array_key_exists('lastName', $registrationFlow->getAttributes())) {
         $user->setLastName($registrationFlow->getAttributes()['lastName']);
     }
     // Persist user
     $this->userRepository->add($user);
     $this->persistenceManager->whitelistObject($user);
     $this->persistenceManager->whitelistObject($account);
 }
Example #10
0
 /**
  * @return \Ag\Login\Domain\Model\AccountDescriptor
  */
 public function getDescriptor()
 {
     $d = new AccountDescriptor();
     $d->accountId = $this->accountId;
     $d->email = $this->login->getAccountIdentifier();
     $d->name = $this->name;
     $d->imageId = $this->imageId;
     $d->roles = $this->login->getRoles();
     foreach ($d->roles as $key => $role) {
         $d->roles[$key] = $this->flowRoleToRole($role);
     }
     return $d;
 }
 /**
  * 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 Account A new account, not yet added to the account repository
  */
 public function createAccountWithPassword($identifier, $password, $roleIdentifiers = [], $authenticationProviderName = 'DefaultProvider', $passwordHashingStrategy = 'default')
 {
     $account = new Account();
     $account->setAccountIdentifier($identifier);
     $account->setCredentialsSource($this->hashService->hashPassword($password, $passwordHashingStrategy));
     $account->setAuthenticationProviderName($authenticationProviderName);
     $roles = [];
     foreach ($roleIdentifiers as $roleIdentifier) {
         $roles[] = $this->policyService->getRole($roleIdentifier);
     }
     $account->setRoles($roles);
     return $account;
 }
 /**
  * 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);
     }
 }
 /**
  * In this method, actually create the user / account.
  *
  * NOTE: After this method is called, the $registrationFlow is DESTROYED, so you need to store all attributes
  * in your object as you need them.
  *
  * @param RegistrationFlow $registrationFlow
  * @return void
  */
 public function createUserAndAccount(RegistrationFlow $registrationFlow)
 {
     // Create the account
     $account = new Account();
     $account->setAccountIdentifier($registrationFlow->getEmail());
     $account->setCredentialsSource($registrationFlow->getEncryptedPassword());
     $account->setAuthenticationProviderName('Sandstorm.UserManagement:Login');
     // Assign preconfigured roles
     foreach ($this->rolesForNewUsers as $roleString) {
         $account->addRole(new Role($roleString));
     }
     // Create the user
     $user = new User();
     $name = new PersonName('', $registrationFlow->getAttributes()['firstName'], '', $registrationFlow->getAttributes()['lastName'], '', $registrationFlow->getEmail());
     $user->setName($name);
     // Assign them to each other and persist
     $this->getPartyService()->assignAccountToParty($account, $user);
     $this->getPartyRepository()->add($user);
     $this->accountRepository->add($account);
     $this->persistenceManager->whitelistObject($user);
     $this->persistenceManager->whitelistObject($user->getPreferences());
     $this->persistenceManager->whitelistObject($name);
     $this->persistenceManager->whitelistObject($account);
 }
 /**
  * @expectedException \TYPO3\Flow\Security\Exception
  * @expectedExceptionCode 1397745354
  * @test
  */
 public function callingSetPartyWithoutIdentifierThrowsException()
 {
     $account = new Account();
     $mockParty = $this->getMock('TYPO3\\Party\\Domain\\Model\\AbstractParty');
     $account->setParty($mockParty);
 }
 /**
  * @param array $userdata
  * @return Account
  */
 protected function createAccount(array $userdata)
 {
     if (!isset($userdata['username'])) {
         return;
     }
     $account = new Account();
     $account->setCredentialsSource('typo3.org SSO');
     $account->setAuthenticationProviderName($this->name);
     $account->setRoles(array($this->policyService->getRole('T3DD.Backend:Authenticated')));
     $account->setAccountIdentifier($userdata['username']);
     $person = new Person();
     $this->partyRepository->add($person);
     $this->partyService->assignAccountToParty($account, $person);
     $this->updatePerson($person, $userdata);
     $this->accountRepository->add($account);
     $this->persistenceManager->persistAll();
     return $account;
 }
Example #16
0
 /**
  * @test
  */
 public function shutdownCreatesSpecialDataEntryForSessionWithAuthenticatedAccounts()
 {
     $session = new Session();
     $this->inject($session, 'bootstrap', $this->mockBootstrap);
     $this->inject($session, 'objectManager', $this->mockObjectManager);
     $this->inject($session, 'settings', $this->settings);
     $this->inject($session, 'metaDataCache', $this->createCache('Meta'));
     $this->inject($session, 'storageCache', $this->createCache('Storage'));
     $session->initializeObject();
     $session->start();
     $account = new Account();
     $account->setAccountIdentifier('admin');
     $account->setAuthenticationProviderName('MyProvider');
     $token = new UsernamePassword();
     $token->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
     $token->setAccount($account);
     $this->mockSecurityContext->expects($this->any())->method('isInitialized')->will($this->returnValue(TRUE));
     $this->mockSecurityContext->expects($this->any())->method('getAuthenticationTokens')->will($this->returnValue(array($token)));
     $session->close();
     $this->httpRequest->setCookie($this->httpResponse->getCookie('TYPO3_Flow_Session'));
     $session->resume();
     $this->assertEquals(array('MyProvider:admin'), $session->getData('TYPO3_Flow_Security_Accounts'));
 }
 /**
  * @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;
 }
Example #18
0
 /**
  * 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);
         }
     }
 }
 /**
  * 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;
 }
 /**
  * @expectedException \TYPO3\Flow\Security\Exception
  * @expectedExceptionCode 1397745354
  * @test
  */
 public function callingSetPartyWithoutIdentifierThrowsException()
 {
     $account = new Account();
     $account->setParty(new \stdClass());
 }
 /**
  * Tries to authenticate the given token. Sets isAuthenticated to TRUE if authentication succeeded.
  *
  * @param TokenInterface $authenticationToken The token to be authenticated
  * @throws \TYPO3\Flow\Security\Exception\UnsupportedAuthenticationTokenException
  * @return void
  */
 public function authenticate(TokenInterface $authenticationToken)
 {
     if (!$authenticationToken instanceof AbstractClientToken) {
         throw new UnsupportedAuthenticationTokenException('This provider cannot authenticate the given token.', 1383754993);
     }
     $credentials = $authenticationToken->getCredentials();
     // There is no way to validate the Token or check the scopes at the moment apart from "trying" (and possibly receiving an access denied)
     // we could check the validity of the Token and the scopes here in the future when Instagram provides that
     // Only check if an access Token is present at this time and do a single test call
     if (isset($credentials['accessToken']) && $credentials['accessToken'] !== NULL) {
         // check if a secure request is possible (https://www.instagram.com/developer/secure-api-requests/)
         $userInfo = $this->instagramTokenEndpoint->validateSecureRequestCapability($credentials['accessToken']);
         if ($userInfo === FALSE) {
             $authenticationToken->setAuthenticationStatus(TokenInterface::WRONG_CREDENTIALS);
             $this->securityLogger->log('A secure call to the API with the provided accessToken and clientSecret was not possible', LOG_NOTICE);
             return FALSE;
         }
     } else {
     }
     // From here, we surely know the user is considered authenticated against the remote service,
     // yet to check if there is an immanent account present.
     $authenticationToken->setAuthenticationStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
     /** @var $account \TYPO3\Flow\Security\Account */
     $account = NULL;
     $providerName = $this->name;
     $accountRepository = $this->accountRepository;
     $this->securityContext->withoutAuthorizationChecks(function () use($userInfo, $providerName, $accountRepository, &$account) {
         $account = $accountRepository->findByAccountIdentifierAndAuthenticationProviderName($userInfo['id'], $providerName);
     });
     if ($account === NULL) {
         $account = new Account();
         $account->setAccountIdentifier($userInfo['id']);
         $account->setAuthenticationProviderName($providerName);
         $this->accountRepository->add($account);
     }
     $authenticationToken->setAccount($account);
     // the access token is valid for an "undefined time" according to instagram (so we cannot know when the user needs to log in again)
     $account->setCredentialsSource($credentials['accessToken']);
     $this->accountRepository->update($account);
     // check if a user is already attached to this account
     if ($this->partyService->getAssignedPartyOfAccount($account) === null || count($this->partyService->getAssignedPartyOfAccount($account)) < 1) {
         $user = $this->userService->getCurrentUser();
         if ($user !== null) {
             $user->addAccount($account);
             $this->userService->updateUser($user);
             $this->persistenceManager->whitelistObject($user);
         } else {
             $this->securityLogger->logException(new Exception("The InstagramProvider was unable to determine the backend user, make sure the configuration Typo3BackendProvider requestPattern matches the Instagram Controller and the authentication strategy is set to 'atLeastOne' Token"));
         }
     }
     // persistAll is called automatically at the end of this function, account gets whitelisted to allow
     // persisting for an object thats tinkered with via a GET request
     $this->persistenceManager->whitelistObject($account);
 }
 /**
  * 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();
     }
 }
Example #23
0
 /**
  * @return string
  */
 public function getProfileImage()
 {
     return sprintf('//typo3.org/services/userimage.php?username=%s&size=big', $this->payload->getAccountIdentifier());
 }
 /**
  * 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);
     }
 }
 /**
  * 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));
 }
 /**
  * Creates a personal workspace for the given user's account if it does not exist already.
  *
  * @param User $user The new user to create a workspace for
  * @param Account $account The user's backend account
  * @throws IllegalObjectTypeException
  */
 protected function createPersonalWorkspace(User $user, Account $account)
 {
     $userWorkspaceName = UserUtility::getPersonalWorkspaceNameForUsername($account->getAccountIdentifier());
     $userWorkspace = $this->workspaceRepository->findByIdentifier($userWorkspaceName);
     if ($userWorkspace === null) {
         $liveWorkspace = $this->workspaceRepository->findByIdentifier('live');
         if (!$liveWorkspace instanceof Workspace) {
             $liveWorkspace = new Workspace('live');
             $liveWorkspace->setTitle('Live');
             $this->workspaceRepository->add($liveWorkspace);
         }
         $userWorkspace = new Workspace($userWorkspaceName, $liveWorkspace, $user);
         $userWorkspace->setTitle((string) $user->getName());
         $this->workspaceRepository->add($userWorkspace);
     }
 }
 /**
  * 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::class)->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;
 }
Example #28
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;
 }
 /**
  * Edit the given account
  *
  * @param Account $account
  * @return void
  */
 public function editAccountAction(Account $account)
 {
     $this->view->assignMultiple(array('account' => $account, 'user' => $this->userService->getUser($account->getAccountIdentifier(), $account->getAuthenticationProviderName())));
 }
 /**
  * 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;
 }