Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CsrfValidator.php
Go to the documentation of this file.
1 <?php
7 declare(strict_types=1);
8 
10 
16 use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
18 use Magento\Framework\App\Request\Http as HttpRequest;
21 
26 {
30  private $formKeyValidator;
31 
35  private $redirectFactory;
36 
40  private $appState;
41 
47  public function __construct(
48  FormKeyValidator $formKeyValidator,
49  RedirectFactory $redirectFactory,
50  AppState $appState
51  ) {
52  $this->formKeyValidator = $formKeyValidator;
53  $this->redirectFactory = $redirectFactory;
54  $this->appState = $appState;
55  }
56 
63  private function validateRequest(
64  HttpRequest $request,
65  ActionInterface $action
66  ): bool {
67  $valid = null;
68  if ($action instanceof CsrfAwareActionInterface) {
69  $valid = $action->validateForCsrf($request);
70  }
71  if ($valid === null) {
72  $valid = !$request->isPost()
73  || $request->isAjax()
74  || $this->formKeyValidator->validate($request);
75  }
76 
77  return $valid;
78  }
79 
86  private function createException(
87  HttpRequest $request,
88  ActionInterface $action
89  ): InvalidRequestException {
90  $exception = null;
91  if ($action instanceof CsrfAwareActionInterface) {
92  $exception = $action->createCsrfValidationException($request);
93  }
94  if (!$exception) {
95  $response = $this->redirectFactory->create()
96  ->setRefererOrBaseUrl()
97  ->setHttpResponseCode(302);
98  $messages = [
99  new Phrase('Invalid Form Key. Please refresh the page.'),
100  ];
101  $exception = new InvalidRequestException($response, $messages);
102  }
103 
104  return $exception;
105  }
106 
110  public function validate(
112  ActionInterface $action
113  ): void {
114  try {
115  $areaCode = $this->appState->getAreaCode();
116  } catch (LocalizedException $exception) {
117  $areaCode = null;
118  }
119  if ($request instanceof HttpRequest
120  && in_array(
121  $areaCode,
123  true
124  )
125  ) {
126  $valid = $this->validateRequest($request, $action);
127  if (!$valid) {
128  throw $this->createException($request, $action);
129  }
130  }
131  }
132 }
$response
Definition: 404.php:11
__construct(FormKeyValidator $formKeyValidator, RedirectFactory $redirectFactory, AppState $appState)
validate(RequestInterface $request, ActionInterface $action)