Ejemplo n.º 1
0
 /**
  * Return user-credentials; returned password is encoded via "security.encoder_factory".
  * 
  * @param \Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface $encoder_service
  *
  * @return array|bool
  */
 public function getCredentials(EncoderFactoryInterface $encoder_service = null)
 {
     if (($user = $this->request->getRawServerValue('PHP_AUTH_USER')) && ($pass = $this->request->getRawServerValue('PHP_AUTH_PW'))) {
         $credentials = array($user, $pass);
     } else {
         // Most other webservers
         $auth = $this->request->getHeader('Authorization');
         // Apache could prefix environment variables with REDIRECT_ when urls
         // are passed through mod_rewrite
         if (!$auth) {
             $auth = $this->request->getRawServerValue('REDIRECT_HTTP_AUTHORIZATION');
         }
         if (!$auth) {
             return false;
         }
         if (strpos(strtolower($auth), 'basic') !== 0) {
             return false;
         }
         $credentials = explode(':', base64_decode(substr($auth, 6)), 2);
     }
     $user = $this->getUser($credentials[0]);
     if (!$user) {
         return false;
     }
     if ($encoder_service === null) {
         // don't return password, because it isn't encoded
         return array($credentials[0], '');
     }
     $encoder = $encoder_service->getEncoder($user);
     $encoded_pass = $encoder->encodePassword($credentials[1], $user->getSalt());
     return array($credentials[0], $encoded_pass);
 }
Ejemplo n.º 2
0
 /**
  * @param string $username
  * @param string $password
  * @param null|string $requiredGroupRole
  * @return bool
  */
 public function login($username, $password, $requiredGroupRole = null)
 {
     if (empty($username) || empty($password)) {
         return false;
     }
     $user = $this->userProvider->loadUserByUsername($username);
     if (!$user) {
         $this->logger->warning(sprintf('Login failed for "%s". User not found', $username));
         sleep(1);
         return false;
     }
     if (null !== $requiredGroupRole) {
         $groupRoles = $user->getGroupRoles();
         if (!in_array($requiredGroupRole, $groupRoles)) {
             $this->logger->warning(sprintf('Login failed for "%s". Not in requested group role "%s" vs "%s"', $username, $requiredGroupRole, implode(',', $groupRoles)));
             sleep(1);
             return false;
         }
     }
     $encoder = $this->encoderFactory->getEncoder($user);
     if (!$encoder->isPasswordValid($user->getPassword(), $password, null)) {
         $this->logger->warning(sprintf('Login failed for "%s". Password missmatch ', $username));
         sleep(1);
         return false;
     }
     $this->manualLogin($user);
     return true;
 }
 /**
  * This authentification is role based
  * @see OAuth2\IOAuth2GrantExtension::checkGrantExtension
  */
 public function checkGrantExtension(IOAuth2Client $client, array $inputData, array $authHeaders)
 {
     if (!isset($inputData['email'])) {
         throw new OAuth2ServerException(OAuth2::HTTP_BAD_REQUEST, OAuth2::ERROR_INVALID_REQUEST, 'No "email" parameter found');
     }
     if (!isset($inputData['password'])) {
         throw new OAuth2ServerException(OAuth2::HTTP_BAD_REQUEST, OAuth2::ERROR_INVALID_REQUEST, 'No "password" parameter found');
     }
     $email = $inputData['email'];
     $password = $inputData['password'];
     $user = $this->userProvider->loadByEmail($email);
     if (null === $user) {
         throw new OAuth2ServerException(OAuth2::HTTP_BAD_REQUEST, self::ERROR_UNKNOWN_USER, 'User not found.');
     }
     $encoder = $this->encoderFactory->getEncoder($user);
     if ($encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
         if (method_exists($user, 'isLocked')) {
             if ($user->isLocked()) {
                 throw new OAuth2ServerException(OAuth2::HTTP_BAD_REQUEST, self::ERROR_LOCKED, "User is locked.");
             }
         }
         return array('data' => $user);
     }
     throw new OAuth2ServerException(OAuth2::HTTP_BAD_REQUEST, self::ERROR_INVALID_PASSWORD, 'Password is not valid.');
 }
Ejemplo n.º 4
0
 function it_encodes_password(EncoderFactoryInterface $encoderFactory, PasswordEncoderInterface $passwordEncoder, UserInterface $user)
 {
     $user->getPlainPassword()->willReturn('topSecretPlainPassword');
     $user->getSalt()->willReturn('typicalSalt');
     $encoderFactory->getEncoder($user)->willReturn($passwordEncoder);
     $passwordEncoder->encodePassword('topSecretPlainPassword', 'typicalSalt')->willReturn('topSecretEncodedPassword');
     $this->encode($user)->shouldReturn('topSecretEncodedPassword');
 }
Ejemplo n.º 5
0
 /**
  * {@inheritDoc}
  */
 public function updatePassword(UserInterface $user)
 {
     if (0 !== strlen($password = $user->getPlainPassword())) {
         $encoder = $this->encoderFactory->getEncoder($user);
         $user->setPassword($encoder->encodePassword($password, $user->getSalt()));
         $user->eraseCredentials();
     }
 }
Ejemplo n.º 6
0
 private function updatePasswordHash(HasPassword $object)
 {
     $password = $this->generatePassword($this->encoderFactory->getEncoder($object), $object);
     $object->setPassword($password);
     if ($object instanceof UserInterface) {
         $object->eraseCredentials();
     }
 }
Ejemplo n.º 7
0
 function it_encodes_password(EncoderFactoryInterface $encoderFactory, PasswordEncoderInterface $passwordEncoder, CredentialsHolderInterface $user)
 {
     $user->getPlainPassword()->willReturn('topSecretPlainPassword');
     $user->getSalt()->willReturn('typicalSalt');
     $encoderFactory->getEncoder(get_class($user->getWrappedObject()))->willReturn($passwordEncoder);
     $passwordEncoder->encodePassword('topSecretPlainPassword', 'typicalSalt')->willReturn('topSecretEncodedPassword');
     $this->encode($user)->shouldReturn('topSecretEncodedPassword');
 }
Ejemplo n.º 8
0
 /**
  * @{inheritdoc}
  */
 public function reverseTransform($value)
 {
     // Only encode if $value holds something, empty means we shouldnt encode
     // anything at all.
     if (empty($value)) {
         return $value;
     }
     return $this->factory->getEncoder($this->user)->encodePassword($value, $this->user->getSalt());
 }
Ejemplo n.º 9
0
 public function registerUser(RegisterUserCommand $command)
 {
     $salt = random_bytes(22);
     $password = $this->encoderFactory->getEncoder(User::class)->encodePassword($command->getPassword(), $salt);
     $user = new User(new UuidIdentity(Uuid::uuid4()), $command->getUsername(), $password, $salt, User::ROLE_USER, new Address());
     $this->repository->save($user);
     $event = new UserRegisteredEvent($user);
     $this->eventBus->handle($event);
 }
Ejemplo n.º 10
0
 public function getValue()
 {
     if (!parent::getValue()) {
         return null;
     }
     $userClass = $this->getFieldDefinition()->getOption('userClass') ?: User::class;
     $encoder = $this->encoderFactory->getEncoder($userClass);
     return $encoder->encodePassword(parent::getValue(), null);
 }
Ejemplo n.º 11
0
 /**
  * Updates a user password if a plain password is set.
  *
  * @param UserInterface $user A UserInterface instance
  */
 protected function setPassword(UserInterface $user)
 {
     if (0 === strlen($password = $user->getPlainPassword())) {
         return;
     }
     $encoder = $this->encoderFactory->getEncoder($user);
     $user->setPassword($encoder->encodePassword($password, $user->getSalt()));
     $user->eraseCredentials();
 }
Ejemplo n.º 12
0
 /**
  * Update the password of the user
  *
  * @param User $user 
  * @return User
  */
 public function updatePassword(User $user)
 {
     $plaintext_password = $user->getPlaintextPassword();
     if (!is_null($plaintext_password)) {
         $encoder = $this->encoderFactory->getEncoder($user);
         $user->setPassword($encoder->encodePassword($plaintext_password, $user->getSalt()));
         $user->eraseCredentials();
     }
     return $user;
 }
Ejemplo n.º 13
0
 /**
  * @Given I am a user
  */
 public function iAmAUser()
 {
     $password = '******';
     $salt = str_repeat('1', 22);
     $encodedPassword = $this->encoderFactory->getEncoder(AccountUser::class)->encodePassword($password, $salt);
     $this->accountRepository->add(Account::create(new AccountId((string) \Rhumsaa\Uuid\Uuid::uuid4()), new Credentials(new EmailAddress('*****@*****.**'), $encodedPassword, $salt)));
     $this->client->request('POST', '/login/', ['username' => '*****@*****.**', 'password' => $password]);
     $response = $this->client->getResponse();
     PHPUnit_Framework_Assert::assertEquals(Response::HTTP_OK, $response->getStatusCode());
     PHPUnit_Framework_Assert::assertNotNull($this->session->get('oauth_data'));
 }
Ejemplo n.º 14
0
 /**
  * Encode a password with a generated salt.
  *
  * @param string $password
  * @param UserInterface $user instance of user, default to user class.
  * @param string $passwordSalt generate one if not defined.
  *
  * @return array with hash and salt.
  */
 public function encodePassword($password, UserInterface $user = null, $passwordSalt = null)
 {
     if (null === $user) {
         $user = new $this->userClass();
     }
     if (null === $passwordSalt) {
         $passwordSalt = $this->generateSalt();
     }
     $encoder = $this->encoderFactory->getEncoder($user);
     $passwordHash = $encoder->encodePassword($password, $passwordSalt);
     return array('hash' => $passwordHash, 'salt' => $passwordSalt, 'user' => get_class($user));
 }
Ejemplo n.º 15
0
 function let(EncoderFactoryInterface $factory, PasswordEncoderInterface $encoder, HasPassword $user, LifecycleEventArgs $event)
 {
     $user->implement('Symfony\\Component\\Security\\Core\\User\\UserInterface');
     $user->getPlainPassword()->willReturn('password');
     $user->getSalt()->willReturn('salt');
     $user->setPassword(Argument::any())->willReturn(null);
     $user->eraseCredentials()->willReturn(null);
     $event->getObject()->willReturn($user);
     $factory->getEncoder($user)->willReturn($encoder);
     $encoder->encodePassword('password', 'salt')->willReturn('encoded');
     $this->beConstructedWith($factory);
 }
Ejemplo n.º 16
0
 /**
  * @param string $userName
  * @param string $email
  * @param string $password
  * @param array $roles
  * @param array $extraFields
  * @return \Leapt\AdminBundle\Entity\User
  */
 public function createUser($userName, $email, $password, array $roles, array $extraFields = array())
 {
     $user = new $this->userClass();
     $encoder = $this->encoderFactory->getEncoder($user);
     $encodedPassword = $encoder->encodePassword($password, $user->getSalt());
     $user->setUsername($userName)->setEmail($email)->setPassword($encodedPassword)->setRoles($roles);
     foreach ($extraFields as $extraFieldName => $extraFieldValue) {
         $propertyAccessor = PropertyAccess::createPropertyAccessor();
         $propertyAccessor->setValue($user, $extraFieldName, $extraFieldValue);
     }
     $this->em->persist($user);
     $this->em->flush($user);
 }
Ejemplo n.º 17
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $array = array(array('superadmin', 'australie', 'ROLE_SUPER_ADMIN'), array('admin', 'australie', 'ROLE_ADMIN'), array('user', 'australie', 'ROLE_USER'));
     foreach ($array as $row) {
         $user = new User();
         $user->setUsername($row[0]);
         $encoder = $this->factory->getEncoder($user);
         $user->setPassword($encoder->encodePassword($row[1], $user->getSalt()));
         $user->setRoles($row[2]);
         $manager->persist($user);
         $this->addReference($row[0], $user);
     }
     $manager->flush();
 }
 /**
  * @param \FSi\Bundle\AdminSecurityBundle\Event\ChangePasswordEvent $event
  * @param \Doctrine\Bundle\DoctrineBundle\Registry $registry
  * @param \FSi\Bundle\AdminSecurityBundle\spec\fixtures\User $user
  * @param \Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface $encodeFactory
  * @param \Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface $encoder
  */
 function it_set_password_when_user_is_doctrine_entity($event, $registry, $user, $encodeFactory, $encoder)
 {
     $prophet = new Prophet();
     $em = $prophet->prophesize('Doctrine\\ORM\\EntityManager');
     $registry->getManagerForClass(Argument::type('string'))->willReturn($em);
     $event->getUser()->shouldBeCalled()->willReturn($user);
     $event->getPlainPassword()->shouldBeCalled()->willReturn('plain_password');
     $user->getSalt()->shouldBeCalled()->willReturn('salt');
     $encodeFactory->getEncoder($user)->shouldBeCalled()->willReturn($encoder);
     $encoder->encodePassword('plain_password', 'salt')->shouldBeCalled()->willReturn('encoded_password');
     $user->setPassword('encoded_password')->shouldBeCalled();
     $em->persist($user->getWrappedObject())->shouldBeCalled();
     $em->flush()->shouldBeCalled();
     $this->onChangePassword($event);
 }
Ejemplo n.º 19
0
 function it_should_encode_password_when_attribute_changed(EncoderFactoryInterface $encoderFactory, User $user, PasswordEncoderInterface $encoder, LifecycleEventArgs $args, UnitOfWork $unitOfWork, EntityManager $entityManager, \Doctrine\ORM\Mapping\ClassMetadata $meta)
 {
     $args->getEntityManager()->willReturn($entityManager);
     $entityManager->getUnitOfWork()->willReturn($unitOfWork);
     $entityManager->getClassMetadata(Argument::any())->willReturn($meta);
     $unitOfWork->computeChangeSet(Argument::cetera())->willReturn();
     $user->getPassword()->willReturn('pass');
     $user->getSalt()->willReturn('salt');
     $args->getEntity()->willReturn($user);
     $encoderFactory->getEncoder($user)->willReturn($encoder);
     $encoder->encodePassword(Argument::any(), Argument::any())->willReturn('encoded_pass');
     $unitOfWork->getEntityChangeSet($user)->willReturn(['password' => 'password']);
     $user->setPassword('encoded_pass')->shouldBeCalled();
     $this->postPersist($args);
 }
 public function checkUserCredentials(IOAuth2Client $client, $username, $password)
 {
     if (!$client instanceof ClientInterface) {
         throw new \InvalidArgumentException('Client has to implement the ClientInterface');
     }
     try {
         $user = $this->userProvider->loadUserByUsername($username);
     } catch (AuthenticationException $e) {
         return false;
     }
     if (null !== $user) {
         $data = array('data' => $user);
         if ($this->tokenPathAuth === 'plain') {
             $encoder = $this->encoderFactory->getEncoder($user);
             if ($encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
                 return $data;
             }
         } elseif ($this->tokenPathAuth === 'hash') {
             if ($user->getPassword() === $password) {
                 return $data;
             }
         } else {
             throw new \InvalidArgumentException('Token Path Auth is not valid');
         }
     }
     return false;
 }
 function it_should_change_user_password(CredentialsRepository $credentialsRepository, EncoderFactoryInterface $encoderFactory, EventDispatcherInterface $eventDispatcher, PasswordEncoderInterface $passwordEncoder, User $user, Credentials $oldCredentials, Credentials $newCredentials, ChangePasswordAction $action)
 {
     // Mocks
     $action->getUser()->willReturn($user);
     $action->getOldPassword()->willReturn('old_p4ssw0rd');
     $action->getNewPassword()->willReturn('new_p4ssw0rd');
     $encoderFactory->getEncoder($user)->willReturn($passwordEncoder);
     $passwordEncoder->encodePassword('new_p4ssw0rd', Argument::type('string'))->shouldBeCalled()->willReturn('encoded_password==');
     // Old credentials should be remove
     $credentialsRepository->findOneByUser($user)->willReturn($oldCredentials);
     $credentialsRepository->remove($oldCredentials)->shouldBeCalled();
     // New encoded password should be saved
     $credentialsRepository->createNew($user, 'encoded_password==', Argument::type('string'))->shouldBeCalled()->willReturn($newCredentials);
     $credentialsRepository->save($newCredentials)->shouldBeCalled();
     $this->execute($action);
 }
Ejemplo n.º 22
0
 public function testUpdateUser()
 {
     $password = '******';
     $encodedPassword = '******';
     $user = $this->getUser(true);
     $user->setUsername(self::TEST_NAME);
     $user->setEmail(self::TEST_EMAIL);
     $user->setPlainPassword($password);
     $encoder = $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface');
     $encoder->expects($this->once())->method('encodePassword')->with($user->getPlainPassword(), $user->getSalt())->will($this->returnValue($encodedPassword));
     $this->ef->expects($this->once())->method('getEncoder')->with($user)->will($this->returnValue($encoder));
     $this->om->expects($this->once())->method('persist')->with($this->equalTo($user));
     $this->om->expects($this->once())->method('flush');
     $this->userManager->updateUser($user);
     $this->assertEquals(self::TEST_EMAIL, $user->getEmail());
     $this->assertEquals($encodedPassword, $user->getPassword());
 }
Ejemplo n.º 23
0
 /**
  * Encode the password if it change
  *
  * @param LifecycleEventArgs $args
  */
 public function postPersist(LifecycleEventArgs $args)
 {
     $entity = $args->getEntity();
     // We will only work on User entities
     if ($entity instanceof User) {
         $em = $args->getEntityManager();
         $unitOfWork = $em->getUnitOfWork();
         $changeSet = $unitOfWork->getEntityChangeSet($entity);
         // If the password was changed we have to encode it
         if (array_key_exists('password', $changeSet)) {
             $password = $this->encoderFactory->getEncoder($entity)->encodePassword($entity->getPassword(), $entity->getSalt());
             $entity->setPassword($password);
             // Register the password modification
             $unitOfWork->computeChangeSet($em->getClassMetadata(get_class($entity)), $entity);
         }
     }
 }
Ejemplo n.º 24
0
 public function execute()
 {
     $passwordBuilder = new PasswordBuilder();
     $passwordBuilder->specifyPassword($this->password);
     $passwordBuilder->processChangedPassword($this->encoderFactory->getEncoder($this->user));
     $changeRequest = CredentialChangeRequest::forPassword($this->user, $passwordBuilder->getEncodedPassword(), $passwordBuilder->getSalt(), $_SERVER['REMOTE_ADDR'], time());
     $this->repository->insertCredentialChangeRequest($changeRequest);
     $this->dispatcher->dispatch(CantigaEvents::USER_CREDENTIAL_CHANGE, new CredentialChangeEvent($changeRequest));
 }
 function it_execute_action(UserRepository $userRepository, CredentialsRepository $credentialsRepository, EncoderFactoryInterface $encoderFactory, EventDispatcherInterface $eventDispatcher, PasswordEncoderInterface $passwordEncoder, User $user, Credentials $credentials, RegisterUserAction $action)
 {
     // Mocks
     $action->getUsername()->willReturn('mattketmo');
     $action->getDisplayName()->willReturn('Matthieu Moquet');
     $action->getEmail()->willReturn('*****@*****.**');
     $action->getPassword()->willReturn('super_passw0rd');
     $action->getPreferredLocale()->willReturn('fr_FR');
     $encoderFactory->getEncoder($user)->willReturn($passwordEncoder);
     $passwordEncoder->encodePassword('super_passw0rd', Argument::type('string'))->willReturn('encoded_password==');
     $userRepository->createNew(Argument::exact(new Username('mattketmo')))->willReturn($user);
     $credentialsRepository->createNew($user, 'encoded_password==', Argument::type('string'))->shouldBeCalled()->willReturn($credentials);
     $user->setName(Argument::exact(new Name('Matthieu Moquet')))->shouldBeCalled()->willReturn($user);
     $user->setEmail(Argument::exact(new Email('*****@*****.**')))->shouldBeCalled()->willReturn($user);
     $user->setPreferredLocale(Argument::exact(Locale::parse('fr_FR')))->shouldBeCalled()->willReturn($user);
     $userRepository->save($user)->shouldBeCalled();
     $credentialsRepository->save($credentials)->shouldBeCalled();
     $this->execute($action)->shouldReturn($user);
 }
Ejemplo n.º 26
0
 /**
  * @Then the password for user ":username" should be ":password"
  *
  * @param $username
  * @param $password
  */
 public function thePasswordForUserShouldBe($username, $password)
 {
     $user = $this->userManager->findUserByUsername($username);
     if (null === $user) {
         throw new \InvalidArgumentException(sprintf('No user with username %s can be found', $username));
     }
     $encoder = $this->encoderFactory->getEncoder($user);
     $valid = $encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt());
     PHPUnit::assertTrue($valid, sprintf('The password for user %s does not match %s', $username, $password));
 }
 /**
  * Authenticate a token according to the user provided with password encoder.
  *
  * @param \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token
  * @param \Symfony\Component\Security\Core\User\UserInterface                  $user
  *
  * @return boolean|\BackBee\Security\Token\UsernamePasswordToken
  */
 private function authenticateWithEncoder(TokenInterface $token, UserInterface $user)
 {
     try {
         $classname = \Symfony\Component\Security\Core\Util\ClassUtils::getRealClass($user);
         if (true === $this->_encoderFactory->getEncoder($classname)->isPasswordValid($user->getPassword(), $token->getCredentials(), $user->getSalt())) {
             return new UsernamePasswordToken($user, $user->getPassword(), $user->getRoles());
         }
     } catch (Exception $e) {
         return false;
     }
 }
Ejemplo n.º 28
0
 /**
  * @param FixtureCollectionEvent $event
  * @throws \DavidBadura\Fixtures\Util\ObjectAccess\ObjectAccessException
  */
 public function onPostExecute(FixtureCollectionEvent $event)
 {
     $fixtures = $event->getCollection();
     foreach ($fixtures as $fixture) {
         $properties = $fixture->getProperties();
         if (!isset($properties['security']) || $properties['security'] == false) {
             continue;
         }
         $passwordField = isset($properties['security']['password']) ? $properties['security']['password'] : '******';
         $saltField = isset($properties['security']['salt']) ? $properties['security']['salt'] : 'salt';
         foreach ($fixture as $data) {
             $object = $data->getObject();
             if (!$object) {
                 continue;
             }
             $encoder = $this->factory->getEncoder($object);
             $access = new ObjectAccess($object);
             $password = $encoder->encodePassword($access->readProperty($passwordField), $access->readProperty($saltField));
             $access->writeProperty($passwordField, $password);
         }
     }
 }
Ejemplo n.º 29
0
 /**
  * Update the users password and/or salt
  *
  * @param User   $user
  * @param string $password New password
  * @param string $salt     If Ommitted, the salt will not be updated
  * @param bool   $flush    Flush the entity manager on completion
  */
 public function updateUserCredentials(User $user, $password, $salt = null, $flush = true)
 {
     if (!$salt) {
         $salt = $user->getSalt() ?: $this->generateSalt();
     }
     $encoder = $this->encoder_factory->getEncoder($user);
     $password = $encoder->encodePassword($password, $salt);
     $user->setPassword($password);
     $user->setSalt($salt);
     $this->entity_manager->persist($user);
     if ($flush) {
         $this->entity_manager->flush();
     }
 }
Ejemplo n.º 30
0
 public function changePassword($token, $data)
 {
     $em = $this->entityManager;
     $user = $em->getRepository('NaidusvoeBundle:User')->findOneBy(['confirmationToken' => $token]);
     if ($user !== null) {
         $encoder = $this->encoderFactory->getEncoder(new User());
         $user->setPassword($encoder->encodePassword($data, $user->getSalt()));
         $user->setConfirmationToken(null);
         $em->persist($user);
         $em->flush();
         return true;
     } else {
         return false;
     }
 }