Completed
Push — master ( 8f2b16...c80f65 )
by Marcel
03:24
created

HandleSamlRequestSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 4
ccs 4
cts 4
cp 1
crap 1
rs 10
1
<?php
2
3
namespace App\EventSubscriber;
4
5
use Scheb\TwoFactorBundle\Security\Authentication\Token\TwoFactorToken;
6
use SchulIT\LightSamlIdpBundle\RequestStorage\RequestStorageInterface;
7
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8
use Symfony\Component\HttpFoundation\RedirectResponse;
9
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
10
use Symfony\Component\HttpKernel\KernelEvents;
11
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
12
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
13
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
14
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
15
16
/**
17
 * Listener which checks whether there is a SAMLRequest pending from before login. If so, the listener redirects to the
18
 * SSO controller in order to send the SAMLResponse (and redirect the user to the requested service).
19
 */
20
class HandleSamlRequestSubscriber implements EventSubscriberInterface {
21
22
    private $urlGenerator;
23
    private $tokenStorage;
24
    private $samlRequestStorage;
25
26 13
    public function __construct(TokenStorageInterface $tokenStorage, RequestStorageInterface $requestStorage, UrlGeneratorInterface $urlGenerator) {
27 13
        $this->tokenStorage = $tokenStorage;
28 13
        $this->samlRequestStorage = $requestStorage;
29 13
        $this->urlGenerator = $urlGenerator;
30 13
    }
31
32 11
    public function onKernelRequest(GetResponseEvent $event) {
33 11
        $request = $event->getRequest();
34 11
        $route = $request->get('_route');
35
36 11
        if(!$event->isMasterRequest()) {
37
            // prevent loops
38 1
            return;
39
        }
40
41
        /** @var TokenInterface|null $token */
42 10
        $token = $this->tokenStorage->getToken();
43
44 10
        if($token === null || !$token->isAuthenticated() || $token instanceof AnonymousToken || $token instanceof TwoFactorToken || $route === 'idp_saml') {
45
            // prevent loops
46 7
            return;
47
        }
48
49 5
        if($this->samlRequestStorage->has()) {
50 1
            $response = new RedirectResponse($this->urlGenerator->generate('idp_saml'));
51 1
            $event->setResponse($response);
52
        }
53 5
    }
54
55
    /**
56
     * @return array
57
     */
58
    public static function getSubscribedEvents() {
59
        return [
60
            KernelEvents::REQUEST => [
61
                [ 'onKernelRequest', 0]
62
            ]
63
        ];
64
    }
65
}