Completed
Push — master ( 91361b...756e8e )
by max
02:53
created

Checker   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 4
Bugs 1 Features 1
Metric Value
wmc 9
c 4
b 1
f 1
lcom 0
cbo 5
dl 0
loc 67
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A redirectTo() 0 13 1
C __invoke() 0 39 7
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
    /**
15
     * @var AuthenticationService
16
     */
17
    protected $authService;
18
19
    public function __construct(AuthenticationService $authService)
20
    {
21
        $this->authService = $authService;
22
    }
23
24
    public function __invoke(MvcEvent $event)
25
    {
26
        if ($event->getRequest() instanceof ConsoleRequest) {
27
            return;
28
        }
29
30
        $match = $event->getRouteMatch();
31
32
        // No route match, this is a 404
33
        if (!$match instanceof RouteMatch) {
34
            return;
35
        }
36
37
        if ($match->getMatchedRouteName() == 'auth-login' && $this->authService->hasIdentity()) {
38
            $response = $this->redirectTo($event, 'home');
39
40
            return $response;
41
        }
42
43
        /** @var Application $app */
44
        $app = $event->getParam('application');
45
        $config = $app->getConfig();
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
        $response = $event->getResponse();
71
        $response->getHeaders()->addHeaderLine('Location', $url);
72
        $response->setStatusCode(302);
73
        $response->setReasonPhrase($reasonPhrase);
74
75
        return $response;
76
    }
77
}
78