/** * Attempts to log the authenticated CAS user into Drupal. * * This method should be used to login a user after they have successfully * authenticated with the CAS server. * * @param CasPropertyBag $property_bag * CasPropertyBag containing username and attributes from CAS. * @param string $ticket * The service ticket. * * @throws CasLoginException * Thrown if there was a problem logging in the user. */ public function loginToDrupal(CasPropertyBag $property_bag, $ticket) { // Dispatch an event that allows modules to change user data we received // from CAS before attempting to use it to load a Drupal user. // Auto-registration can also be disabled for this user if their account // does not exist. $user_load_event = new CasUserLoadEvent($property_bag); $this->eventDispatcher->dispatch(CasHelper::EVENT_USER_LOAD, $user_load_event); $account = $this->userLoadByName($property_bag->getUsername()); if (!$account) { $config = $this->settings->get('cas.settings'); if ($config->get('user_accounts.auto_register') === TRUE) { if ($user_load_event->allowAutoRegister) { $account = $this->registerUser($property_bag->getUsername(), $config->get('user_accounts.auto_assigned_roles')); } else { throw new CasLoginException("Cannot register user, an event listener denied access."); } } else { throw new CasLoginException("Cannot login, local Drupal user account does not exist."); } } // Dispatch an event that allows modules to prevent this user from logging // in and/or alter the user entity before we save it. $pre_auth_event = new CasPreAuthEvent($account, $property_bag); $this->eventDispatcher->dispatch(CasHelper::EVENT_PRE_AUTH, $pre_auth_event); // Save user entity since event listeners may have altered it. $account->save(); if (!$pre_auth_event->allowLogin) { throw new CasLoginException("Cannot login, an event listener denied access."); } $this->userLoginFinalize($account); $this->storeLoginSessionData($this->session->getId(), $ticket); }
function it_logs_user_out(SessionInterface $session, CookieSetterInterface $cookieSetter) { $session->set('_security_shop', null)->shouldBeCalled(); $session->save()->shouldBeCalled(); $session->getName()->willReturn('MOCKEDSID'); $session->getId()->willReturn('xyzc123'); $cookieSetter->setCookie('MOCKEDSID', 'xyzc123')->shouldBeCalled(); $this->logOut(); }
/** * @param UserInterface $user */ private function logInUser(UserInterface $user) { $token = new UsernamePasswordToken($user, $user->getPassword(), 'randomstringbutnotnull', $user->getRoles()); $this->session->set($this->sessionTokenVariable, serialize($token)); $this->session->save(); $this->cookieSetter->setCookie($this->session->getName(), $this->session->getId()); }
/** * Checks if there is an authenticated back end user. * * @param Request $request * * @return bool */ private function hasAuthenticatedBackendUser(Request $request) { if (!$request->cookies->has('BE_USER_AUTH')) { return false; } $sessionHash = sha1(sprintf('%s%sBE_USER_AUTH', $this->session->getId(), $this->disableIpCheck ? '' : $request->getClientIp())); return $request->cookies->get('BE_USER_AUTH') === $sessionHash; }
protected function generateCookie() { $lifetime = $this->options->getInt('cookie_lifetime'); if ($lifetime !== 0) { $lifetime += time(); } return new Cookie($this->session->getName(), $this->session->getId(), $lifetime, $this->options['cookie_path'], $this->options['cookie_domain'] ?: null, $this->options->getBoolean('cookie_secure'), $this->options->getBoolean('cookie_httponly')); }
/** * Write the session cookie to the response. * * @param \Symfony\Component\HttpFoundation\Response $response * @return void */ protected function writeSessionTo(Response $response) { // TODO: Take these values from config $lifetime = Carbon::now()->addMinutes(120); $path = '/'; $domain = null; $secure = false; $response->headers->setCookie(new Cookie($this->session->getName(), $this->session->getId(), $lifetime, $path, $domain, $secure)); }
/** * {@inheritdoc} */ public function logIn($email, $providerKey, Session $minkSession) { $user = $this->userRepository->findOneBy(['username' => $email]); if (null === $user) { throw new \InvalidArgumentException(sprintf('There is no user with email %s', $email)); } $token = new UsernamePasswordToken($user, $user->getPassword(), $providerKey, $user->getRoles()); $this->session->set('_security_user', serialize($token)); $this->session->save(); $minkSession->setCookie($this->session->getName(), $this->session->getId()); }
public function getConfig() { $sessionInfo = ['isStarted' => false]; if ($this->session->isStarted()) { $sessionInfo['isStarted'] = true; $sessionInfo['name'] = $this->session->getName(); $sessionInfo['identifier'] = $this->session->getId(); $sessionInfo['csrfToken'] = $this->csrfTokenManager->getToken($this->csrfTokenIntention)->getValue(); $sessionInfo['href'] = $this->generateUrl('ezpublish_rest_deleteSession', ['sessionId' => $this->session->getId()]); } return $sessionInfo; }
/** * Adds session id to log record. * * @param array $record * * @return array */ public function processRecord(array $record) { if (null === $this->token) { try { $this->token = substr($this->session->getId(), 0, 8); } catch (\RuntimeException $e) { $this->token = '????????'; } $this->token = $this->hash($this->token); } $record['extra']['token'] = $this->token; return $record; }
/** * @return string */ public function getSessionId() { try { if ($this->startSession && !$this->session->isStarted()) { $this->session->start(); } if ($this->session->isStarted()) { return $this->session->getId(); } } catch (\RuntimeException $e) { } return self::SESSION_ID_UNKNOWN; }
/** * @param TokenInterface $token */ private function setToken(TokenInterface $token) { $serializedToken = serialize($token); $this->session->set($this->sessionTokenVariable, $serializedToken); $this->session->save(); $this->cookieSetter->setCookie($this->session->getName(), $this->session->getId()); }
/** * Generate Hash-Token from string * * @param string $value * @param string $secret * @return string */ public function getToken($value, $secret = null) { if ($secret === null) { $secret = $this->secret; } // Create real key for value $sessionId = $this->session->getId(); $realHash = sha1($value . $sessionId . $secret); return $realHash; }
protected function makeCookie(Request $request) { // merge native PHP session cookie params with custom ones. $params = array_replace(session_get_cookie_params(), $this->cookies); // if the cookie lifetime is not 0 (closes when browser window closes), // add the request time and the lifetime to get the expiration time of // the cookie. if ($params['lifetime'] !== 0) { $params['lifetime'] = $request->server->get('REQUEST_TIME') + $params['lifetime']; } return new Cookie($this->session->getName(), $this->session->getId(), $params['lifetime'], $params['path'], $params['domain'], $params['secure'], $params['httponly']); }
/** * {@inheritDoc} */ public function generate($key) { if (!is_string($key)) { throw new InvalidTypeException($key, 'string'); } if (empty($key)) { throw new \InvalidArgumentException('Argument must not be empty.'); } $token = $this->tokenStorage->getToken(); if ($token instanceof TokenInterface && !$token instanceof AnonymousToken) { $username = $token->getUsername(); if (!empty($username)) { return sprintf('user_%s_%s', $username, $key); } } // fallback to session id if (!$this->session->isStarted()) { $this->session->start(); } return sprintf('session_%s_%s', $this->session->getId(), $key); }
function it_logs_user_in(UserRepositoryInterface $userRepository, SessionInterface $session, CookieSetterInterface $cookieSetter, UserInterface $user) { $userRepository->findOneBy(['username' => '*****@*****.**'])->willReturn($user); $user->getRoles()->willReturn(['ROLE_USER']); $user->getPassword()->willReturn('xyz'); $user->serialize()->willReturn('serialized_user'); $session->set('_security_context_name', Argument::any())->shouldBeCalled(); $session->save()->shouldBeCalled(); $session->getName()->willReturn('MOCKEDSID'); $session->getId()->willReturn('xyzc123'); $cookieSetter->setCookie('MOCKEDSID', 'xyzc123')->shouldBeCalled(); $this->logIn('*****@*****.**'); }
/** * @param BaseUser $user * @param SessionInterface $session * @param $firewall * @throws UnsupportedDriverActionException */ public function login(BaseUser $user, SessionInterface $session, $firewall) { $driver = $this->getDriver(); if (!$driver instanceof BrowserKitDriver) { //Fall back to manual login if BrowserKitDriver is not used throw new UnsupportedDriverActionException("Not supported by the current driver", $driver); } $client = $driver->getClient(); $client->getCookieJar()->set(new Cookie(session_name(), true)); $token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles()); $session->set('_security_' . $firewall, serialize($token)); $session->save(); $cookie = new Cookie($session->getName(), $session->getId()); $client->getCookieJar()->set($cookie); }
/** * @param SessionInterface $session * @param Response $response */ private function postRequestHandle(SessionInterface $session, Response $response) { if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) { $id = $session->getId(); $key = 'session:' . $id; $content = $session->all(); unset($content['_token'], $content['flash']); $lastSeen = time(); $content['last_seen'] = $lastSeen; $session->set('last_seen', $lastSeen); $value = Json::dump($content); $this->redis->watch($key); $this->redis->multi(); $this->redis->set($key, $value); $this->redis->expire($key, $this->getSessionLifetimeInSeconds()); $this->redis->exec(); $cookie = new Cookie($this->key, $id, $this->getCookieExpirationDate(), $config['path'], $config['domain'], Arr::get($config, 'secure', false)); $response->headers->setCookie($cookie); } }
/** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $page = $builder->getData(); $builder->add('title', 'text', ['label' => 'Seitentitel'])->add('content', 'textarea', ['label' => 'Inhalt der Seite'])->add('isHomepage', 'checkbox', ['label' => 'Seite als Homepage verwenden', 'required' => false])->add('showInMenu', 'checkbox', ['label' => 'Seite im Menü anzeigen', 'required' => false])->add('sessionId', 'hidden', ['data' => $this->session->getId(), 'mapped' => false]); }
function it_returns_session_id(SessionInterface $session) { $session->isStarted()->willReturn(true); $session->getId()->shouldBeCalled()->willReturn('dfsdfgdg4sdfg4s5df4'); $this->getSessionId()->shouldBeString(); }
/** * @param SessionInterface $session */ public function __construct(SessionInterface $session) { $this->sessionId = $session->getId(); }
/** * @param string $token */ private function restorePreviousSessionToken($token) { $this->setSerializedToken($token); $this->cookieSetter->setCookie($this->session->getName(), $this->session->getId()); }
/** * Get the session ID * * @return string * @since 1.9 */ public function getId() { return $this->storage->getId(); }
/** * Creates a new Order Entity. * * @param array $data The data array, which will be used for setting the orders data * @param string $locale Locale * @param int $userId Id of the User, which is is saved as creator / changer * @param int|null $id If defined, the Order with the given ID will be updated * @param int|null $statusId if defined, the status will be set to the given value * @param bool $flush Defines if a flush should be performed * @param bool $patch * * @throws EntityNotFoundException * @throws MissingOrderAttributeException * @throws OrderDependencyNotFoundException * @throws OrderException * @throws OrderNotFoundException * * @return null|Order */ public function save(array $data, $locale, $userId = null, $id = null, $statusId = null, $flush = true, $patch = true) { $isNewOrder = !$id; if (!$isNewOrder) { $order = $this->findByIdAndLocale($id, $locale); if (!$order) { throw new OrderNotFoundException($id); } } else { $order = $this->orderFactory->createApiEntity($this->orderFactory->createEntity(), $locale); $this->checkRequiredData($data, $id === null); } $user = $userId ? $this->userRepository->findUserById($userId) : null; $order->setOrderNumber($this->getPropertyBasedOnPatch($data, 'orderNumber', $order->getOrderNumber(), $patch)); $order->setCurrencyCode($this->getPropertyBasedOnPatch($data, 'currencyCode', $order->getCurrencyCode(), $patch)); $order->setCostCentre($this->getPropertyBasedOnPatch($data, 'costCentre', $order->getCostCentre(), $patch)); $order->setCommission($this->getPropertyBasedOnPatch($data, 'commission', $order->getCommission(), $patch)); $order->setTaxfree($this->getPropertyBasedOnPatch($data, 'taxfree', $order->getTaxfree(), $patch)); $order->setNetShippingCosts($this->getPropertyBasedOnPatch($data, 'netShippingCosts', $order->getNetShippingCosts(), $patch)); $order->setInternalNote($this->getPropertyBasedOnPatch($data, 'internalNote', $order->getInternalNote(), $patch)); // Set type of order (if set). $this->setOrderType($data, $order, $patch); $this->setDate($data, 'desiredDeliveryDate', $order->getDesiredDeliveryDate(), array($order, 'setDesiredDeliveryDate')); $this->setDate($data, 'orderDate', $order->getOrderDate(), array($order, 'setOrderDate')); $this->setTermsOfDelivery($data, $order, $patch); $this->setTermsOfPayment($data, $order, $patch); $account = $this->setCustomerAccount($data, $order, $patch); // Set session - id. $sessionId = $this->session->getId(); $order->setSessionId($sessionId); // Add contact. $contact = $this->addContactRelation($data, 'customerContact', function ($contact) use($order) { $order->setCustomerContact($contact); }); // Add contact. $this->addContactRelation($data, 'responsibleContact', function ($contact) use($order) { $order->setResponsibleContact($contact); }); // Create order (POST). if ($order->getId() == null) { $order->setCreated(new DateTime()); $order->setCreator($user); $this->em->persist($order->getEntity()); // Set status to created if not defined. if ($statusId === null) { $statusId = OrderStatus::STATUS_CREATED; } // Create OrderAddress. $deliveryAddress = new OrderAddress(); $invoiceAddress = new OrderAddress(); // Persist entities. $this->em->persist($deliveryAddress); $this->em->persist($invoiceAddress); // Assign to order. $order->setDeliveryAddress($deliveryAddress); $order->setInvoiceAddress($invoiceAddress); } // Set order status. if ($statusId !== null) { $this->convertStatus($order, $statusId); } // If not new and contact is not set, use old contact. if (!$isNewOrder && !$contact) { $contact = $order->getEntity()->getCustomerContact(); } $contactFullName = null; if ($contact) { $contactFullName = $contact->getFullName(); } if (isset($data['invoiceAddress'])) { // Set customer name to account if set, otherwise to contact. $contactFullName = $this->orderAddressManager->getContactData($data['invoiceAddress'], $contact)['fullName']; // Set OrderAddress data. $this->orderAddressManager->setOrderAddress($order->getEntity()->getInvoiceAddress(), $data['invoiceAddress'], $contact, $account); } if (isset($data['deliveryAddress'])) { $this->orderAddressManager->setOrderAddress($order->getEntity()->getDeliveryAddress(), $data['deliveryAddress'], $contact, $account); } // Set customer name. $customerName = $account !== null ? $account->getName() : $contactFullName; if ($customerName) { $order->setCustomerName($customerName); } // Handle items. if (!$this->processItems($data, $order, $locale, $userId)) { throw new OrderException('Error while processing items'); } $order->setChanged(new DateTime()); $order->setChanger($user); $this->updateApiEntity($order, $locale); if ($flush) { $this->em->flush(); } return $order; }
public function __construct(SessionInterface $session) { $this->sessionId = $session->getId(); $this->csrfTokenManager = new CsrfTokenManager(new TokenGenerator($this->sessionId, CSRF_SALT), new SessionTokenStorage($session)); }
/** * @param SsoState $ssoState * * @return void */ public function set(SsoState $ssoState) { $ssoState->setLocalSessionId($this->session->getId()); $this->session->set($this->key, $ssoState); }
private function withSessionCookie(Response $response, SessionInterface $session) { return FigResponseCookies::set($response, SetCookie::create($session->getName(), $session->getId())->withPath('/')->withHttpOnly(true)); }
public function testGetId() { $this->assertEquals('', $this->session->getId()); $this->session->start(); $this->assertNotEquals('', $this->session->getId()); }
/** * Finds cart by session-id * * @return array */ private function findCartBySessionId() { $sessionId = $this->session->getId(); $cartsArray = $this->orderRepository->findBy(array('sessionId' => $sessionId, 'status' => OrderStatus::STATUS_IN_CART), array('created' => 'DESC')); return $cartsArray; }