From: Marcel Werk Date: Wed, 28 Aug 2024 14:09:08 +0000 (+0200) Subject: Document guest tokens X-Git-Url: https://git.stricted.de/?a=commitdiff_plain;h=dacce610a8600454bdc32972c1390daa0c013e84;p=GitHub%2FWoltLab%2Fwoltlab.github.io.git Document guest tokens Closes #439 --- diff --git a/docs/javascript/components_guest_token.md b/docs/javascript/components_guest_token.md new file mode 100644 index 00000000..ad74255a --- /dev/null +++ b/docs/javascript/components_guest_token.md @@ -0,0 +1,63 @@ +# Guest Token + +Guest token is a generic implementation to handle the authorization of a guest (entering a user name and filling out a captcha) that can be used in various places. + +The token must be transmitted to the backend and validated there. A corresponding API is available on the PHP backend. + +## Client-side Example + +```ts +import { prepareRequest } from "WoltLabSuite/Core/Ajax/Backend"; +import User from "WoltLabSuite/Core/User"; +import { getGuestToken } from "WoltLabSuite/Core/Component/GuestTokenDialog"; + +let token: string | undefined = ""; +if (!User.userId) { + token = await getGuestToken(); +} + +await prepareRequest("your_backend_url").post({ + token, +}).fetchAsJson(); +``` + +## Backend Example + +```php +use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; +use wcf\http\Helper; +use wcf\system\endpoint\IController; +use wcf\system\endpoint\PostRequest; +use wcf\system\exception\UserInputException; +use wcf\system\WCF; +use wcf\util\UserUtil; + +#[PostRequest('/core/foo')] +final class CreateFoo implements IController +{ + public function __invoke(ServerRequestInterface $request, array $variables): ResponseInterface + { + $parameters = Helper::mapApiParameters($request, CreateFooParameters::class); + + $username = ''; + if (!WCF::getUser()->userID) { + $username = UserUtil::verifyGuestToken($parameters->guestToken); + if ($username === null) { + throw new UserInputException('guestToken'); + } + } + + // ... + } +} + +/** @internal */ +final class CreateFooParameters +{ + public function __construct( + public readonly string $guestToken, + ) { + } +} +``` diff --git a/mkdocs.yml b/mkdocs.yml index c4136c46..a3f35a1f 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -64,6 +64,7 @@ nav: - 'Confirmation': 'javascript/components_confirmation.md' - 'Dialog': 'javascript/components_dialog.md' - 'Google Maps': 'javascript/components_google_maps.md' + - 'Guest Token': 'javascript/components_guest_token.md' - 'Notices': 'javascript/components_notice.md' - 'Pagination': 'javascript/components_pagination.md' - 'RPC API': 'javascript/components_rpc_api.md'