add admin middleware
This commit is contained in:
parent
40649ded8e
commit
bb4e27a45b
1 changed files with 64 additions and 0 deletions
64
app/Auth/AdminMiddleware.php
Normal file
64
app/Auth/AdminMiddleware.php
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
<?php
|
||||
|
||||
namespace App\Auth;
|
||||
|
||||
use App\User\User;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\MiddlewareInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Slim\Psr7\Response;
|
||||
|
||||
class AdminMiddleware implements MiddlewareInterface
|
||||
{
|
||||
public function process(
|
||||
ServerRequestInterface $request,
|
||||
RequestHandlerInterface $handler,
|
||||
): ResponseInterface {
|
||||
$user = $request->getAttribute('user');
|
||||
|
||||
if (!$user instanceof User || !$user->isAdmin()) {
|
||||
return $this->forbidden($request);
|
||||
}
|
||||
|
||||
return $handler->handle($request);
|
||||
}
|
||||
|
||||
private function forbidden(
|
||||
ServerRequestInterface $request
|
||||
): ResponseInterface {
|
||||
$response = new Response(403);
|
||||
|
||||
if ($this->wantsJson($request)) {
|
||||
$response->getBody()->write(
|
||||
json_encode(['error' => 'forbidden'])
|
||||
);
|
||||
return $response->withHeader(
|
||||
'Content-Type',
|
||||
'application/json'
|
||||
);
|
||||
}
|
||||
|
||||
$html = file_get_contents(
|
||||
__DIR__ . '/../../views/templates/forbidden.php'
|
||||
);
|
||||
$response->getBody()->write($html);
|
||||
|
||||
return $response->withHeader('Content-Type', 'text/html');
|
||||
}
|
||||
|
||||
private function wantsJson(ServerRequestInterface $request): bool
|
||||
{
|
||||
$path = $request->getUri()->getPath();
|
||||
if (str_starts_with($path, '/api/')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$accept = $request->getHeaderLine('Accept');
|
||||
if (str_contains($accept, 'application/json')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue