Skip to content

Instantly share code, notes, and snippets.

@maxchene
Last active February 18, 2020 10:59
Show Gist options
  • Save maxchene/d404aecebccadbee9ba84674081bdc12 to your computer and use it in GitHub Desktop.
Save maxchene/d404aecebccadbee9ba84674081bdc12 to your computer and use it in GitHub Desktop.
Cake 4.0.x redirect and flash with Authorization
<?php
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
$authentication = new AuthenticationMiddleware($this);
$middlewareQueue
// Catch any exceptions in the lower layers,
// and make an error page/response
->add(new ErrorHandlerMiddleware(Configure::read('Error')))
// Handle plugin/theme assets like CakePHP normally does.
->add(new AssetMiddleware([
'cacheTime' => Configure::read('Asset.cacheTime'),
]))
// Add routing middleware.
// If you have a large number of routes connected, turning on routes
// caching in production could improve performance. For that when
// creating the middleware instance specify the cache config name by
// using it's second constructor argument:
// `new RoutingMiddleware($this, '_cake_routes_')`
->add(new RoutingMiddleware($this))
->add($authentication)
->add(new AuthorizationMiddleware($this, [
'unauthorizedHandler' => [
'className' => 'CustomRedirect',
'url' => ['_name' => 'login'],
'queryParams' => 'redirectUrl',
'flash' => [
'message' => 'coucou',
'key' => 'flash',
'element' => 'flash/error'
]
]
]))
->add(new RequestAuthorizationMiddleware());
return $middlewareQueue;
}
<?php
declare(strict_types=1);
namespace App\Middleware\UnauthorizedHandler;
use Authorization\Exception\Exception;
use Authorization\Exception\ForbiddenException;
use Authorization\Exception\MissingIdentityException;
use Authorization\Middleware\UnauthorizedHandler\CakeRedirectHandler;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class CustomRedirectHandler extends CakeRedirectHandler
{
/**
* @inheritDoc
*/
protected $defaultOptions = [
'exceptions' => [
MissingIdentityException::class,
ForbiddenException::class
],
'url' => [
'controller' => 'Users',
'action' => 'login',
],
'queryParam' => 'redirect',
'statusCode' => 302,
];
public function handle(Exception $exception, ServerRequestInterface $request, array $options = []): ResponseInterface
{
$session = $request->getSession();
$session->write('Flash.' . $options['flash']['key'], [[
'message' => $options['flash']['message'],
'key' => $options['flash']['key'],
'element' => $options['flash']['element']
]]);
return parent::handle($exception, $request, $options); // TODO: Change the autogenerated stub
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment