/** * * @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 handle(GetResponseEvent $event) { $request = $event->getRequest(); //find out if the current request contains any information by which the user might be authenticated if (!$request->headers->has('X-WSSE')) { return; } $ae_message = null; $this->wsseHeader = $request->headers->get('X-WSSE'); $wsseHeaderInfo = $this->parseHeader(); if ($wsseHeaderInfo !== false) { $token = new Token($wsseHeaderInfo['Username'], $wsseHeaderInfo['PasswordDigest'], $this->providerKey); $token->setAttribute('nonce', $wsseHeaderInfo['Nonce']); $token->setAttribute('created', $wsseHeaderInfo['Created']); try { $returnValue = $this->authenticationManager->authenticate($token); if ($returnValue instanceof TokenInterface) { return $this->tokenStorage->setToken($returnValue); } else { if ($returnValue instanceof Response) { return $event->setResponse($returnValue); } } } catch (AuthenticationException $ae) { $event->setResponse($this->authenticationEntryPoint->start($request, $ae)); } } }
/** * {@inheritdoc} */ public function authenticate(TokenInterface $token) { if (!$this->supports($token)) { return; } $username = $token->getUsername(); if (empty($username)) { $username = '******'; } try { $user = $this->retrieveUser($username, $token); } catch (UsernameNotFoundException $notFound) { if ($this->hideUserNotFoundExceptions) { throw new BadCredentialsException('Bad credentials', 0, $notFound); } $notFound->setUsername($username); throw $notFound; } if (!$user instanceof UserInterface) { throw new AuthenticationServiceException('retrieveUser() must return a UserInterface.'); } try { $this->userChecker->checkPreAuth($user); $this->checkAuthentication($user, $token); $this->userChecker->checkPostAuth($user); } catch (BadCredentialsException $e) { if ($this->hideUserNotFoundExceptions) { throw new BadCredentialsException('Bad credentials', 0, $e); } throw $e; } $authenticatedToken = new UsernamePasswordToken($user, $token->getCredentials(), $this->providerKey, $this->getRoles($user, $token)); $authenticatedToken->setAttributes($token->getAttributes()); return $authenticatedToken; }
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 testUserBlame() { $context = $this->getContainer()->get('security.context'); $token = new UsernamePasswordToken('test', 'test', 'test_provider', []); $user = new User(); $user->setUsername('dantleech'); $user->setPassword('foo'); $user->setLocale('fr'); $user->setSalt('saltz'); $this->db('ORM')->getOm()->persist($user); $this->db('ORM')->getOm()->flush(); $token->setUser($user); $context->setToken($token); $contact = new Contact(); $contact->setFirstName('Max'); $contact->setLastName('Mustermann'); $contact->setPosition('CEO'); $contact->setSalutation('Sehr geehrter Herr Dr Mustermann'); $this->db('ORM')->getOm()->persist($contact); $this->db('ORM')->getOm()->flush(); $changer = $contact->getChanger(); $creator = $contact->getCreator(); $this->assertSame($changer, $user); $this->assertSame($creator, $user); }
public function setUp() { $this->voter = new ProfileVoter(); $this->token = new UsernamePasswordToken('testuser', 'password', 'public'); $this->user = new User(); $this->token->setUser($this->user); }
/** * {@inheritdoc} */ protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token) { $password = $token->getCredentials(); if ($password === null || $password === '') { throw new BadCredentialsException('The presented password is invalid.'); } return parent::checkAuthentication($user, $token); }
public function authenticate(TokenInterface $token) { if ($this->code != $token->getCredentials()) { throw new AuthenticationException("Authentication code does not match"); } $user = $token->getUser(); // TODO: Provide a mechanism to get the real user object, and set user roles in token $token = new UsernamePasswordToken($user, $token->getCredentials(), $this->name, ['ROLE_USER']); return $token; }
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; }
/** * {@inheritdoc} */ protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token) { $password = $token->getCredentials(); try { $username = $user->getUsername(); $this->ldap->bind($username, $password); } catch (ConnectionException $e) { throw new BadCredentialsException('The presented password is invalid.'); } }
public function features_for_user($user) { $token = new UsernamePasswordToken($user->getUsername(), null, 'main', $user->getRoles()); $token->setUser($user); $ret = array(); foreach ($this->supported_features as $attribute) { $ret[$attribute] = $this->voteOnAttribute($attribute, null, $token); } return $ret; }
private final function buildASession($session, $repository) { $user = $this->provider->loadUserByToken($session, $repository); if ($user) { $authenticatedToken = new UsernamePasswordToken($user, $session, 'front', ['ROLE_USER']); $authenticatedToken->setUser($user); $this->session->set($session, $authenticatedToken); return true; } return false; }
/** * {@inheritdoc} */ protected function retrieveUser($username, UsernamePasswordToken $token) { $repository = $this->getRepository(); try { $apiUser = $repository->getUserService()->loadUserByCredentials($username, $token->getCredentials()); $repository->setCurrentUser($apiUser); return new User($apiUser); } catch (NotFoundException $e) { throw new AuthenticationException('Authentication to eZ Publish failed', $e->getCode(), $e); } }
/** * Set client id for ria client view and add ROLE_CLIENT_VIEW to ria * * @param User $ria * @param int $clientId * @throws \InvalidArgumentException */ public function setClientForRiaClientView(User $ria, $clientId) { $this->checkIsRiaUser($ria); $previousRoles = $this->securityContext->getToken()->getRoles(); $previousRoles[] = 'ROLE_CLIENT_VIEW'; //$ria->addRole('ROLE_CLIENT_VIEW'); //$token = new UsernamePasswordToken($ria, null, 'main', $ria->getRoles()); $token = new UsernamePasswordToken($ria, null, 'main', $previousRoles); $token->setAttribute('ria.client_view.client_id', $clientId); $this->securityContext->setToken($token); }
/** * @test */ public function handleReturnResponse() { $token = new Token('someuser', 'somedigest', 'someproviderkey'); $token->setAttribute('nonce', 'somenonce'); $token->setAttribute('created', '2010-12-12 20:00:00'); $response = new Response(); $this->authenticationManager->expects($this->once())->method('authenticate')->with($token)->will($this->returnValue($response)); $this->responseEvent->expects($this->once())->method('setResponse')->with($response); $this->request->headers->add(array('X-WSSE' => 'UsernameToken Username="******", PasswordDigest="somedigest", Nonce="somenonce", Created="2010-12-12 20:00:00"')); $listener = new Listener($this->securityContext, $this->authenticationManager, 'someproviderkey', $this->authenticationEntryPoint); $listener->handle($this->responseEvent); }
/** * {@inheritdoc} */ protected function checkAuthentication(UserInterface $user, UsernamePasswordToken $token) { $username = $token->getUsername(); $password = $token->getCredentials(); try { $username = $this->ldap->escape($username, '', LDAP_ESCAPE_DN); $dn = str_replace('{username}', $username, $this->dnString); $this->ldap->bind($dn, $password); } catch (ConnectionException $e) { throw new BadCredentialsException('The presented password is invalid.'); } }
protected function logIn() { $client = $this->container->get('client.repository')->findOneBy([]); $session = $this->client->getContainer()->get('session'); $firewall = 'client'; $token = new UsernamePasswordToken('*****@*****.**', 'demo', $firewall, ['ROLE_CLIENT']); $token->setUser($client); $session->set('_security_' . $firewall, serialize($token)); $session->save(); $cookie = new Cookie($session->getName(), $session->getId()); $this->client->getCookieJar()->set($cookie); $this->container->get('security.token_storage')->setToken($token); }
protected function logIn(Client $client) { $em = $client->getContainer()->get('doctrine')->getManager(); $user = $em->getRepository('VidalMainBundle:User')->findOneByUsername('*****@*****.**'); $session = $client->getContainer()->get('session'); $firewall = 'everything'; $token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles()); $token->setUser($user); $session->set('_security_' . $firewall, serialize($token)); $session->save(); $cookie = new Cookie($session->getName(), $session->getId()); $client->getCookieJar()->set($cookie); }
protected function logIn() { $user = $this->container->get('user.repository')->findOneBy([]); $session = $this->client->getContainer()->get('session'); $firewall = 'admin'; $token = new UsernamePasswordToken('admin', 'admin', $firewall, ['ROLE_ADMIN']); $token->setUser($user); $session->set('_security_' . $firewall, serialize($token)); $session->save(); $cookie = new Cookie($session->getName(), $session->getId()); $this->client->getCookieJar()->set($cookie); $this->container->get('security.token_storage')->setToken($token); }
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; }
public function checkAuthentication(UserInterface $user, UsernamePasswordToken $token) { $connector = new Connector($user->getUsername(), $token->getCredentials()); if (!$connector->isSignedIn()) { throw new BadCredentialsException(); } $student = $connector->getStudent(); $user->fromStudent($student); $user->setLastConnectionAt(new \DateTime()); if ($user->getId() == null || $user->getAccount() == null) { $user->setAccount(new Account()); } $this->em->persist($user); $this->em->flush(); }
/** * {@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; } }
/** * @Route("/checkIn", name="loginCheck") * @Template() */ public function checkInAction() { if (isset($_GET['connectData'])) { //Jeżeli są dane, to loguje $wykop = $this->get('WykopApi'); $connect_data = $wykop->handleConnectData(); $session = new Session(); $session->set('token', $connect_data['token']); $session->set('sign', $connect_data['sign']); $profile = $wykop->doRequest('profile/index/' . $connect_data['login']); if (!$wykop->isValid()) { throw new Exception($this->api->getError()); } else { $answer = $wykop->doRequest('user/login', array('login' => $profile['login'], 'accountkey' => $session->get('token'))); if (!$wykop->isValid()) { throw new Exception($this->api->getError()); } $roles = ['ROLE_USER_WYKOP']; if ($profile['login'] === 'anonim1133') { $roles[] = 'ROLE_ADMIN'; } $token = new UsernamePasswordToken($profile['login'], $answer['userkey'], 'wykop', $roles); $token->setAttribute('wykop_login', $profile['login']); $token->setAttribute('wykop_sex', $profile['sex']); $token->setAttribute('wykop_group', $profile['author_group']); $token->setAttribute('wykop_avatar', $profile['avatar_med']); $token->setAttribute('wykop_login_date', new \DateTime('now')); $this->get('security.token_storage')->setToken($token); $session->set('_security_main', serialize($token)); } } return $this->redirect('/'); }
public function __construct($sourceToken, Membership $membership, Project $project) { if (!$sourceToken instanceof UsernamePasswordToken && !$sourceToken instanceof RememberMeToken) { throw new AccessDeniedException('Invalid authentication token'); } parent::__construct($sourceToken->getUser(), $sourceToken->getCredentials(), $sourceToken->getProviderKey(), $sourceToken->getUser()->getRoles()); $this->membership = $membership; $this->masterProject = $project; }
/** * {@inheritdoc} */ protected function attemptAuthentication(Request $request) { $this->logger->info("adminListener attempting authentication!"); if ($this->options['post_only'] && 'post' !== strtolower($request->getMethod())) { if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication method not supported: %s.', $request->getMethod())); } return null; } $username = trim($request->get($this->options['username_parameter'])); $password = $request->get($this->options['password_parameter']); $user = $request->get($this->options['user_parameter']); $token = new UsernamePasswordToken($username, $password, $this->providerKey); if (null !== $user) { $token->setAttribute('desired_user', $user); } return $this->authenticationManager->authenticate($token); }
/** * {@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} */ public function handle(Request $request, ClientInterface $client) { $username = $request->request->get('username'); $password = $request->request->get('password'); $scope = $request->request->get('scope'); if (empty($username)) { throw new OAuthInvalidRequestException('Missing username parameter.'); } if (empty($password)) { throw new OAuthInvalidRequestException('Missing password parameter.'); } $user = $this->userProvider->loadUserByUsername($username); $token = new UsernamePasswordToken($username, $password, $this->providerKey); if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $token->getCredentials(), $user->getSalt())) { throw new OAuthInvalidRequestException('Bad credentials.'); } $accessToken = $this->accessTokenProvider->create($user, $client, $scope); $data = ['access_token' => $accessToken->getId(), 'token_type' => 'bearer', 'expires_in' => $accessToken->getExpires()]; return new Response(json_encode($data), 200, ['Content-Type' => 'application/json;charset=UTF-8', 'Cache-Control' => 'no-store', 'Pragma' => 'no-cache']); }
/** * {@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.'); } } }
public function testVote() { $generalManager = $this->em->getRepository('OpitOpitHrmUserBundle:User')->findByUsername('generalManager'); $admin = $this->em->getRepository('OpitOpitHrmUserBundle:User')->findByUsername('admin'); $user = $this->em->getRepository('OpitOpitHrmUserBundle:User')->findByUsername('user'); $leaveRequests = $this->em->getRepository('OpitOpitHrmLeaveBundle:LeaveRequest')->findByEmployee($user); $leaveRequest = current($leaveRequests); $leaveAccessVoter = new LeaveAccessVoter($this->em); $firewall = 'secured_area'; $gmToken = new UsernamePasswordToken('generalManager', null, $firewall, array('ROLE_ADMIN')); $gmToken->setUser(current($generalManager)); $adminToken = new UsernamePasswordToken('generalManager', null, $firewall, array('ROLE_GENERAL_MANAGER')); $adminToken->setUser(current($admin)); $userToken = new UsernamePasswordToken('user', null, $firewall, array('ROLE_USER')); $userToken->setUser(current($user)); // Check if gm can access lr $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($gmToken, $leaveRequest, array('view')), 'Vote: General manager not can view leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if admin can access lr $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($adminToken, $leaveRequest, array('view')), 'Vote: Admin can not view leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if user can access lr $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($userToken, $leaveRequest, array('view')), 'Vote: User can view leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if gm can edit lr $this->assertEquals(VoterInterface::ACCESS_DENIED, $leaveAccessVoter->vote($gmToken, $leaveRequest, array('edit')), 'Vote: General manager can edit leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if admin can edit lr $this->assertEquals(VoterInterface::ACCESS_DENIED, $leaveAccessVoter->vote($adminToken, $leaveRequest, array('edit')), 'Vote: Admin can edit leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if user can edit lr $this->assertEquals(VoterInterface::ACCESS_DENIED, $leaveAccessVoter->vote($userToken, $leaveRequest, array('edit')), 'Vote: User can edit leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if gm can delete lr $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($gmToken, $leaveRequest, array('delete')), 'Vote: General manager can not edit leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if admin can delete lr $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($adminToken, $leaveRequest, array('delete')), 'Vote: Admin can not edit leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if user can delete lr $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($userToken, $leaveRequest, array('delete')), 'Vote: User can edit leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if gm can change lr status $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($gmToken, $leaveRequest, array('status')), 'Vote: General manager can change status leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if admin can change lr status $this->assertEquals(VoterInterface::ACCESS_GRANTED, $leaveAccessVoter->vote($adminToken, $leaveRequest, array('status')), 'Vote: Admin can change status leave request ' . $leaveRequest->getLeaveRequestId() . '.'); // Check if user can change lr status $this->assertEquals(VoterInterface::ACCESS_DENIED, $leaveAccessVoter->vote($userToken, $leaveRequest, array('status')), 'Vote: User can change status leave request ' . $leaveRequest->getLeaveRequestId() . '.'); }
public function attemptAuthentication(Request $request) { if ($this->options['post_only'] && 'post' !== strtolower($request->getMethod())) { if (null !== $this->logger) { $this->logger->debug(sprintf('Authentication method not supported: %s.', $request->getMethod())); } return null; } if (null !== $this->csrfProvider) { $csrfToken = $request->get($this->options['csrf_parameter'], null, true); if (false === $this->csrfProvider->isCsrfTokenValid($this->options['intention'], $csrfToken)) { throw new InvalidCsrfTokenException('Invalid CSRF token.'); } } $username = trim($request->get($this->options['username_parameter'], null, true)); $password = $request->get($this->options['password_parameter'], null, true); $request->getSession()->set(SecurityContextInterface::LAST_USERNAME, $username); $token = new UsernamePasswordToken($username, $password, $this->providerKey); $this->logger->debug(sprintf('Attempting to authenticate user: %s.', $token->getUsername())); $this->logger->debug(sprintf('Requested path is: %s.', $request->getUri())); return $this->authenticationManager->authenticate($token); }