本文整理汇总了PHP中Symfony\Component\HttpKernel\Event\GetResponseEvent::setResponse方法的典型用法代码示例。如果您正苦于以下问题:PHP GetResponseEvent::setResponse方法的具体用法?PHP GetResponseEvent::setResponse怎么用?PHP GetResponseEvent::setResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\HttpKernel\Event\GetResponseEvent
的用法示例。
在下文中一共展示了GetResponseEvent::setResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: onKernelRequestMaintenance
/**
* Determine whether the page is configured to be offline.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The event to process.
*/
public function onKernelRequestMaintenance(GetResponseEvent $event)
{
$request = $event->getRequest();
$route_match = RouteMatch::createFromRequest($request);
$path = $request->attributes->get('_system_path');
if ($this->maintenanceMode->applies($route_match)) {
// If the site is offline, log out unprivileged users.
if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
user_logout();
// Redirect to homepage.
$event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE])));
return;
}
}
if ($this->account->isAuthenticated()) {
if ($path == 'user/login') {
// If the user is already logged in, redirect to their profile page.
$event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()]));
return;
}
if ($path == 'user/register') {
// If the user is already registered, redirect to their edit page.
$event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE])));
return;
}
}
}
示例2: handle
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();
$token->setUser($wsseHeaderInfo['Username']);
$token->setAttribute('digest', $wsseHeaderInfo['PasswordDigest']);
$token->setAttribute('nonce', $wsseHeaderInfo['Nonce']);
$token->setAttribute('created', $wsseHeaderInfo['Created']);
try {
$returnValue = $this->authenticationManager->authenticate($token);
if ($returnValue instanceof TokenInterface) {
return $this->securityContext->setToken($returnValue);
} else {
if ($returnValue instanceof Response) {
return $event->setResponse($returnValue);
}
}
} catch (AuthenticationException $ae) {
$event->setResponse($this->authenticationEntryPoint->start($request, $ae));
}
}
}
示例3: onRequest
/**
* 请求完成后执行
*/
public function onRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$session = $request->getSession();
// 如果有 OpenID,则放行
if ($session->has('openid')) {
return;
}
// 排除资源文件
if (preg_match("^/(_(profiler|wdt)|css|images|js)/^", $request->getPathInfo())) {
return;
}
// 排除不需要 openid 的 URL
$currentRoute = $request->get('_route');
$currentParams = $request->get('_route_params');
if (in_array($currentRoute, $this->ignoreRoute)) {
return;
}
// 跳转到授权页,并把当前页作为参数(授权完成后还要跳转回来)
$currentUri = $this->router->generate($currentRoute, $currentParams);
$authorizeUrl = $this->router->generate('wechat_authorize', ['continue' => $currentUri]);
if (!$request->isXmlHttpRequest()) {
return $event->setResponse(new RedirectResponse($authorizeUrl));
}
$response = new JsonResponse(['failure' => '401 Unauthorized', 'redirect' => $authorizeUrl]);
return $event->setResponse($response);
}
示例4: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
try {
$response = $this->authenticationManager->authenticate(new WordpressToken());
if ($response->isAuthenticated()) {
$this->securityContext->setToken($response);
$session = $request->getSession();
$token_id = uniqid();
$session->set('token_id', $token_id);
$session->set($token_id, $response);
} elseif ($response->getRedirectUrl() != null) {
$url = $response->getRedirectUrl();
if (strpos('?', $url) !== false) {
$separator = '&';
} else {
$separator = '?';
}
$url .= $separator . 'redirect_to=' . urlencode($request->getUri());
$response = new RedirectResponse($url);
$event->setResponse($response);
} else {
$response = new Response();
$response->setStatusCode(403);
$event->setResponse($response);
}
} catch (AuthenticationException $e) {
$response = new Response();
$response->setStatusCode(403);
$event->setResponse($response);
}
}
示例5: onKernelRequest
public function onKernelRequest(GetResponseEvent $event)
{
if ($this->kernel->getEnvironment() != "dev") {
if (preg_match("/\\/api\\//", $event->getRequest()->getUri())) {
$requestUri = $event->getRequest()->getUri();
$requestMethod = $event->getRequest()->getMethod();
if ($requestMethod !== "GET") {
$token = $this->context->getToken();
if (isset($token)) {
$user = $token->getUser();
if (!isset($user) || "anon." === $user) {
if (!$event->getRequest()->query->has('api_key')) {
$event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
}
}
} else {
$event->setResponse(new Response(json_encode(array("code" => 401, "message" => "The request requires user authentication")), 401));
}
}
}
}
$request = $event->getRequest();
if (!count($request->request->all()) && in_array($request->getMethod(), array('POST', 'PUT', 'PATCH', 'DELETE'))) {
$contentType = $request->headers->get('Content-Type');
$format = null === $contentType ? $request->getRequestFormat() : $request->getFormat($contentType);
if (!$this->decoderProvider->supports($format)) {
return;
}
$decoder = $this->decoderProvider->getDecoder($format);
$data = $decoder->decode($request->getContent(), $format);
if (is_array($data)) {
$request->request = new ParameterBag($data);
}
}
}
示例6: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
//@todo
if ($request->headers->has('x-wsse')) {
$wsseRegex = '/UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
if (preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
$token = new LdapUserToken();
$token->setUser($matches[1]);
$token->setDigest($matches[2]);
$token->setNonce($matches[3]);
$token->setCreated($matches[4]);
try {
$returnValue = $this->authenticationManager->authenticate($token);
if ($returnValue instanceof TokenInterface) {
$this->securityContext->setToken($returnValue);
} elseif ($returnValue instanceof Response) {
$event->setResponse($returnValue);
}
return null;
} catch (AuthenticationException $e) {
// you might log something here
}
}
}
$response = new Response();
$response->setStatusCode(403);
$event->setResponse($response);
}
示例7: handle
/**
* This interface must be implemented by firewall listeners.
*
* @param GetResponseEvent $event
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$apiKey = $request->headers->get('Authorization', $request->query->get('api_key'));
if (!$apiKey) {
if (true === $this->forceApiKey) {
$response = new Response();
$response->setStatusCode(401);
$event->setResponse($response);
}
return;
}
$token = new ApiKeyUserToken();
$token->setApiKey($apiKey);
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
$token = $this->securityContext->getToken();
if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
$this->securityContext->setToken(null);
}
$message = $failed->getMessage();
}
if ($this->isJsonRequest($request)) {
$response = new JsonResponse(array('error' => $message));
} else {
$response = new Response();
$response->setContent($message);
}
$response->setStatusCode(401);
$event->setResponse($response);
}
示例8: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->query->has($this->options['signed_login_parameter'])) {
return;
}
try {
$token = $this->createToken($request);
$token = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($token);
} catch (AuthenticationException $e) {
$this->tokenStorage->setToken(null);
if ($this->failureHandler instanceof AuthenticationFailureHandlerInterface) {
$response = $this->failureHandler->onAuthenticationFailure($request, $e);
if ($response instanceof Response) {
$event->setResponse($response);
} elseif (null !== $response) {
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationFailure method must return null or a Response object', get_class($this->failureHandler)));
}
}
return;
}
if ($this->successHandler instanceof AuthenticationSuccessHandlerInterface) {
$response = $this->successHandler->onAuthenticationSuccess($request, $token);
if ($response instanceof Response) {
$event->setResponse($response);
} elseif (null !== $response) {
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationSuccess method must return null or a Response object', get_class($this->successHandler)));
}
}
}
示例9: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$wsseHeader = $request->headers->get(self::WSSE_HEADER, false);
if (!$wsseHeader || 1 !== preg_match(self::WSSE_REGEX, $wsseHeader, $matches)) {
$event->setResponse(new Response('', Response::HTTP_FORBIDDEN, array('WWW-Authenticate' => 'WSSE realm="webservice", profile="ApplicationToken"')));
return;
}
$token = new TelenorUserToken($this->providerKey, $matches[2], $matches[3], $matches[4]);
$token->setUser($matches[1]);
try {
$authenticatedToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authenticatedToken);
return;
} catch (NonceExpiredException $failed) {
$this->logger->debug("Nonce expired: " . $wsseHeader);
} catch (AuthenticationException $failed) {
$this->logger->debug("Authentication failed: " . $failed->getMessage());
}
$token = $this->securityContext->getToken();
if ($token instanceof TelenorUserToken) {
$this->securityContext->setToken(null);
}
$response = new Response("", Response::HTTP_UNAUTHORIZED, array(Headers::LOCATION => $this->router->generate('telenor.authentication.login')));
$event->setResponse($response);
}
示例10: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$wsseRegex = '/UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
return;
}
$user = $matches[1];
$token = new WsseToken();
$token->setUser($user);
$token->setAttribute('digest', $matches[2]);
$token->setAttribute('nonce', $matches[3]);
$token->setAttribute('created', $matches[4]);
try {
$returnValue = $this->authenticationManager->authenticate($token);
if ($returnValue instanceof TokenInterface) {
if (!$returnValue->getUser()->isActive()) {
throw new AuthenticationException("Your account is not activated yet, please check your email and confirm registration.\n" . "If you didn't receive your verification email, please <a href=\"#reconfirm/{$user}\">click here.</a>");
}
return $this->securityContext->setToken($returnValue);
} else {
if ($returnValue instanceof Response) {
$event->setResponse($returnValue);
return;
}
}
} catch (AuthenticationException $failed) {
$this->logger->error(sprintf("Authentication failed for user %s. Reason: %s", $token->getUser(), $failed->getMessage()));
$response = new Response($this->serializer->serialize(['message' => $failed->getMessage()], $request->getRequestFormat()), Codes::HTTP_UNAUTHORIZED);
$event->setResponse($response);
}
}
示例11: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$wsseRegex = '~UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([a-zA-Z0-9+/]+={0,2})", Created="([^"]+)"~';
if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
return;
}
$token = new WsseUserToken();
$token->setUser($matches[1]);
$token->digest = $matches[2];
$token->nonce = $matches[3];
$token->created = $matches[4];
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->tokenStorage->setToken($authToken);
return;
} catch (AuthenticationException $failed) {
$response = new Response();
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->setContent($failed->getMessage());
$event->setResponse($response);
}
// By default deny authorization
$response = new Response();
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->setContent("WSSE authentication failed");
$event->setResponse($response);
}
示例12: onKernelRequest
public function onKernelRequest(GetResponseEvent $event)
{
// Only operate on the master request
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
if (!$request->hasSession()) {
return;
}
$session = $request->getSession();
$session->start();
$session_data = $session->getMetadataBag();
// Expire sessions if unused for $idletimeout
$idle_timeout = $this->container->getParameter('tui_session.session_timeout');
if (time() - $session_data->getLastUsed() > $idle_timeout) {
$session->invalidate();
// Return custom response if provided
$expiry_response = $this->container->getParameter('tui_session.expired_response');
if ($expiry_response) {
$event->setResponse($this->container->get($expiry_response));
return;
}
// Redirect to route name if provided
$path = $this->container->getParameter('tui_session.redirect_to');
if ($path) {
$url = $this->container->get('router')->generate($path);
$response = new RedirectResponse($url);
$event->setResponse($response);
return;
}
throw new CredentialsExpiredException();
}
}
示例13: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$currentRoute = $request->attributes->get('_route');
if (!$this->session->has('LDAP_LOGIN_CALLBACK')) {
if (in_array($currentRoute, $this->allowedRoutes)) {
$this->session->set('LDAP_LOGIN_CALLBACK', $this->kernel->getParameter('rheck_ldap_firewall.default_url'));
} else {
$this->session->set('LDAP_LOGIN_CALLBACK', $currentRoute);
}
}
if (in_array($currentRoute, $this->allowedRoutes)) {
return;
}
if (!$this->session->has('LDAP_LOGIN')) {
$loginUrl = $this->router->generate($this->kernel->getParameter('rheck_ldap_firewall.login_url'));
$event->setResponse(RedirectResponse::create($loginUrl));
return;
}
$ldapUserCredentials = $this->session->get('LDAP_LOGIN');
$token = new LDAPToken();
$token->setUser('ldap_proxy_user');
$token->setLDAPUserCredentials($ldapUserCredentials);
try {
$authToken = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($authToken);
} catch (AuthenticationException $failed) {
$this->session->set('LDAP_LOGIN_ERROR', 'Some error was occurred! Can\'t connect to LDAP.');
$event->setResponse(RedirectResponse::create($this->router->generate('_rheck_ldap_login')));
} catch (\Exception $e) {
$this->session->set('LDAP_LOGIN_ERROR', 'Invalid credentials.');
$event->setResponse(RedirectResponse::create($this->router->generate('_rheck_ldap_login')));
}
}
示例14: purlCheckNodeContext
/**
* Checks if a node's type requires a redirect.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The event to process.
*/
public function purlCheckNodeContext(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher_interface)
{
$route_options = $this->routeMatch->getRouteObject()->getOptions();
$isAdminRoute = array_key_exists('_admin_route', $route_options) && $route_options['_admin_route'];
if (!$isAdminRoute && ($matched = $this->matchedModifiers->getMatched() && ($entity = $this->routeMatch->getParameter('node')))) {
$node_type = $this->entityStorage->load($entity->bundle());
$purl_settings = $node_type->getThirdPartySettings('purl');
if (!isset($purl_settings['keep_context']) || !$purl_settings['keep_context']) {
$url = \Drupal\Core\Url::fromRoute($this->routeMatch->getRouteName(), $this->routeMatch->getRawParameters()->all(), ['host' => Settings::get('purl_base_domain'), 'absolute' => TRUE]);
try {
$redirect_response = new TrustedRedirectResponse($url->toString());
$redirect_response->getCacheableMetadata()->setCacheMaxAge(0);
$modifiers = $event->getRequest()->attributes->get('purl.matched_modifiers', []);
$new_event = new ExitedContextEvent($event->getRequest(), $redirect_response, $this->routeMatch, $modifiers);
$dispatcher_interface->dispatch(PurlEvents::EXITED_CONTEXT, $new_event);
$event->setResponse($new_event->getResponse());
return;
} catch (RedirectLoopException $e) {
\Drupal::logger('redirect')->warning($e->getMessage());
$response = new Response();
$response->setStatusCode(503);
$response->setContent('Service unavailable');
$event->setResponse($response);
return;
}
}
}
}
示例15: handle
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if ($request->headers->has('x-wsse')) {
$wsseRegex = '/UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
if (preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
$token = new WsseToken();
$token->setUser($matches[1]);
$token->digest = $matches[2];
$token->nonce = $matches[3];
$token->created = $matches[4];
try {
$returnValue = $this->authenticationManager->authenticate($token);
if ($returnValue instanceof TokenInterface) {
return $this->securityContext->setToken($returnValue);
} else {
if ($returnValue instanceof Response) {
return $event->setResponse($returnValue);
}
}
} catch (AuthenticationException $authException) {
$response = new Response();
$response->setStatusCode(401, $authException ? $authException->getMessage() : null);
$event->setResponse($response);
return;
}
}
}
$response = new Response();
$response->setStatusCode(403);
$event->setResponse($response);
}