Lines
92.95%
277 / 298
Methods
67.85%
19 / 28
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| updateData | 100.00% | 52 / 52 | 100.00% | 1 / 1 | 22 | ||
| exportUserData | 88.88% | 32 / 36 | 0.00% | 0 / 1 | 8.09 | ||
| requestUserRemoval | 93.75% | 45 / 48 | 0.00% | 0 / 1 | 16.06 | ||
| removeTwofactorConfig | 100.00% | 17 / 17 | 100.00% | 1 / 1 | 6 | ||
| [phpMyFAQ\Controller\AbstractController] setContainer | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 1 | ||
| [phpMyFAQ\Controller\AbstractController] initializeFromContainer | 78.57% | 11 / 14 | 0.00% | 0 / 1 | 4.16 | ||
| [phpMyFAQ\Controller\AbstractController] render | 100.00% | 5 / 5 | 100.00% | 1 / 1 | 1 | ||
| [phpMyFAQ\Controller\AbstractController] renderView | 0.00% | 0 / 3 | 0.00% | 0 / 1 | 2 | ||
| [phpMyFAQ\Controller\AbstractController] json | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| [phpMyFAQ\Controller\AbstractController] getJsonObject | 75.00% | 3 / 4 | 0.00% | 0 / 1 | 2.06 | ||
| [phpMyFAQ\Controller\AbstractController] getTwigWrapper | 100.00% | 10 / 10 | 100.00% | 1 / 1 | 3 | ||
| [phpMyFAQ\Controller\AbstractController] hasValidToken | 85.71% | 6 / 7 | 0.00% | 0 / 1 | 5.07 | ||
| [phpMyFAQ\Controller\AbstractController] isSecured | 100.00% | 10 / 10 | 100.00% | 1 / 1 | 5 | ||
| [phpMyFAQ\Controller\AbstractController] isPublicAuthenticationPath | 100.00% | 23 / 23 | 100.00% | 1 / 1 | 1 | ||
| [phpMyFAQ\Controller\AbstractController] userIsAuthenticated | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 2 | ||
| [phpMyFAQ\Controller\AbstractController] userIsSuperAdmin | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 2 | ||
| [phpMyFAQ\Controller\AbstractController] userHasGroupPermission | 100.00% | 8 / 8 | 100.00% | 1 / 1 | 6 | ||
| [phpMyFAQ\Controller\AbstractController] userHasUserPermission | 100.00% | 7 / 7 | 100.00% | 1 / 1 | 5 | ||
| [phpMyFAQ\Controller\AbstractController] userHasPermission | 100.00% | 5 / 5 | 100.00% | 1 / 1 | 3 | ||
| [phpMyFAQ\Controller\AbstractController] userHasAnyPermission | 100.00% | 10 / 10 | 100.00% | 1 / 1 | 4 | ||
| [phpMyFAQ\Controller\AbstractController] verifySessionCsrfToken | 70.00% | 7 / 10 | 0.00% | 0 / 1 | 4.43 | ||
| [phpMyFAQ\Controller\AbstractController] captchaCodeIsValid | 85.71% | 6 / 7 | 0.00% | 0 / 1 | 2.01 | ||
| [phpMyFAQ\Controller\AbstractController] isApiEnabled | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| [phpMyFAQ\Controller\AbstractController] addExtension | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| [phpMyFAQ\Controller\AbstractController] addFilter | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| [phpMyFAQ\Controller\AbstractController] getRateLimiter | 100.00% | 4 / 4 | 100.00% | 1 / 1 | 3 | ||
| [phpMyFAQ\Controller\AbstractController] createFallbackContainer | 71.42% | 5 / 7 | 0.00% | 0 / 1 | 2.09 | ||
| 40 | final class UserController extends AbstractController | |
| 41 | { | |
| 42 | public function __construct( | |
| 43 | private readonly StopWords $stopWords, | |
| 44 | private readonly Mail $mailer, | |
| 45 | ) { | |
| 46 | parent::__construct(); | |
| 47 | } | |
| 48 | ||
| 49 | /** | |
| 50 | * @throws \Exception | |
| 51 | */ | |
| 52 | #[Route(path: 'user/data/update', name: 'api.private.user.update', methods: ['PUT'])] | |
| 53 | public function updateData(Request $request): JsonResponse | |
| 54 | { | |
| 55 | $this->userIsAuthenticated(); | |
| 56 | ||
| 57 | $data = $this->getJsonObject($request); | |
| 58 | ||
| 59 | $csrfToken = Filter::filterVar($data->{'pmf-csrf-token'} ?? null, FILTER_SANITIZE_SPECIAL_CHARS); | |
| 60 | ||
| 61 | if (!Token::getInstance($this->session)->verifyToken('ucp', $csrfToken)) { | |
| 62 | return $this->json(['error' => Translation::get(key: 'ad_msg_noauth')], Response::HTTP_UNAUTHORIZED); | |
| 63 | } | |
| 64 | ||
| 65 | $userId = Filter::filterVar($data->userid ?? null, FILTER_VALIDATE_INT); | |
| 66 | $userName = trim(strip_tags((string) ($data->name ?? ''))); | |
| 67 | $email = Filter::filterEmail($data->email ?? null); | |
| 68 | $isVisible = Filter::filterVar($data->{'is_visible'} ?? null, FILTER_SANITIZE_SPECIAL_CHARS); | |
| 69 | $password = trim((string) Filter::filterVar($data->faqpassword ?? null, FILTER_SANITIZE_SPECIAL_CHARS)); | |
| 70 | $confirm = trim((string) Filter::filterVar($data->faqpassword_confirm ?? null, FILTER_SANITIZE_SPECIAL_CHARS)); | |
| 71 | $twoFactorEnabled = Filter::filterVar($data->twofactor_enabled ?? 'off', FILTER_SANITIZE_SPECIAL_CHARS); | |
| 72 | $secret = Filter::filterVar($data->secret ?? '', FILTER_SANITIZE_SPECIAL_CHARS, ''); | |
| 73 | ||
| 74 | $isAzureAdUser = $this->currentUser->getUserAuthSource() === 'azure'; | |
| 75 | $isWebAuthnUser = $this->currentUser->getUserAuthSource() === 'webauthn'; | |
| 76 | ||
| 77 | if ($userId !== $this->currentUser->getUserId()) { | |
| 78 | return $this->json(['error' => 'User ID mismatch!'], Response::HTTP_BAD_REQUEST); | |
| 79 | } | |
| 80 | ||
| 81 | $success = false; | |
| 82 | if (!$isAzureAdUser) { | |
| 83 | // The password is only changed when the user actually entered one; | |
| 84 | // leaving both fields blank keeps the current password. | |
| 85 | $changePassword = $password !== '' || $confirm !== ''; | |
| 86 | ||
| 87 | if ($changePassword) { | |
| 88 | if (!hash_equals($password, $confirm)) { | |
| 89 | return $this->json([ | |
| 90 | 'error' => Translation::get('ad_user_error_passwordsDontMatch'), | |
| 91 | ], Response::HTTP_CONFLICT); | |
| 92 | } | |
| 93 | ||
| 94 | if ((strlen($password) <= 7 || strlen($confirm) <= 7) && !$isWebAuthnUser) { | |
| 95 | return $this->json(['error' => Translation::get(key: 'ad_passwd_fail')], Response::HTTP_CONFLICT); | |
| 96 | } | |
| 97 | } | |
| 98 | ||
| 99 | $userData = [ | |
| 100 | 'display_name' => $userName, | |
| 101 | 'is_visible' => $isVisible === 'on' ? 1 : 0, | |
| 102 | ]; | |
| 103 | if (!$isWebAuthnUser) { | |
| 104 | $userData['email'] = is_string($email) ? $email : ''; | |
| 105 | $userData['twofactor_enabled'] = $twoFactorEnabled === 'on' ? 1 : 0; | |
| 106 | } | |
| 107 | ||
| 108 | $success = $this->currentUser->setUserData($userData); | |
| 109 | ||
| 110 | if ($changePassword) { | |
| 111 | foreach ($this->currentUser->getAuthContainer() as $authDriver) { | |
| 112 | if ($authDriver->disableReadOnly()) { | |
| 113 | continue; | |
| 114 | } | |
| 115 | ||
| 116 | if (!$authDriver->update($this->currentUser->getLogin(), $password)) { | |
| 117 | return $this->json(['error' => $authDriver->getErrors()], Response::HTTP_BAD_REQUEST); | |
| 118 | } | |
| 119 | ||
| 120 | $success = true; | |
| 121 | } | |
| 122 | } | |
| 123 | } | |
| 124 | ||
| 125 | if ($isAzureAdUser) { | |
| 126 | $userData = [ | |
| 127 | 'is_visible' => $isVisible === 'on' ? 1 : 0, | |
| 128 | 'twofactor_enabled' => $twoFactorEnabled === 'on' ? 1 : 0, | |
| 129 | 'secret' => $secret, | |
| 130 | ]; | |
| 131 | ||
| 132 | $success = $this->currentUser->setUserData($userData); | |
| 133 | } | |
| 134 | ||
| 135 | if ($success) { | |
| 136 | return $this->json(['success' => Translation::get(key: 'ad_entry_savedsuc')], Response::HTTP_OK); | |
| 137 | } | |
| 138 | ||
| 139 | return $this->json(['error' => Translation::get(key: 'ad_entry_savedfail')], Response::HTTP_BAD_REQUEST); | |
| 140 | } | |
| 141 | ||
| 142 | /** | |
| 143 | * Export userdata of the currently logged-in user as a ZIP file. | |
| 144 | * | |
| 145 | * @throws \Exception | |
| 146 | */ | |
| 147 | #[Route(path: 'user/data/export', name: 'api.private.user.data.export', methods: ['POST'])] | |
| 148 | public function exportUserData(Request $request): Response | |
| 149 | { | |
| 150 | $this->userIsAuthenticated(); | |
| 151 | ||
| 152 | $inputBag = $request->getPayload(); | |
| 153 | ||
| 154 | $csrfToken = Filter::filterVar($inputBag->get('pmf-csrf-token'), FILTER_SANITIZE_SPECIAL_CHARS); | |
| 155 | $userIdInput = Filter::filterVar($inputBag->get('userid') ?? null, FILTER_VALIDATE_INT); | |
| 156 | ||
| 157 | if (!Token::getInstance($this->session)->verifyToken('export-userdata', $csrfToken)) { | |
| 158 | return $this->json(['error' => Translation::get(key: 'ad_msg_noauth')], Response::HTTP_UNAUTHORIZED); | |
| 159 | } | |
| 160 | ||
| 161 | if (null !== $userIdInput && $userIdInput !== $this->currentUser->getUserId()) { | |
| 162 | return $this->json(['error' => 'User ID mismatch!'], Response::HTTP_BAD_REQUEST); | |
| 163 | } | |
| 164 | ||
| 165 | if (!class_exists(ZipArchive::class)) { | |
| 166 | return $this->json(['error' => 'ZIP extension not available.'], Response::HTTP_INTERNAL_SERVER_ERROR); | |
| 167 | } | |
| 168 | ||
| 169 | $userData = [ | |
| 170 | 'user_id' => $this->currentUser->getUserId(), | |
| 171 | 'last_modified' => (string) ($this->currentUser->getUserData('last_modified') ?? ''), | |
| 172 | 'display_name' => (string) ($this->currentUser->getUserData('display_name') ?? ''), | |
| 173 | 'email' => (string) ($this->currentUser->getUserData('email') ?? ''), | |
| 174 | 'is_visible' => (int) ($this->currentUser->getUserData('is_visible') ?? 0), | |
| 175 | 'twofactor_enabled' => (int) ($this->currentUser->getUserData('twofactor_enabled') ?? 0), | |
| 176 | 'secret' => (string) ($this->currentUser->getUserData('secret') ?? ''), | |
| 177 | ]; | |
| 178 | ||
| 179 | $json = json_encode($userData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); | |
| 180 | if ($json === false) { | |
| 181 | return $this->json(['error' => 'Failed to encode userdata.'], Response::HTTP_INTERNAL_SERVER_ERROR); | |
| 182 | } | |
| 183 | ||
| 184 | // Create a temporary ZIP file | |
| 185 | $tmpFile = tempnam(directory: sys_get_temp_dir(), prefix: 'pmf_userdata_'); | |
| 186 | if ($tmpFile === false) { | |
| 187 | return $this->json(['error' => 'Failed to create temp file.'], Response::HTTP_INTERNAL_SERVER_ERROR); | |
| 188 | } | |
| 189 | ||
| 190 | $zipArchive = new ZipArchive(); | |
| 191 | if ($zipArchive->open($tmpFile, ZipArchive::OVERWRITE) !== true) { | |
| 192 | return $this->json(['error' => 'Failed to create ZIP archive.'], Response::HTTP_INTERNAL_SERVER_ERROR); | |
| 193 | } | |
| 194 | ||
| 195 | $zipArchive->addFromString('userdata.json', $json); | |
| 196 | $zipArchive->close(); | |
| 197 | ||
| 198 | $fileName = sprintf('phpmyfaq-userdata-%d-%s.zip', $this->currentUser->getUserId(), date(format: 'YmdHis')); | |
| 199 | ||
| 200 | $binaryFileResponse = new BinaryFileResponse($tmpFile); | |
| 201 | $binaryFileResponse->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $fileName); | |
| 202 | $binaryFileResponse->headers->set('Content-Type', 'application/zip'); | |
| 203 | $binaryFileResponse->deleteFileAfterSend(); | |
| 204 | ||
| 205 | return $binaryFileResponse; | |
| 206 | } | |
| 207 | ||
| 208 | /** | |
| 209 | * @throws Exception|\Exception | |
| 210 | */ | |
| 211 | #[Route(path: 'user/request-removal', name: 'api.private.user.request-removal', methods: ['POST'])] | |
| 212 | public function requestUserRemoval(Request $request): JsonResponse | |
| 213 | { | |
| 214 | $data = $this->getJsonObject($request); | |
| 215 | ||
| 216 | if (($data->{'pmf-csrf-token'} ?? null) === null) { | |
| 217 | throw new Exception('Missing CSRF token'); | |
| 218 | } | |
| 219 | ||
| 220 | $csrfToken = Filter::filterVar($data->{'pmf-csrf-token'}, FILTER_SANITIZE_SPECIAL_CHARS); | |
| 221 | if (!Token::getInstance($this->session)->verifyToken('request-removal', $csrfToken)) { | |
| 222 | throw new Exception('Invalid CSRF token'); | |
| 223 | } | |
| 224 | ||
| 225 | $userId = Filter::filterVar($data->userId ?? null, FILTER_VALIDATE_INT); | |
| 226 | $author = trim((string) Filter::filterVar($data->name ?? null, FILTER_SANITIZE_SPECIAL_CHARS)); | |
| 227 | $loginName = trim((string) Filter::filterVar($data->loginname ?? null, FILTER_SANITIZE_SPECIAL_CHARS)); | |
| 228 | $email = trim((string) Filter::filterEmail($data->email ?? null)); | |
| 229 | $question = trim((string) Filter::filterVar($data->question ?? null, FILTER_SANITIZE_SPECIAL_CHARS)); | |
| 230 | ||
| 231 | // Validate User ID, Username and email | |
| 232 | if ($userId === null) { | |
| 233 | return $this->json([ | |
| 234 | 'error' => Translation::get(key: 'ad_user_error_loginInvalid'), | |
| 235 | ], Response::HTTP_BAD_REQUEST); | |
| 236 | } | |
| 237 | ||
| 238 | if ( | |
| 239 | !$this->currentUser->getUserById($userId) | |
| 240 | || $userId !== $this->currentUser->getUserId() | |
| 241 | || $loginName !== $this->currentUser->getLogin() | |
| 242 | || $email !== $this->currentUser->getUserData('email') | |
| 243 | ) { | |
| 244 | return $this->json([ | |
| 245 | 'error' => Translation::get(key: 'ad_user_error_loginInvalid'), | |
| 246 | ], Response::HTTP_BAD_REQUEST); | |
| 247 | } | |
| 248 | ||
| 249 | if ( | |
| 250 | $author !== '' | |
| 251 | && $author !== '0' | |
| 252 | && $email !== '' | |
| 253 | && $email !== '0' | |
| 254 | && $question !== '' | |
| 255 | && $question !== '0' | |
| 256 | && $this->stopWords->checkBannedWord($question) | |
| 257 | ) { | |
| 258 | $question = sprintf( | |
| 259 | '%s %s<br>%s %s<br>%s %s<br><br>%s', | |
| 260 | Translation::getString(key: 'msgUsername'), | |
| 261 | $loginName, | |
| 262 | Translation::getString(key: 'msgNewContentName'), | |
| 263 | $author, | |
| 264 | Translation::getString(key: 'msgNewContentMail'), | |
| 265 | $email, | |
| 266 | $question, | |
| 267 | ); | |
| 268 | ||
| 269 | try { | |
| 270 | $this->mailer->setReplyTo($email, $author); | |
| 271 | $this->mailer->addTo($this->configuration->getAdminEmail()); | |
| 272 | $this->mailer->subject = $this->configuration->getTitle() . ': Remove User Request'; | |
| 273 | $this->mailer->message = $question; | |
| 274 | $this->mailer->send(); | |
| 275 | ||
| 276 | return $this->json(['success' => Translation::get(key: 'msgMailContact')], Response::HTTP_OK); | |
| 277 | } catch (Exception|TransportExceptionInterface $exception) { | |
| 278 | return $this->json(['error' => $exception->getMessage()], Response::HTTP_BAD_REQUEST); | |
| 279 | } | |
| 280 | } | |
| 281 | ||
| 282 | return $this->json(['error' => Translation::get(key: 'err_sendMail')], Response::HTTP_BAD_REQUEST); | |
| 283 | } | |
| 284 | ||
| 285 | /** | |
| 286 | * @throws \Exception|Exception|TwoFactorAuthException | |
| 287 | */ | |
| 288 | #[Route(path: 'user/remove-twofactor', name: 'api.private.user.remove-twofactor', methods: ['POST'])] | |
| 289 | public function removeTwofactorConfig(Request $request): JsonResponse | |
| 290 | { | |
| 291 | $data = json_decode($request->getContent()); | |
| 292 | ||
| 293 | if (!$data) { | |
| 294 | throw new Exception('Invalid JSON data'); | |
| 295 | } | |
| 296 | ||
| 297 | if (($data->csrfToken ?? null) === null) { | |
| 298 | throw new Exception('Missing CSRF token'); | |
| 299 | } | |
| 300 | ||
| 301 | $twoFactor = new TwoFactor($this->configuration, $this->currentUser); | |
| 302 | ||
| 303 | $csrfToken = Filter::filterVar($data->csrfToken, FILTER_SANITIZE_SPECIAL_CHARS); | |
| 304 | if (!Token::getInstance($this->session)->verifyToken('remove-twofactor', $csrfToken)) { | |
| 305 | throw new Exception('Invalid CSRF token'); | |
| 306 | } | |
| 307 | ||
| 308 | if (!$this->currentUser->isLoggedIn()) { | |
| 309 | throw new Exception('The user is not logged in.'); | |
| 310 | } | |
| 311 | ||
| 312 | $newSecret = $twoFactor->generateSecret(); | |
| 313 | ||
| 314 | if ($this->currentUser->setUserData(['secret' => $newSecret, 'twofactor_enabled' => 0])) { | |
| 315 | return $this->json([ | |
| 316 | 'success' => Translation::get('msgRemoveTwofactorConfigSuccessful'), | |
| 317 | ], Response::HTTP_OK); | |
| 318 | } | |
| 319 | ||
| 320 | return $this->json(['error' => Translation::get(key: 'msgErrorOccurred')], Response::HTTP_BAD_REQUEST); | |
| 321 | } | |
| 322 | } |
Inherited from phpMyFAQ\Controller\AbstractController
| 93 | public function setContainer(ContainerInterface $container): void | |
| 94 | { | |
| 95 | $this->container = $container; | |
| 96 | $this->initializeFromContainer(); | |
| 97 | } |
| 104 | protected function initializeFromContainer(): void | |
| 105 | { | |
| 106 | $configuration = $this->container->get(id: 'phpmyfaq.configuration'); | |
| 107 | if (!$configuration instanceof Configuration) { | |
| 108 | throw new LogicException('Configuration service not found in container.'); | |
| 109 | } | |
| 110 | ||
| 111 | $this->configuration = $configuration; | |
| 112 | ||
| 113 | $currentUser = $this->container->get(id: 'phpmyfaq.user.current_user'); | |
| 114 | if (!$currentUser instanceof CurrentUser) { | |
| 115 | throw new LogicException('CurrentUser service not found in container.'); | |
| 116 | } | |
| 117 | ||
| 118 | $this->currentUser = $currentUser; | |
| 119 | ||
| 120 | $session = $this->container->get(id: 'session'); | |
| 121 | if (!$session instanceof FlashBagAwareSessionInterface) { | |
| 122 | throw new LogicException('Session service not found in container.'); | |
| 123 | } | |
| 124 | ||
| 125 | $this->session = $session; | |
| 126 | ||
| 127 | TwigWrapper::setTemplateSetName($this->configuration->getTemplateSet()); | |
| 128 | $this->isSecured(); | |
| 129 | } |
| 137 | public function render(string $file, array $context = [], ?Response $response = null): Response | |
| 138 | { | |
| 139 | $response ??= new Response(); | |
| 140 | $twigWrapper = $this->getTwigWrapper(); | |
| 141 | $templateWrapper = $twigWrapper->loadTemplate($file); | |
| 142 | ||
| 143 | $response->setContent($templateWrapper->render($context)); | |
| 144 | ||
| 145 | return $response; | |
| 146 | } |
| 154 | public function renderView(string $pathToTwigFile, array $templateVars = []): string | |
| 155 | { | |
| 156 | $twigWrapper = $this->getTwigWrapper(); | |
| 157 | $templateWrapper = $twigWrapper->loadTemplate($pathToTwigFile); | |
| 158 | ||
| 159 | return $templateWrapper->render($templateVars); | |
| 160 | } |
| 167 | public function json(mixed $data, int $status = 200, array $headers = []): JsonResponse | |
| 168 | { | |
| 169 | return new JsonResponse($data, $status, $headers); | |
| 170 | } |
| 182 | protected function getJsonObject(Request $request): \stdClass | |
| 183 | { | |
| 184 | /* @mago-expect analysis:mixed-assignment - json_decode() is mixed by nature; validated to stdClass below */ | |
| 185 | $data = json_decode($request->getContent(), associative: false, depth: 512, flags: JSON_THROW_ON_ERROR); | |
| 186 | ||
| 187 | if (!$data instanceof \stdClass) { | |
| 188 | throw new JsonException('The request body must be a JSON object.'); | |
| 189 | } | |
| 190 | ||
| 191 | return $data; | |
| 192 | } |
| 197 | public function getTwigWrapper(): TwigWrapper | |
| 198 | { | |
| 199 | $twigWrapper = new TwigWrapper( | |
| 200 | (string) PMF_ROOT_DIR . '/assets/templates', | |
| 201 | false, | |
| 202 | $this->configuration->getTemplateSet(), | |
| 203 | ); | |
| 204 | ||
| 205 | foreach ($this->twigExtensions as $twigExtension) { | |
| 206 | $twigWrapper->addExtension($twigExtension); | |
| 207 | } | |
| 208 | ||
| 209 | foreach ($this->twigFilters as $twigFilter) { | |
| 210 | $twigWrapper->addFilter($twigFilter); | |
| 211 | } | |
| 212 | ||
| 213 | return $twigWrapper; | |
| 214 | } |
| 219 | protected function hasValidToken(): void | |
| 220 | { | |
| 221 | $configuredToken = $this->configuration->get(item: 'api.apiClientToken'); | |
| 222 | if (!is_string($configuredToken) || $configuredToken === '') { | |
| 223 | throw new UnauthorizedHttpException(challenge: '"x-pmf-token" is not valid.'); | |
| 224 | } | |
| 225 | ||
| 226 | $request = Request::createFromGlobals(); | |
| 227 | $requestToken = $request->headers->get(key: 'x-pmf-token'); | |
| 228 | if (!is_string($requestToken) || !hash_equals($configuredToken, $requestToken)) { | |
| 229 | throw new UnauthorizedHttpException(challenge: '"x-pmf-token" is not valid.'); | |
| 230 | } | |
| 231 | } |
| 236 | protected function isSecured(): void | |
| 237 | { | |
| 238 | if ($this->currentUser->isLoggedIn()) { | |
| 239 | return; | |
| 240 | } | |
| 241 | ||
| 242 | if (!$this->configuration->get(item: 'security.enableLoginOnly')) { | |
| 243 | return; | |
| 244 | } | |
| 245 | ||
| 246 | $request = Request::createFromGlobals(); | |
| 247 | $pathInfo = rtrim($request->getPathInfo(), characters: '/'); | |
| 248 | $pathInfo = $pathInfo === '' ? '/' : $pathInfo; | |
| 249 | ||
| 250 | if ($this->isPublicAuthenticationPath($pathInfo)) { | |
| 251 | return; | |
| 252 | } | |
| 253 | ||
| 254 | throw new UnauthorizedHttpException(challenge: 'You are not allowed to view this content.'); | |
| 255 | } |
| 257 | private function isPublicAuthenticationPath(string $pathInfo): bool | |
| 258 | { | |
| 259 | $publicAuthenticationPaths = [ | |
| 260 | '/login', | |
| 261 | '/authenticate', | |
| 262 | '/forgot-password', | |
| 263 | '/token', | |
| 264 | '/check', | |
| 265 | '/contact.html', | |
| 266 | '/imprint.html', | |
| 267 | '/privacy.html', | |
| 268 | '/terms.html', | |
| 269 | '/accessibility.html', | |
| 270 | '/auth/azure/authorize', | |
| 271 | '/auth/azure/callback', | |
| 272 | '/auth/azure/callback.php', | |
| 273 | '/auth/keycloak/authorize', | |
| 274 | '/auth/keycloak/callback', | |
| 275 | '/auth/keycloak/logout', | |
| 276 | '/services/azure/callback', | |
| 277 | '/services/azure/callback.php', | |
| 278 | '/api/webauthn/prepare-login', | |
| 279 | '/api/webauthn/login', | |
| 280 | ]; | |
| 281 | ||
| 282 | return in_array($pathInfo, $publicAuthenticationPaths, strict: true); | |
| 283 | } |
| 288 | public function userIsAuthenticated(): void | |
| 289 | { | |
| 290 | if (!$this->currentUser->isLoggedIn()) { | |
| 291 | throw new UnauthorizedHttpException(challenge: 'User is not authenticated.'); | |
| 292 | } | |
| 293 | } |
| 298 | protected function userIsSuperAdmin(): void | |
| 299 | { | |
| 300 | if (!$this->currentUser->isSuperAdmin()) { | |
| 301 | throw new UnauthorizedHttpException(challenge: 'User is not super admin.'); | |
| 302 | } | |
| 303 | } |
| 308 | protected function userHasGroupPermission(): void | |
| 309 | { | |
| 310 | if (!$this->currentUser->isLoggedIn()) { | |
| 311 | throw new UnauthorizedHttpException(challenge: 'User is not authenticated.'); | |
| 312 | } | |
| 313 | ||
| 314 | $currentUser = $this->currentUser; | |
| 315 | if ( | |
| 316 | !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_ADD->value) | |
| 317 | || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_EDIT->value) | |
| 318 | || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_DELETE->value) | |
| 319 | || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::GROUP_EDIT->value) | |
| 320 | ) { | |
| 321 | throw new ForbiddenException(message: 'User has no group permission.'); | |
| 322 | } | |
| 323 | } |
| 328 | protected function userHasUserPermission(): void | |
| 329 | { | |
| 330 | if (!$this->currentUser->isLoggedIn()) { | |
| 331 | throw new UnauthorizedHttpException(challenge: 'User is not authenticated.'); | |
| 332 | } | |
| 333 | ||
| 334 | $currentUser = $this->currentUser; | |
| 335 | if ( | |
| 336 | !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_ADD->value) | |
| 337 | || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_EDIT->value) | |
| 338 | || !$currentUser->perm->hasPermission($currentUser->getUserId(), PermissionType::USER_DELETE->value) | |
| 339 | ) { | |
| 340 | throw new ForbiddenException(message: 'User has no user permission.'); | |
| 341 | } | |
| 342 | } |
| 347 | protected function userHasPermission(PermissionType $permissionType): void | |
| 348 | { | |
| 349 | if (!$this->currentUser->isLoggedIn()) { | |
| 350 | throw new UnauthorizedHttpException(challenge: 'User is not authenticated.'); | |
| 351 | } | |
| 352 | ||
| 353 | $currentUser = $this->currentUser; | |
| 354 | if (!$currentUser?->perm->hasPermission($currentUser->getUserId(), $permissionType->value)) { | |
| 355 | throw new ForbiddenException(message: sprintf('User has no "%s" permission.', $permissionType->name)); | |
| 356 | } | |
| 357 | } |
| 364 | protected function userHasAnyPermission(PermissionType ...$permissionTypes): void | |
| 365 | { | |
| 366 | if (!$this->currentUser->isLoggedIn()) { | |
| 367 | throw new UnauthorizedHttpException(challenge: 'User is not authenticated.'); | |
| 368 | } | |
| 369 | ||
| 370 | $currentUser = $this->currentUser; | |
| 371 | foreach ($permissionTypes as $permissionType) { | |
| 372 | if ($currentUser->perm->hasPermission($currentUser->getUserId(), $permissionType->value)) { | |
| 373 | return; | |
| 374 | } | |
| 375 | } | |
| 376 | ||
| 377 | throw new ForbiddenException(message: sprintf('User has none of the required permissions: %s.', implode(', ', array_map( | |
| 378 | static fn(PermissionType $type): string => $type->name, | |
| 379 | $permissionTypes, | |
| 380 | )))); | |
| 381 | } |
| 389 | protected function verifySessionCsrfToken(string $page, #[\SensitiveParameter] string $requestToken): bool | |
| 390 | { | |
| 391 | if ($requestToken === '') { | |
| 392 | return false; | |
| 393 | } | |
| 394 | ||
| 395 | $sessionKey = sprintf('pmf-csrf-token.%s', $page); | |
| 396 | $storedToken = $this->session->get($sessionKey); | |
| 397 | ||
| 398 | if (!$storedToken instanceof Token) { | |
| 399 | return false; | |
| 400 | } | |
| 401 | ||
| 402 | if (time() > $storedToken->getExpiry()) { | |
| 403 | $this->session->remove($sessionKey); | |
| 404 | return false; | |
| 405 | } | |
| 406 | ||
| 407 | return hash_equals($storedToken->getSessionToken(), $requestToken); | |
| 408 | } |
| 414 | protected function captchaCodeIsValid(Request $request): bool | |
| 415 | { | |
| 416 | $captcha = Captcha::getInstance($this->configuration); | |
| 417 | $captcha->setUserIsLoggedIn($this->currentUser->isLoggedIn()); | |
| 418 | ||
| 419 | $data = json_decode($request->getContent(), associative: false, depth: 512, flags: JSON_THROW_ON_ERROR); | |
| 420 | ||
| 421 | $code = Filter::filterVar($data->captcha ?? '', FILTER_SANITIZE_SPECIAL_CHARS); | |
| 422 | if ($this->configuration->get(item: 'security.enableGoogleReCaptchaV2')) { | |
| 423 | $code = Filter::filterVar($data->{'g-recaptcha-response'} ?? '', FILTER_SANITIZE_SPECIAL_CHARS); | |
| 424 | } | |
| 425 | ||
| 426 | return $captcha->checkCaptchaCode((string) $code); | |
| 427 | } |
| 429 | public function isApiEnabled(): bool | |
| 430 | { | |
| 431 | return (bool) $this->configuration->get(item: 'api.enableAccess'); | |
| 432 | } |
| 434 | public function addExtension(ExtensionInterface $extension): void | |
| 435 | { | |
| 436 | $this->twigExtensions[] = $extension; | |
| 437 | } |
| 439 | public function addFilter(TwigFilter $twigFilter): void | |
| 440 | { | |
| 441 | $this->twigFilters[] = $twigFilter; | |
| 442 | } |
| 444 | protected function getRateLimiter(): ?RateLimiter | |
| 445 | { | |
| 446 | if (!$this->container->has('phpmyfaq.http.rate-limiter')) { | |
| 447 | return null; | |
| 448 | } | |
| 449 | ||
| 450 | $rateLimiter = $this->container->get('phpmyfaq.http.rate-limiter'); | |
| 451 | ||
| 452 | return $rateLimiter instanceof RateLimiter ? $rateLimiter : null; | |
| 453 | } |
| 455 | private function createFallbackContainer(): ContainerBuilder | |
| 456 | { | |
| 457 | $containerBuilder = new ContainerBuilder(); | |
| 458 | $phpFileLoader = new PhpFileLoader($containerBuilder, new FileLocator(__DIR__)); | |
| 459 | try { | |
| 460 | $phpFileLoader->load(resource: '../../services.php'); | |
| 461 | } catch (\Exception $exception) { | |
| 462 | error_log($exception->getMessage()); | |
| 463 | } | |
| 464 | ||
| 465 | // Register Forms services | |
| 466 | FormsServiceProvider::register($containerBuilder); | |
| 467 | ||
| 468 | return $containerBuilder; | |
| 469 | } |