Skip to content

Instantly share code, notes, and snippets.

@arnekolja
Last active June 24, 2020 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnekolja/f4126bd13caac69f9a52a986363261b4 to your computer and use it in GitHub Desktop.
Save arnekolja/f4126bd13caac69f9a52a986363261b4 to your computer and use it in GitHub Desktop.
TYPO3 middleware to offer user login status as JSON for AJAX requests
<?php
namespace My\Ext\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Http\Response;
use TYPO3\CMS\Core\Http\Stream;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Middleware to offer user login status as JSON for AJAX requests
* Modified version of code example by Thomas Kieslich
*
* @author Arne-Kolja Bachstein <arnekolja.bachstein@gmail.com>
* @see https://www.thomaskieslich.de/blog/140-typo3-9-psr-15-middleware-am-einfachen-beispiel/
*/
class UncachedContent implements MiddlewareInterface
{
/**
* @param \Psr\Http\Message\ServerRequestInterface $request
* @param \Psr\Http\Server\RequestHandlerInterface $handler
* @return \Psr\Http\Message\ResponseInterface
*/
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
$normalizedParams = $request->getAttribute('normalizedParams');
$uri = $normalizedParams->getRequestUri();
if (strpos($uri, '/uncached/json') === 0) {
$pathComponents = explode('/', $uri);
$path = parse_url($pathComponents[3]);
$command = (string) $path['path'];
$result = '';
if ($command) {
$result = $this->$command();
}
$body = new Stream('php://temp', 'rw');
$body->write(json_encode($result));
return (new Response())
->withHeader('content-type', 'application/json; charset=utf-8')
->withBody($body)
->withStatus(200);
}
return $handler->handle($request);
}
/**
* @return array
*/
protected function loginStatus(): array
{
$context = GeneralUtility::makeInstance(Context::class);
$data = [
// property isLoggedIn seems to be buggy for me in 9.5.16, so comparing id for a workaround
'isLoggedIn' => $context->getPropertyFromAspect('frontend.user', 'id', 0) > 0,
'groupNames' => $context->getPropertyFromAspect('frontend.user', 'groupNames', NULL),
'id' => $context->getPropertyFromAspect('frontend.user', 'id', NULL),
'username' => $context->getPropertyFromAspect('frontend.user', 'username', NULL)
];
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment