1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace T4web\Authentication\Service; |
4
|
|
|
|
5
|
|
|
use Zend\Authentication\AuthenticationService; |
6
|
|
|
use Zend\Mvc\MvcEvent; |
7
|
|
|
use Zend\Mvc\Router\RouteMatch; |
8
|
|
|
use Zend\Console\Request as ConsoleRequest; |
9
|
|
|
use Zend\Mvc\Application; |
10
|
|
|
|
11
|
|
|
class Checker |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var AuthenticationService |
15
|
|
|
*/ |
16
|
|
|
protected $authService; |
17
|
|
|
|
18
|
|
|
public function __construct(AuthenticationService $authService) |
19
|
|
|
{ |
20
|
|
|
$this->authService = $authService; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function __invoke(MvcEvent $event) |
24
|
|
|
{ |
25
|
|
|
if ($event->getRequest() instanceof ConsoleRequest) { |
26
|
|
|
return; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$match = $event->getRouteMatch(); |
30
|
|
|
|
31
|
|
|
// No route match, this is a 404 |
32
|
|
|
if (!$match instanceof RouteMatch) { |
33
|
|
|
return; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** @var Application $app */ |
37
|
|
|
$app = $event->getParam('application'); |
38
|
|
|
$config = $app->getConfig(); |
39
|
|
|
|
40
|
|
|
$disableForAuthorizedCallback = $config['authorized-redirect-to-route']; |
41
|
|
|
$redirectTo = $disableForAuthorizedCallback($match, $this->authService); |
42
|
|
|
if ($this->authService->hasIdentity() && !empty($redirectTo)) { |
43
|
|
|
$response = $this->redirectTo($event, $redirectTo); |
44
|
|
|
return $response; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$checkCallback = $config['need-authorization-callback']; |
48
|
|
|
|
49
|
|
|
// if true = authorization needed |
50
|
|
|
if (!$checkCallback($match, $this->authService)) { |
51
|
|
|
return; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
// User is authenticated |
55
|
|
|
if ($this->authService->hasIdentity()) { |
56
|
|
|
return; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$response = $this->redirectTo($event, 'auth-login'); |
60
|
|
|
|
61
|
|
|
return $response; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
private function redirectTo(MvcEvent $event, $routeName, $reasonPhrase = 'Unauthorized') |
65
|
|
|
{ |
66
|
|
|
// Redirect to the user login page, as an example |
67
|
|
|
$router = $event->getRouter(); |
68
|
|
|
$url = $router->assemble([], ['name' => $routeName]); |
69
|
|
|
|
70
|
|
|
/** @var \Zend\Http\Response $response */ |
71
|
|
|
$response = $event->getResponse(); |
72
|
|
|
$response->getHeaders()->addHeaderLine('Location', $url); |
73
|
|
|
$response->setStatusCode(302); |
74
|
|
|
$response->setReasonPhrase($reasonPhrase); |
75
|
|
|
|
76
|
|
|
return $response; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|