Skip to content

Instantly share code, notes, and snippets.

@basz
Last active November 18, 2015 21:40
Show Gist options
  • Save basz/b78e3da1ebb36bf46290 to your computer and use it in GitHub Desktop.
Save basz/b78e3da1ebb36bf46290 to your computer and use it in GitHub Desktop.
ZfcRbac\Middleware\ZendAuthenticationServiceMiddleware
<?php
namespace ZfcRbac\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Authentication\AuthenticationService;
use Zend\Stratigility\MiddlewareInterface;
class ZendAuthenticationServiceMiddleware implements MiddlewareInterface
{
/**
* @var AuthenticationService
*/
private $authService;
/**
* @var string
*/
private $attributeName;
/**
* ZendAuthenticationServiceMiddleware constructor.
*
* @param AuthenticationService $authService
*/
public function __construct(AuthenticationService $authService, $attributeName = 'identity')
{
$this->authService = $authService;
$this->attributeName = $attributeName;
}
/**
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable|null $next
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
if ($this->authService->hasIdentity()) {
$identity = $this->authService->getIdentity();
if (!$request->getAttribute($this->attributeName, false)) {
$request = $request->withAttribute($this->attributeName, $identity);
}
}
$response = $next($request, $response);
return $response;
}
}
<?php
namespace ZfcRbac\Middleware;
use Doctrine\Common\Cache\Cache;
use Interop\Container\ContainerInterface;
use Zend\Authentication\AuthenticationService;
class ZendAuthenticationServiceMiddlewareFactory
{
public function __invoke(ContainerInterface $container)
{
$authService = $container->get(AuthenticationService::class);
$config = $container->get('config')['zfc_rbac'];
return new ZendAuthenticationServiceMiddleware($authService, $config['attributeName']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment