|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace AbterPhp\Admin\Http\Middleware; |
|
6
|
|
|
|
|
7
|
|
|
use AbterPhp\Framework\Constant\Session; |
|
8
|
|
|
use Casbin\Enforcer; |
|
9
|
|
|
use Casbin\Exceptions\CasbinException; |
|
10
|
|
|
use Closure; |
|
11
|
|
|
use Opulence\Http\Requests\Request; |
|
12
|
|
|
use Opulence\Http\Responses\RedirectResponse; |
|
13
|
|
|
use Opulence\Http\Responses\Response; |
|
14
|
|
|
use Opulence\Http\Responses\ResponseHeaders; |
|
15
|
|
|
use Opulence\Routing\Middleware\ParameterizedMiddleware; |
|
16
|
|
|
use Opulence\Sessions\ISession; |
|
17
|
|
|
|
|
18
|
|
|
class Authorization extends ParameterizedMiddleware |
|
19
|
|
|
{ |
|
20
|
|
|
public const PATH_403 = '/nope'; |
|
21
|
|
|
|
|
22
|
|
|
public const RESOURCE = 'resource'; |
|
23
|
|
|
public const ROLE = 'role'; |
|
24
|
|
|
|
|
25
|
|
|
public const RESOURCE_PREFIX = 'admin_resource_'; |
|
26
|
|
|
|
|
27
|
|
|
protected ISession $session; |
|
28
|
|
|
|
|
29
|
|
|
protected Enforcer $enforcer; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Authorization constructor. |
|
33
|
|
|
* |
|
34
|
|
|
* @param ISession $session |
|
35
|
|
|
* @param Enforcer $enforcer |
|
36
|
|
|
*/ |
|
37
|
|
|
public function __construct(ISession $session, Enforcer $enforcer) |
|
38
|
|
|
{ |
|
39
|
|
|
$this->session = $session; |
|
40
|
|
|
$this->enforcer = $enforcer; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param Request $request |
|
45
|
|
|
* @param Closure $next |
|
46
|
|
|
* |
|
47
|
|
|
* @return Response |
|
48
|
|
|
* @throws \Exception |
|
49
|
|
|
*/ |
|
50
|
|
|
public function handle(Request $request, Closure $next): Response |
|
51
|
|
|
{ |
|
52
|
|
|
$username = $this->session->get(Session::USERNAME); |
|
53
|
|
|
$resource = static::RESOURCE_PREFIX . $this->getParameter(static::RESOURCE); |
|
54
|
|
|
$role = $this->getParameter(static::ROLE); |
|
55
|
|
|
|
|
56
|
|
|
try { |
|
57
|
|
|
if ($this->enforcer->enforce($username, $resource, $role)) { |
|
58
|
|
|
return $next($request); |
|
59
|
|
|
} |
|
60
|
|
|
} catch (CasbinException $e) { |
|
61
|
|
|
return new RedirectResponse(static::PATH_403, ResponseHeaders::HTTP_TEMPORARY_REDIRECT); |
|
62
|
|
|
} catch (\Exception $e) { |
|
63
|
|
|
throw $e; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return new RedirectResponse(static::PATH_403, ResponseHeaders::HTTP_TEMPORARY_REDIRECT); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|