/** * {@inheritdoc} */ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { // always set the session onto the request object. $request->setSession($this->session); // we only need to manage the session for the master request. // subrequests will have the session available anyways, but we will // be closing and setting the cookie for the master request only. if ($type !== HttpKernelInterface::MASTER_REQUEST) { return $this->kernel->handle($request, $type, $catch); } // the session may have been manually started before the middleware is // invoked - in this case, we cross our fingers and hope the session has // properly initialised itself if (!$this->session->isStarted()) { $this->initSession($request); } $response = $this->kernel->handle($request, $type, $catch); // if the session has started, save it and attach the session cookie. if // the session has not started, there is nothing to save and there is no // point in attaching a cookie to persist it. if ($this->session->isStarted()) { $this->closeSession($request, $response); } return $response; }
/** * {@inheritdoc} */ public function getData($key, $default = null) { if (!$this->session->isStarted()) { return $default; } return $this->session->get($key, $default); }
/** * @return string */ public function getHost() { if ($this->session->isStarted() && $this->session->has(self::OVERRIDE_HOST)) { return $this->session->get(self::OVERRIDE_HOST); } return parent::getHost(); }
/** * Add the session cookie to the response if it is started. * * @param FilterResponseEvent $event */ public function onResponse(FilterResponseEvent $event) { if (!$event->isMasterRequest() || !$this->session->isStarted()) { return; } $this->session->save(); $cookie = $this->generateCookie(); $event->getResponse()->headers->setCookie($cookie); }
public function onSiteAccessMatch(PostSiteAccessMatchEvent $event) { if (!($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST && isset($this->session) && !$this->session->isStarted() && $this->sessionStorage instanceof NativeSessionStorage)) { return; } $sessionOptions = (array) $this->configResolver->getParameter('session'); $sessionName = isset($sessionOptions['name']) ? $sessionOptions['name'] : $this->session->getName(); $sessionOptions['name'] = $this->getSessionName($sessionName, $event->getSiteAccess()); $this->sessionStorage->setOptions($sessionOptions); }
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; }
public function onSiteAccessMatch(PostSiteAccessMatchEvent $event) { if (!$this->session || $event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) { return; } $sessionName = $this->session->getName(); $request = $event->getRequest(); if (!$this->session->isStarted() && !$request->hasPreviousSession() && $request->request->has($sessionName)) { $this->session->setId($request->request->get($sessionName)); $this->session->start(); } }
/** * Handle errors thrown in the application. * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $hasUser = $this->session->isStarted() && $this->session->has('authentication'); if (!$hasUser && !$this->showWhileLoggedOff) { return; } $exception = $event->getException(); ob_start(); $this->whoops->handleException($exception); $response = ob_get_clean(); $code = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR; $event->setResponse(new Response($response, $code)); }
/** * @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; }
/** * Handle errors thrown in the application. * * Note: * - We don't want to show Whoops! screens for requests that trigger a 404. * - Our priority is set just above Symfony's, as we are giving up and * displaying the error to the user, so that should be a low priority * compared to error handlers that do something else. * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { // We (generally) do not want to show Whoops! screens when the user isn't logged on. $hasUser = $this->session->isStarted() && $this->session->has('authentication'); if (!$hasUser && !$this->showWhileLoggedOff) { return; } // Register Whoops as an error handler $this->whoops->register(); $exception = $event->getException(); ob_start(); $this->whoops->handleException($exception); $response = ob_get_clean(); $code = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR; $event->setResponse(new Response($response, $code)); }
/** * We will not allow tampering with sessions, so we make sure the current * session is still valid for the device on which it was created, and that * the username, and IP address, are still the same. * * 1. If user has a valid session and it is fresh, check against cookie: * - If NOT a match refuse * - If a match accept * 2. If user has a valid session and it is stale (>10 minutes), check the * database records again: * - If disabled refuse * - If enabled * - If NOT a match refuse * - If a match accept * - Update session data * 3. If user has no session check authtoken table entry (closed broswer): * - If passed validity date refuse * - If within validity date, hash username and IP against salt and * compare to database: * - If NOT a match refuse * - If a match accept * * @param string $authCookie * * @throws AccessControlException * * @return boolean */ public function isValidSession($authCookie) { if ($authCookie === null) { throw new AccessControlException('Can not validate session with an empty token.'); } if ($this->validSession !== null) { return $this->validSession; } $check = false; $sessionAuth = null; /** @var \Bolt\AccessControl\Token\Token $sessionAuth */ if ($this->session->isStarted() && ($sessionAuth = $this->session->get('authentication'))) { $check = $this->checkSessionStored($sessionAuth); } if (!$check) { // Either the session keys don't match, or the session is too old $check = $this->checkSessionDatabase($authCookie); } if ($check) { return $this->validSession = true; } $this->validSession = false; $this->systemLogger->debug("Clearing sessions for expired or invalid token: {$authCookie}", ['event' => 'authentication']); return $this->revokeSession(); }
/** * {@inheritdoc} */ public function removeToken($tokenId) { if (!$this->session->isStarted()) { $this->session->start(); } return $this->session->remove($this->namespace . '/' . $tokenId); }
/** * Initializes session access for $_SESSION['FE_DATA'] and $_SESSION['BE_DATA']. */ private function initializeLegacySessionAccess() { if (!$this->session->isStarted()) { return; } $_SESSION['BE_DATA'] = $this->session->getBag('contao_backend'); $_SESSION['FE_DATA'] = $this->session->getBag('contao_frontend'); }
/** * Get the exception trace that is safe to display publicly * * @param Exception $exception * * @return array */ protected function getSafeTrace(Exception $exception) { if (!$this->isDebug && !($this->session->isStarted() && $this->session->has('authentication'))) { return []; } $trace = $exception->getTrace(); foreach ($trace as $key => $value) { if (!empty($value['file']) && strpos($value['file'], '/vendor/') > 0) { unset($trace[$key]['args']); } // Don't display the full path. if (isset($trace[$key]['file'])) { $trace[$key]['file'] = str_replace($this->rootPath, '[root]/', $trace[$key]['file']); } } return $trace; }
public function __construct(SessionInterface $session) { if ($session->isStarted()) { $this->session = $session; } else { $sessionClass = get_class($session); $this->session = new $sessionClass(new PhpBridgeSessionStorage()); } }
/** * Adds the session settings to the parameters that will be injected * into the legacy kernel * * @param \eZ\Publish\Core\MVC\Legacy\Event\PreBuildKernelEvent $event */ public function onBuildKernelHandler(PreBuildKernelEvent $event) { $sessionInfos = array('configured' => false, 'started' => false, 'name' => false, 'namespace' => false, 'has_previous' => false, 'storage' => false); if (isset($this->session)) { $sessionInfos['configured'] = true; $sessionInfos['name'] = $this->session->getName(); $sessionInfos['started'] = $this->session->isStarted(); $sessionInfos['namespace'] = $this->sessionStorageKey; $sessionInfos['has_previous'] = isset($this->request) ? $this->request->hasPreviousSession() : false; $sessionInfos['storage'] = $this->sessionStorage; } $legacyKernelParameters = $event->getParameters(); $legacyKernelParameters->set('session', $sessionInfos); // Deactivate session cookie settings in legacy kernel. // This will force using settings defined in Symfony. $sessionSettings = array('site.ini/Session/CookieTimeout' => false, 'site.ini/Session/CookiePath' => false, 'site.ini/Session/CookieDomain' => false, 'site.ini/Session/CookieSecure' => false, 'site.ini/Session/CookieHttponly' => false); $legacyKernelParameters->set("injected-settings", $sessionSettings + (array) $legacyKernelParameters->get("injected-settings")); }
/** * {@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); }
/** * Initialize file list for current user, either from session or database. */ private function initialize() { if ($this->initialized) { return; } if ($this->session->isStarted() && $this->session->get('stack') !== null) { $paths = $this->session->get('stack'); $this->files = $this->hydrateList($paths); } else { $paths = $this->users->getCurrentUser()['stack']; $this->files = $this->hydrateList($paths); $this->session->set('stack', $this->persistableList()); } $this->initialized = true; }
/** * We will not allow tampering with sessions, so we make sure the current * session is still valid for the device on which it was created, and that * the username, and IP address, are still the same. * * 1. If user has a valid session and it is fresh, check against cookie: * - If NOT a match refuse * - If a match accept * 2. If user has a valid session and it is stale (>10 minutes), check the * database records again: * - If disabled refuse * - If enabled * - If NOT a match refuse * - If a match accept * - Update session data * 3. If user has no session check authtoken table entry (closed broswer): * - If passed validity date refuse * - If within validity date, hash username and IP against salt and * compare to database: * - If NOT a match refuse * - If a match accept * * @param string $authCookie * * @return boolean */ public function isValidSession($authCookie) { if ($this->validsession !== null) { return $this->validsession; } $check = false; $sessionAuth = null; /** @var \Bolt\AccessControl\Token\Token $sessionAuth */ if ($this->session->isStarted() && ($sessionAuth = $this->session->get('authentication'))) { $check = $this->checkSessionStored($sessionAuth); } if (!$check) { // Eithter the session keys don't match, or the session is too old $check = $this->checkSessionDatabase($authCookie); } if ($check) { return $this->validsession = true; } $this->validsession = false; return $this->revokeSession(); }
/** * Has the session been started * * @return boolean * @since 1.9 */ public function isStarted() { return $this->storage->isStarted(); }
function it_returns_session_id(SessionInterface $session) { $session->isStarted()->willReturn(true); $session->getId()->shouldBeCalled()->willReturn('dfsdfgdg4sdfg4s5df4'); $this->getSessionId()->shouldBeString(); }
/** * Check if session flag is set and is not complete. * * @param string $provider * @param TokenInterface $token * * @return bool */ public function isNotAuthenticated($provider, $token) { $sessionFlag = $this->getSessionFlag($provider, $token); return $this->session->isStarted() && $this->session->has($sessionFlag) && !$this->session->get($sessionFlag); }
public function testIsStarted() { $this->assertFalse($this->session->isStarted()); $this->session->start(); $this->assertTrue($this->session->isStarted()); }
/** * Load the redirects stored in the session. */ public function loadRedirects() { if ($this->session->isStarted()) { $this->redirectStack = $this->session->get(self::REDIRECT_STACK, [new Redirect('/')]); } }