*/ class CsrfToken extends tao_helpers_form_elements_xhtml_Hidden { use LoggerAwareTrait; /** * @inheritdoc */ public function render() { /** @var TokenService $tokenService */ $tokenService = ServiceManager::getServiceManager()->get(TokenService::SERVICE_ID); $formToken = $tokenService->getFormToken(); $this->setValue($formToken->getValue()); return parent::render(); } /** * @inheritdoc */ public function validate() { $csrfToken = $this->getEvaluatedValue(); if (!$csrfToken) { $this->logCsrfFailure('No CSRF token provided in form'); return false; } /** @var TokenService $tokenService */ $tokenService = ServiceManager::getServiceManager()->get(TokenService::SERVICE_ID); if (!$tokenService->checkFormToken($csrfToken)) { $this->logCsrfFailure('Invalid token received', $csrfToken); return false; } $tokenService->revokeToken($csrfToken); try { $tokenService->addFormToken(); } catch (\common_Exception $e) { return false; } return parent::validate(); } /** * Log a failed CSRF validation attempt * * @param string $exceptionMessage * @param string|null $csrfToken * @throws \common_exception_Error */ private function logCsrfFailure($exceptionMessage, $csrfToken = null) { $userIdentifier = common_session_SessionManager::getSession()->getUser()->getIdentifier(); $this->logWarning( '[CSRF] - Failed to validate CSRF token. The following exception occurred: ' . $exceptionMessage ); $this->logWarning( "[CSRF] \n" . "CSRF validation information: \n" . 'Provided token: ' . ($csrfToken ?: 'none') . " \n" . 'User identifier: ' . $userIdentifier . " \n" . 'Form: ' . $this->name ); } }