|
| 1 | +# Guest Token |
| 2 | + |
| 3 | +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. |
| 4 | + |
| 5 | +The token must be transmitted to the backend and validated there. A corresponding API is available on the PHP backend. |
| 6 | + |
| 7 | +## Client-side Example |
| 8 | + |
| 9 | +```ts |
| 10 | +import { prepareRequest } from "WoltLabSuite/Core/Ajax/Backend"; |
| 11 | +import User from "WoltLabSuite/Core/User"; |
| 12 | +import { getGuestToken } from "WoltLabSuite/Core/Component/GuestTokenDialog"; |
| 13 | + |
| 14 | +let token: string | undefined = ""; |
| 15 | +if (!User.userId) { |
| 16 | + token = await getGuestToken(); |
| 17 | +} |
| 18 | + |
| 19 | +await prepareRequest("your_backend_url").post({ |
| 20 | + token, |
| 21 | +}).fetchAsJson(); |
| 22 | +``` |
| 23 | + |
| 24 | +## Backend Example |
| 25 | + |
| 26 | +```php |
| 27 | +use Psr\Http\Message\ResponseInterface; |
| 28 | +use Psr\Http\Message\ServerRequestInterface; |
| 29 | +use wcf\http\Helper; |
| 30 | +use wcf\system\endpoint\IController; |
| 31 | +use wcf\system\endpoint\PostRequest; |
| 32 | +use wcf\system\exception\UserInputException; |
| 33 | +use wcf\system\WCF; |
| 34 | +use wcf\util\UserUtil; |
| 35 | + |
| 36 | +#[PostRequest('/core/foo')] |
| 37 | +final class CreateFoo implements IController |
| 38 | +{ |
| 39 | + public function __invoke(ServerRequestInterface $request, array $variables): ResponseInterface |
| 40 | + { |
| 41 | + $parameters = Helper::mapApiParameters($request, CreateFooParameters::class); |
| 42 | + |
| 43 | + $username = ''; |
| 44 | + if (!WCF::getUser()->userID) { |
| 45 | + $username = UserUtil::verifyGuestToken($parameters->guestToken); |
| 46 | + if ($username === null) { |
| 47 | + throw new UserInputException('guestToken'); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + // ... |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +/** @internal */ |
| 56 | +final class CreateFooParameters |
| 57 | +{ |
| 58 | + public function __construct( |
| 59 | + public readonly string $guestToken, |
| 60 | + ) { |
| 61 | + } |
| 62 | +} |
| 63 | +``` |
0 commit comments