Last active
June 24, 2020 13:24
-
-
Save arnekolja/f4126bd13caac69f9a52a986363261b4 to your computer and use it in GitHub Desktop.
TYPO3 middleware to offer user login status as JSON for AJAX requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 <[email protected]> | |
* @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