Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
95.83% |
23 / 24 |
|
75.00% |
3 / 4 |
CRAP | |
0.00% |
0 / 1 |
| PanelAuth | |
95.83% |
23 / 24 |
|
75.00% |
3 / 4 |
10 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| process | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
| unauthorized | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
3 | |||
| loginUrl | |
87.50% |
7 / 8 |
|
0.00% |
0 / 1 |
3.02 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Middleware; |
| 6 | |
| 7 | use Celemas\Core\Factory\Factory; |
| 8 | use Cosray\Auth; |
| 9 | use Cosray\Config; |
| 10 | use Cosray\Users; |
| 11 | use Psr\Http\Message\ResponseInterface as Response; |
| 12 | use Psr\Http\Message\ServerRequestInterface as Request; |
| 13 | use Psr\Http\Server\MiddlewareInterface as Middleware; |
| 14 | use Psr\Http\Server\RequestHandlerInterface as Handler; |
| 15 | |
| 16 | class PanelAuth implements Middleware |
| 17 | { |
| 18 | public function __construct( |
| 19 | private readonly Config $config, |
| 20 | private readonly Users $users, |
| 21 | private readonly Factory $factory, |
| 22 | ) {} |
| 23 | |
| 24 | public function process(Request $request, Handler $handler): Response |
| 25 | { |
| 26 | $session = $request->getAttribute('session', null); |
| 27 | $auth = new Auth($request, $this->users, $this->config, $session); |
| 28 | $user = $auth->user(); |
| 29 | |
| 30 | if ($user !== null && $user->hasPermission('panel')) { |
| 31 | return $handler->handle($request); |
| 32 | } |
| 33 | |
| 34 | return $this->unauthorized($request, $user !== null); |
| 35 | } |
| 36 | |
| 37 | private function unauthorized(Request $request, bool $authenticated): Response |
| 38 | { |
| 39 | $url = $this->loginUrl($request); |
| 40 | |
| 41 | if ($request->hasHeader('HX-Request')) { |
| 42 | $status = $authenticated ? 403 : 401; |
| 43 | |
| 44 | return $this->factory |
| 45 | ->response($status) |
| 46 | ->withHeader('HX-Redirect', $url); |
| 47 | } |
| 48 | |
| 49 | return $this->factory |
| 50 | ->response(303) |
| 51 | ->withHeader('Location', $url); |
| 52 | } |
| 53 | |
| 54 | private function loginUrl(Request $request): string |
| 55 | { |
| 56 | $panelPath = $this->config->panel->path; |
| 57 | $path = $request->getUri()->getPath(); |
| 58 | |
| 59 | if ($path === '') { |
| 60 | $path = '/'; |
| 61 | } |
| 62 | |
| 63 | $query = $request->getUri()->getQuery(); |
| 64 | $next = $query === '' ? $path : $path . '?' . $query; |
| 65 | $params = http_build_query(['next' => $next]); |
| 66 | |
| 67 | return $panelPath . '/login?' . $params; |
| 68 | } |
| 69 | } |