/**
  * {@inheritdoc}
  */
 protected function retrieveUser($username, UsernamePasswordToken $token)
 {
     $user = $token->getUser();
     if ($user instanceof UserInterface) {
         return $user;
     }
     try {
         if ($this->getAuthService()->hasPartnerAuth()) {
             try {
                 $user = $this->userProvider->loadUserByUsername($username);
                 $bind = $this->getUserService()->getUserBindByTypeAndUserId($this->getAuthService()->getPartnerName(), $user['id']);
                 if ($bind) {
                     $partnerUser = $this->getAuthService()->checkPartnerLoginById($bind['fromId'], $token->getCredentials());
                     if ($partnerUser) {
                         $user = $this->syncEmailAndPassword($user, $partnerUser, $token);
                     }
                 }
             } catch (UsernameNotFoundException $notFound) {
                 if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
                     $partnerUser = $this->getAuthService()->checkPartnerLoginByEmail($username, $token->getCredentials());
                 } else {
                     $partnerUser = $this->getAuthService()->checkPartnerLoginByNickname($username, $token->getCredentials());
                 }
                 if (empty($partnerUser)) {
                     throw $notFound;
                 }
                 $bind = $this->getUserService()->getUserBindByTypeAndFromId($this->getAuthService()->getPartnerName(), $partnerUser['id']);
                 if ($bind) {
                     $user = $this->getUserService()->getUser($bind['toId']);
                     $user = $this->syncEmailAndPassword($user, $partnerUser, $token);
                 } else {
                     $setting = $this->getSettingService()->get('user_partner', array());
                     $email_filter = explode("\n", $setting['email_filter']);
                     if (in_array($partnerUser['email'], $email_filter)) {
                         $partnerUser['email'] = $partnerUser['id'] . '_dz_' . $this->getRandomString(5) . '@edusoho.net';
                     }
                     $registration = array();
                     $registration['nickname'] = $partnerUser['nickname'];
                     $registration['email'] = $partnerUser['email'];
                     $registration['password'] = $token->getCredentials();
                     $registration['createdIp'] = $partnerUser['createdIp'];
                     $registration['token'] = array('userId' => $partnerUser['id']);
                     $this->getUserService()->register($registration, $this->getAuthService()->getPartnerName());
                     $user = $this->userProvider->loadUserByUsername($username);
                 }
             }
         } else {
             $user = $this->userProvider->loadUserByUsername($username);
         }
         if (!$user instanceof UserInterface) {
             throw new AuthenticationServiceException('The user provider must return a UserInterface object.');
         }
         return $user;
     } catch (UsernameNotFoundException $notFound) {
         $notFound->setUsername($username);
         throw $notFound;
     } catch (\Exception $repositoryProblem) {
         $ex = new AuthenticationServiceException($repositoryProblem->getMessage(), 0, $repositoryProblem);
         $ex->setToken($token);
         throw $ex;
     }
 }
 /**
  *
  * @param \DateTime $startDate beginning >=
  * @param \DateTime $endDate   end <=
  * @param           $type      - type of the StatisticEntryFilter
  *
  * @return StatisticEntry[]
  *
  * Note: can be replaced with DQL if performance issues are notable
  */
 public function getStatisticForRangeAndType(\DateTime $startDate, \DateTime $endDate, $type = null)
 {
     /** @var TrainingDayRepository $trainingDayRepository */
     $trainingDayRepository = $this->manager->getRepository('TrainingScheduleBundle:TrainingDay');
     $expr = Criteria::expr();
     $criteria = Criteria::create();
     $criteria->where($expr->gte('date', $startDate));
     $criteria->andWhere($expr->lte('date', $endDate));
     $criteria->andWhere($expr->eq('user', $this->userToken->getUser()));
     /** @var LazyCriteriaCollection $trainingDays */
     $trainingDays = $trainingDayRepository->matching($criteria);
     $result = array();
     /** @var TrainingDay $trainingDay * */
     foreach ($trainingDays as $trainingDay) {
         foreach ($trainingDay->getStatistics() as $statistic) {
             /** @var StatisticEntry $statistic */
             if ($type != null) {
                 if ($statistic->getName() === $type) {
                     $result[] = $statistic;
                 }
             } else {
                 $result[] = $statistic;
             }
         }
     }
     return $result;
 }
 public function authUserFromRedmine(UsernamePasswordToken $token)
 {
     $pass = $token->getCredentials();
     $username = $token->getUser();
     try {
         $response = $this->client->redmineLogin($username, $pass);
         $q = json_decode($response);
         $em = $this->em;
         $user = $em->getRepository("RedmineAppBundle:RedmineUser")->findOneBy(['redmineToken' => $q->user->api_key, 'redmineUserID' => $q->user->id]);
         if ($user) {
             return $user->getUsername();
         } else {
             $user = new RedmineUser();
             $user->setUsername($q->user->login)->setEmail($q->user->mail)->setPassword($this->encoder->encodePassword($user, md5(uniqid())))->setName($q->user->firstname)->setSurname($q->user->lastname)->setRedmineUserID($q->user->id)->setRedmineToken($q->user->api_key);
             $settings = new Settings();
             $settings->setSms(false)->setPush(false)->setCheckFirst(Carbon::createFromTime(17, 45))->setCheckSecond(Carbon::createFromTime(20, 0))->setCheckThird(Carbon::createFromTime(9, 30))->setUser($user);
             $this->em->persist($user);
             $this->em->persist($settings);
             $this->em->flush();
             return $user->getUsername();
         }
     } catch (\Exception $e) {
         return null;
     }
 }
 public function authenticate(TokenInterface $token)
 {
     $user = $this->userProvider->loadUserByUsername($token->getUsername());
     $newToken = new UserToken($token->getUser(), $token->getCredentials(), "secured_area", $user->getRoles());
     $username = $newToken->getUser();
     if (empty($username)) {
         throw new BadCredentialsException('Bad credentials :)');
     }
     return $newToken;
 }
 public function authenticate(TokenInterface $token)
 {
     $user = $this->userProvider->loadUserByUsername($token->getUser(), $token->getCredentials());
     $newToken = new UserToken($token->getUser(), $token->getCredentials(), "main", $user->getRoles());
     $encoder = $this->encoder->getEncoder($user);
     // compute the encoded password
     $encodedPassword = $encoder->encodePassword($token->getCredentials(), $user->salt);
     $newToken = new UserToken($token->getUser(), $token->getCredentials(), "secured_area", $user->getRoles());
     $username = $newToken->getUser();
     if (empty($username) || $user->getPassword() != $encodedPassword) {
         throw new BadCredentialsException('Bad credentials :)');
     }
     return $newToken;
 }
 /**
  * {@inheritdoc}
  */
 protected function retrieveUser($username, UsernamePasswordToken $token)
 {
     $user = $token->getUser();
     if ($user instanceof UserInterface) {
         return $user;
     }
     try {
         $user = $this->userProvider->loadUserByUsernameAndPassword($username, $token->getCredentials());
         if (!$user instanceof UserInterface) {
             throw new AuthenticationServiceException('The user provider must return a UserInterface object.');
         }
         return $user;
     } catch (UsernameNotFoundException $notFound) {
         throw $notFound;
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function retrieveUser($username, UsernamePasswordToken $token)
 {
     $user = $token->getUser();
     if ($user instanceof UserInterface) {
         return $user;
     }
     try {
         $user = $this->userProvider->loadUserByUsername($username);
         if (!$user instanceof UserInterface) {
             throw new AuthenticationServiceException('The user provider must return a UserInterface object.');
         }
         return $user;
     } catch (UsernameNotFoundException $notFound) {
         throw $notFound;
     } catch (\Exception $repositoryProblem) {
         throw new AuthenticationServiceException($repositoryProblem->getMessage(), $token, 0, $repositoryProblem);
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
 {
     $currentUser = $token->getUser();
     $presentedPassword = $token->getCredentials();
     if ($currentUser instanceof UserInterface) {
         if ('' === $presentedPassword) {
             throw new BadCredentialsException('The password in the token is empty. You may forgive turn off `erase_credentials` in your `security.yml`');
         }
         if (!$this->ldapManager->bind($currentUser, $presentedPassword)) {
             throw new BadCredentialsException('The credentials were changed from another session.');
         }
     } else {
         if ('' === $presentedPassword) {
             throw new BadCredentialsException('The presented password cannot be empty.');
         }
         if (!$this->ldapManager->bind($user, $presentedPassword)) {
             throw new BadCredentialsException('The presented password is invalid.');
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
 {
     $currentUser = $token->getUser();
     if ($currentUser instanceof LdapUserInterface) {
         if (!$this->ldapManager->bind($currentUser, $currentUser->getPassword())) {
             throw new BadCredentialsException('The credentials were changed from another session.');
         }
     } else {
         if (!$user->getDn()) {
             $userLdap = $this->ldapManager->findUserByUsername($user->getUsername());
             if (!$userLdap) {
                 throw new BadCredentialsException(sprintf('User "%s" not found', $user->getUsername()));
             }
             $user->setDn($userLdap->getDn());
         }
         if (!($presentedPassword = $token->getCredentials())) {
             throw new BadCredentialsException('The presented password cannot be empty.');
         }
         if (!$this->ldapManager->bind($user, $presentedPassword)) {
             throw new BadCredentialsException('The presented password is invalid.');
         }
     }
 }
 /**
  * Attempts to switch to another user.
  *
  * @param Request $request A Request instance
  *
  * @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise
  *
  * @throws \LogicException
  * @throws AccessDeniedException
  */
 private function attemptSwitchUser(Request $request)
 {
     $token = $this->securityContext->getToken();
     $originalToken = $this->getOriginalToken($token);
     if (false !== $originalToken) {
         if ($token->getUsername() === $request->get($this->usernameParameter)) {
             return $token;
         } else {
             throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername()));
         }
     }
     if (false === $this->accessDecisionManager->decide($token, array($this->role))) {
         throw new AccessDeniedException();
     }
     $username = $request->get($this->usernameParameter);
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Attempt to switch to user "%s"', $username));
     }
     $user = $this->provider->loadUserByUsername($username);
     $this->userChecker->checkPostAuth($user);
     $roles = $user->getRoles();
     $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $this->securityContext->getToken());
     $token = new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey, $roles);
     if (null !== $this->dispatcher) {
         $switchEvent = new SwitchUserEvent($request, $token->getUser());
         $this->dispatcher->dispatch(SecurityEvents::SWITCH_USER, $switchEvent);
     }
     return $token;
 }
 /**
  * Attempts to switch to another user.
  *
  * @param Request $request A Request instance
  *
  * @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise
  */
 protected function attemptSwitchUser(Request $request)
 {
     $token = $this->securityContext->getToken();
     if (false !== $this->getOriginalToken($token)) {
         throw new \LogicException(sprintf('You are already switched to "%s" user.', (string) $token));
     }
     $this->accessDecisionManager->decide($token, array($this->role));
     $username = $request->get($this->usernameParameter);
     if (null !== $this->logger) {
         $this->logger->debug(sprintf('Attempt to switch to user "%s"', $username));
     }
     $user = $this->provider->loadUserByUsername($username);
     $this->accountChecker->checkPostAuth($user);
     $roles = $user->getRoles();
     $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $this->securityContext->getToken());
     $token = new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey, $roles);
     $token->setImmutable(true);
     if (null !== $this->eventDispatcher) {
         $this->eventDispatcher->notify(new Event($this, 'security.switch_user', array('request' => $request, 'target_user' => $token->getUser())));
     }
     return $token;
 }
 /**
  * @param UserInterface $user
  * @param UsernamePasswordToken $token
  */
 protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token)
 {
     $currentUser = $token->getUser();
     if ($currentUser instanceof UserInterface) {
         // this happens if we were already logged in
         if ($currentUser->getPassword() !== $user->getPassword()) {
             throw new BadCredentialsException('The credentials were changed from another session.');
         }
     } else {
         if ("" === ($presentedPassword = $token->getCredentials())) {
             throw new BadCredentialsException('The presented password cannot be empty.');
         }
         if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) {
             throw new BadCredentialsException('The presented password is invalid.');
         }
     }
     if ($token->hasAttribute('desired_user')) {
         $roles = $user->getRoles();
         if (!in_array('ROLE_ALLOWED_TO_SWITCH', $roles)) {
             throw new BadCredentialsException('You are not allowed to login as other users.');
         }
     }
 }
Beispiel #13
0
 /**
  * Authenticates the user via ldap
  *
  * @param \Symfony\Component\Security\Core\User\UserInterface $user
  * @param \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken $token
  * @return boolean $passwordValid
  * @throws BadCredentialsException
  */
 protected function checkAuthenticationLdap(UserInterface $user, UsernamePasswordToken $token)
 {
     $currentUser = $token->getUser();
     // Due to ldap restrinctions we expect a user authenticated once the token
     // contains a user object
     if ($currentUser instanceof UserInterface) {
         return true;
     }
     try {
         $this->ldapManager->bind($token->getUsername(), $token->getCredentials());
         $passwordValid = (bool) $this->ldapManager->getBoundUser();
         if (null !== $this->logger && !$token->isAuthenticated()) {
             $this->logger->info("[LdapAuthenticator] Ldap authentication successful.", array('user' => $this->ldapManager->getBoundUser()));
         }
         return $passwordValid;
     } catch (\Zend\Ldap\Exception\LdapException $e) {
         throw new BadCredentialsException('Ldap authentication failed', 0, $e);
     }
 }
 public function importAuthenticatedUser(UsernamePasswordToken $token)
 {
     $this->userRepository->importAuthenticatedUser($token->getUser());
 }