/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $schoolId = $input->getOption('schoolId'); if (!$schoolId) { $schoolTitles = []; foreach ($this->schoolManager->findBy([], ['title' => 'ASC']) as $school) { $schoolTitles[$school->getTitle()] = $school->getId(); } $helper = $this->getHelper('question'); $question = new ChoiceQuestion("What is this user's primary school?", array_keys($schoolTitles)); $question->setErrorMessage('School %s is invalid.'); $schoolTitle = $helper->ask($input, $output, $question); $schoolId = $schoolTitles[$schoolTitle]; } $school = $this->schoolManager->findOneBy(['id' => $schoolId]); if (!$school) { throw new \Exception("School with id {$schoolId} could not be found."); } $userRecord = ['firstName' => $input->getOption('firstName'), 'lastName' => $input->getOption('lastName'), 'email' => $input->getOption('email'), 'telephoneNumber' => $input->getOption('telephoneNumber'), 'campusId' => $input->getOption('campusId'), 'username' => $input->getOption('username'), 'password' => $input->getOption('password')]; $userRecord = $this->fillUserRecord($userRecord, $input, $output); $user = $this->userManager->findOneBy(['campusId' => $userRecord['campusId']]); if ($user) { throw new \Exception('User #' . $user->getId() . " with campus id {$userRecord['campusId']} already exists."); } $user = $this->userManager->findOneBy(['email' => $userRecord['email']]); if ($user) { throw new \Exception('User #' . $user->getId() . " with email address {$userRecord['email']} already exists."); } $table = new Table($output); $table->setHeaders(array('Campus ID', 'First', 'Last', 'Email', 'Username', 'Phone Number'))->setRows(array([$userRecord['campusId'], $userRecord['firstName'], $userRecord['lastName'], $userRecord['email'], $userRecord['username'], $userRecord['telephoneNumber']])); $table->render(); $helper = $this->getHelper('question'); $output->writeln(''); $question = new ConfirmationQuestion("<question>Do you wish to add this user to Ilios in {$school->getTitle()}?</question>\n", true); if ($helper->ask($input, $output, $question)) { $user = $this->userManager->create(); $user->setFirstName($userRecord['firstName']); $user->setLastName($userRecord['lastName']); $user->setEmail($userRecord['email']); $user->setCampusId($userRecord['campusId']); $user->setAddedViaIlios(true); $user->setEnabled(true); $user->setSchool($school); $user->setUserSyncIgnore(false); $this->userManager->update($user); $authentication = $this->authenticationManager->create(); $authentication->setUsername($userRecord['username']); $user->setAuthentication($authentication); $encodedPassword = $this->encoder->encodePassword($user, $userRecord['password']); $authentication->setPasswordBcrypt($encodedPassword); $this->authenticationManager->update($authentication); $output->writeln('<info>Success! New user #' . $user->getId() . ' ' . $user->getFirstAndLastName() . ' created.</info>'); } else { $output->writeln('<comment>Canceled.</comment>'); } }
/** * @param $username * @param $password * @return \SSPSoftware\ApiTokenBundle\Entity\ApiTokenInterface */ public function authenticate($username, $password) { $user = $this->userProvider->loadUserByUsername($username); if (!$this->passwordEncoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) { throw new AuthenticationException('Bad credentials'); } return $this->apiTokenRepository->createApiToken($user); }
private function encodePassword(User $user) { if (!$user->getRawPassword()) { return; } $password = $this->passwordEncoder->encodePassword($user, $user->getRawPassword()); $user->setPassword($password); }
/** * {@inheritdoc} */ public function checkCredentials($credentials, UserInterface $user) { $plainPassword = $credentials['password']; if (!$this->encoder->isPasswordValid($user, $plainPassword)) { throw new BadCredentialsException(); } return true; }
/** * {@inheritdoc} */ public function validate($object, Constraint $constraint) { $methodPassword = '******' . ucfirst($constraint->fieldPassword); $methodUser = '******' . ucfirst($constraint->fieldUser); $user = $object->{$methodUser}(); $currentPassword = $user->getPassword(); $encodedPassword = $this->encoder->encodePassword($user, $object->{$methodPassword}()); if ($currentPassword !== $encodedPassword) { $this->context->buildViolation($constraint->message)->addViolation(); } }
/** * @param LifecycleEventArgs $event */ public function processPasswordEncodingIfNeeded(LifecycleEventArgs $event) { $entity = $event->getEntity(); if (!$entity instanceof AdminUser) { return; } $plainPassword = $entity->getPlainPassword(); if ($plainPassword === null) { return; } $entity->setPassword($this->passwordEncoder->encodePassword($entity, $plainPassword)); }
public function __invoke($username, $password) { try { $user = $this->userProvider->loadUserByUsername($username); } catch (UsernameNotFoundException $e) { // in order to prevent timing attacks, we call the same method on a dummy user // this way it is not revealed that the user by that username does not exist in DB $this->passwordEncoder->isPasswordValid(AccountUser::dummy(), 'dummy'); return false; } return $this->passwordEncoder->isPasswordValid($user, $password) ? $username : false; }
/** * Authenticates a user. * * @param string $userUniqueIdentifier The username or the email of the user. * @param string $password Plain text password. * @return User */ public function authenticateUser($userUniqueIdentifier, $password) { $user = $this->userManager->getUserByUserNameOrEmail($userUniqueIdentifier); if (!$user) { throw new Exception('There is no user with this email or username.'); } if (!$this->passwordEncoder->isPasswordValid($user, $password)) { throw new Exception('Incorrect password.'); } $user = $this->setUserApiKey($user); return $user; }
/** * {@inheritdoc} */ public function load(ObjectManager $manager) { $userRecords = [['username' => 'raphy', 'password' => 'test']]; foreach ($userRecords as $userRecord) { $user = new User(); $user->setUsername($userRecord['username']); $password = $this->encoder->encodePassword($user, $userRecord['password']); $user->setPassword($password); $manager->persist($user); } $manager->flush(); }
/** * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param $providerKey * @return UsernamePasswordToken */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { try { $user = $userProvider->loadUserByUsername($token->getUsername()); } catch (UsernameNotFoundException $e) { throw new CustomUserMessageAuthenticationException('Invalid username or password'); } $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials()); if ($passwordValid) { return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles()); } throw new CustomUserMessageAuthenticationException('Invalid username or password'); }
public function updateUser(User $user, $userData) { if ($userData['username'] != $user->getUsername()) { $user->setUsername($userData['username']); } if ($userData['firstName'] != $user->getUserFirstName()) { $user->setUserFirstName($userData['firstName']); } if ($userData['lastName'] != $user->getUserLastName()) { $user->setUserLastName($userData['lastName']); } if ($userData['password'] != "") { $password = $this->passwordEncoder->encodePassword($user, $userData['password']); $user->setPassword($password); } if ($userData['email'] != $user->getEmail()) { $user->setEmail($userData['email']); } $roles = $this->getRoles(); $this->assignAppropriateRoles($user, $userData['roleId'], $roles); $errors = $this->validator->validate($user, null, array('registration')); if (count($errors) > 0) { throw new ValidatorException($errors); } $this->userManager->saveChanges(); return $user; }
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name', TextType::class, ['constraints' => [new NotBlank(['groups' => ['create']])]]); $builder->add('email', EmailType::class, ['constraints' => [new NotBlank(['groups' => ['create']])]]); $builder->add('plainPassword', PasswordType::class, ['constraints' => [new NotBlank(['groups' => ['create']]), new Length(['max' => 72])], 'required' => false]); $builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) { /** @var User $user */ $user = $event->getData(); if ($user->getPlainPassword() === null) { return; } $password = $this->passwordEncoder->encodePassword($user, $user->getPlainPassword()); $user->setPassword($password); }, 10); // Priority before the validation. }
/** * Authenticate via the form using users defined in authorized_users * * @param AuthenticationEvent $event * * @return bool|void */ public function onUserFormAuthentication(AuthenticationEvent $event) { $username = $event->getUsername(); $password = $event->getToken()->getCredentials(); $user = new User(); $user->setUsername($username); $authorizedUsers = $this->parametersHelper->getParameter('authorized_users'); if (is_array($authorizedUsers) && isset($authorizedUsers[$username])) { $testUser = $authorizedUsers[$username]; $user->setPassword($testUser['password']); if ($this->encoder->isPasswordValid($user, $password)) { $user->setFirstName($testUser['firstname'])->setLastName($testUser['lastname'])->setEmail($testUser['email'])->setRole($this->em->getReference('MauticUserBundle:Role', 1)); $event->setIsAuthenticated('authorized_users', $user, true); } } }
/** * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param $providerKey * @return UsernamePasswordToken */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { try { if ($userProvider instanceof IsidoreApiUserProvider) { $user = $userProvider->loadUser($token->getUsername(), $token->getCredentials()); } else { $user = $userProvider->loadUserByUsername($token->getUsername()); } } catch (UsernameNotFoundException $e) { throw new CustomUserMessageAuthenticationException("Identifiant ou mot de passe incorrect. Veuillez réessayer."); } $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials()); if ($passwordValid) { return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles()); } throw new CustomUserMessageAuthenticationException("Identifiant ou mot de passe incorrect. Veuillez réessayer."); }
/** * @param $email * @param $password * @param $firstName * @param $lastName */ public function create($email, $password, $firstName, $lastName) { $role = User::ROLE_ADMIN; $em = $this->doctrine->getManager(); $user = $em->getRepository('AppBundle:User')->findBy(['email' => $email]); if (!$user) { $user = new User(); } else { $user = $user[0]; } $pass = $this->userPasswordEncoder->encodePassword($user, $password); $user->setEmail($email); $user->setFirstName($firstName); $user->setLastName($lastName); $user->setPassword($pass); $user->setRole($role); $user->setIsActive(true); $em->persist($user); $em->flush(); }
/** * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param string $providerKey * * @return UsernamePasswordToken */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { if (empty($this->secretKey) == false) { $captcha = $this->request->get('g-recaptcha-response'); $reCaptcha = new ReCaptcha($this->secretKey); $response = $reCaptcha->verify($captcha, $this->request->getClientIp()); if ($response->isSuccess() == false) { throw new AuthenticationException('Captcha not passed'); } } try { $user = $userProvider->loadUserByUsername($token->getUsername()); } catch (UsernameNotFoundException $e) { throw new AuthenticationException('Invalid username or password'); } $passwordValid = $this->encoder->isPasswordValid($user, $token->getCredentials()); if ($passwordValid) { return new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles()); } throw new AuthenticationException('Invalid username or password'); }
/** * Update users to the new password encoding when they login * @param AuthenticationEntityInterface $authEntity * @param string $password */ protected function updateLegacyPassword(AuthenticationEntityInterface $authEntity, $password) { if ($authEntity->isLegacyAccount()) { //we have to have a valid token to update the user because the audit log requires it $authenticatedToken = new PreAuthenticatedToken($authEntity->getUser(), 'fakekey', 'fakeProvider'); $authenticatedToken->setAuthenticated(true); $this->tokenStorage->setToken($authenticatedToken); $authEntity->setPasswordSha256(null); $encodedPassword = $this->encoder->encodePassword($authEntity->getUser(), $password); $authEntity->setPasswordBcrypt($encodedPassword); $this->authManager->updateAuthentication($authEntity); } }
/** * @param TokenInterface $token * @param UserProviderInterface $userProvider * @param $providerKey * * @return UsernamePasswordToken */ public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey) { $authenticated = false; $authenticationService = null; $response = null; $failedAuthMessage = null; $user = $token->getUser(); $authenticatingService = $token instanceof PluginToken ? $token->getAuthenticatingService() : null; if (!$user instanceof User) { try { $user = $userProvider->loadUserByUsername($token->getUsername()); } catch (UsernameNotFoundException $e) { } // Will try with the given password unless the plugin explicitly failed authentication $tryWithPassword = true; // Try authenticating with a plugin first if ($this->dispatcher->hasListeners(UserEvents::USER_FORM_AUTHENTICATION)) { $integrations = $this->integrationHelper->getIntegrationObjects($authenticatingService, ['sso_form'], false, null, true); $authEvent = new AuthenticationEvent($user, $token, $userProvider, $this->request, false, $authenticatingService, $integrations); $this->dispatcher->dispatch(UserEvents::USER_FORM_AUTHENTICATION, $authEvent); if ($authenticated = $authEvent->isAuthenticated()) { $user = $authEvent->getUser(); $authenticatingService = $authEvent->getAuthenticatingService(); } elseif ($authEvent->isFailed()) { $tryWithPassword = false; } $response = $authEvent->getResponse(); $failedAuthMessage = $authEvent->getFailedAuthenticationMessage(); } if (!$authenticated && $tryWithPassword && $user instanceof User) { // Try authenticating with local password $authenticated = $this->encoder->isPasswordValid($user, $token->getCredentials()); } } else { // Assume the user is authenticated although the token will tell for sure $authenticated = true; } if ($authenticated) { return new PluginToken($providerKey, $authenticatingService, $user, $user->getPassword(), $user->getRoles(), $response); } elseif ($response) { return new PluginToken($providerKey, $authenticatingService, $user, '', [], $response); } if ($failedAuthMessage) { throw new AuthenticationException($failedAuthMessage); } throw new BadCredentialsException(); }
public function updateUser(User $user) { $user->setPassword($this->encoder->encodePassword($user, $this->password)); return $user; }
public function updateUser(User $user) { $user->setEmail($this->email); $user->setName($this->name); $user->setPassword($this->passwordEncoder->encodePassword($user, $this->password)); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { // prevent this command to run on a non-empty user store. $existingUser = $this->userManager->findOneBy([]); if (!empty($existingUser)) { throw new \Exception('Sorry, at least one user record already exists. Cannot create a "first" user account.'); } $schools = $this->schoolManager->findBy([], ['title' => 'ASC']); // check if any school data is present before invoking the form helper // to prevent the form from breaking on missing school data further downstream. if (empty($schools)) { throw new \Exception('No schools found. Please load schools into this Ilios instance first.'); } $schoolId = $input->getOption('school'); if (!$schoolId) { $schoolTitles = []; /* @var SchoolInterface $school */ foreach ($schools as $school) { $schoolTitles[$school->getTitle()] = $school->getId(); } $helper = $this->getHelper('question'); $question = new ChoiceQuestion("What is this user's primary school?", array_keys($schoolTitles)); $question->setErrorMessage('School %s is invalid.'); $schoolTitle = $helper->ask($input, $output, $question); $schoolId = $schoolTitles[$schoolTitle]; } $school = $this->schoolManager->findOneBy(['id' => $schoolId]); if (!$school) { throw new \Exception("School with id {$schoolId} could not be found."); } $email = $input->getOption('email'); if (!$email) { $question = new Question("What is the user's Email Address? "); $question->setValidator(function ($answer) { if (!filter_var($answer, FILTER_VALIDATE_EMAIL)) { throw new \RuntimeException("Email is not valid"); } return $answer; }); $email = $this->getHelper('question')->ask($input, $output, $question); } $user = $this->userManager->create(); $user->setFirstName(self::FIRST_NAME); $user->setMiddleName(date('Y-m-d_h.i.s')); $user->setLastName(self::LAST_NAME); $user->setEmail($email); $user->setAddedViaIlios(true); $user->setEnabled(true); $user->setUserSyncIgnore(false); $user->addRole($this->userRoleManager->findOneBy(['title' => 'Developer'])); $user->addRole($this->userRoleManager->findOneBy(['title' => 'Course Director'])); $user->setSchool($school); $this->userManager->update($user); $authentication = $this->authenticationManager->create(); $authentication->setUser($user); $user->setAuthentication($authentication); $encodedPassword = $this->passwordEncoder->encodePassword($user, self::PASSWORD); $authentication->setUsername(self::USERNAME); $authentication->setPasswordBcrypt($encodedPassword); $this->authenticationManager->update($authentication); $output->writeln('Success!'); $output->writeln('A user account has been created.'); $output->writeln(sprintf("You may now log in as '%s' with the password '%s'.", self::USERNAME, self::PASSWORD)); $output->writeln('Please change this password as soon as possible.'); }
/** * {@inheritDoc} */ public function checkCredentials($credentials, UserInterface $user) { return $this->passwordEncoder->isPasswordValid($user, $credentials->password); }
public function setNewPassword($password) { $this->newPassword = $this->passwordEncoder->encodePassword($this->user, $password); return $this; }
/** * @param string $plainPassword * @param UserPasswordEncoderInterface $encoder */ private function updatePassword(string $plainPassword, UserPasswordEncoderInterface $encoder) { $this->password = $encoder->encodePassword($this, $plainPassword); }