aboutsummaryrefslogtreecommitdiffstats
path: root/core/Controller/CSRFTokenController.php
blob: 8ea475941c8d1fc878a0332e1bb6d9376e4539c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php

declare(strict_types=1);

/**
 * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OC\Core\Controller;

use OC\Security\CSRF\CsrfTokenManager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\FrontpageRoute;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest;

class CSRFTokenController extends Controller {
	public function __construct(
		string $appName,
		IRequest $request,
		private CsrfTokenManager $tokenManager,
	) {
		parent::__construct($appName, $request);
	}

	/**
	 * Returns a new CSRF token.
	 *
	 * @return JSONResponse<Http::STATUS_OK, array{token: string}, array{}>|JSONResponse<Http::STATUS_FORBIDDEN, list<empty>, array{}>
	 *
	 * 200: CSRF token returned
	 * 403: Strict cookie check failed
	 */
	#[PublicPage]
	#[NoCSRFRequired]
	#[FrontpageRoute(verb: 'GET', url: '/csrftoken')]
	public function index(): JSONResponse {
		if (!$this->request->passesStrictCookieCheck()) {
			return new JSONResponse([], Http::STATUS_FORBIDDEN);
		}

		$requestToken = $this->tokenManager->getToken();

		return new JSONResponse([
			'token' => $requestToken->getEncryptedValue(),
		]);
	}
}