Passed
Push — master ( e8f83f...f116c2 )
by Jan
05:37
created

LogAccessDeniedSubscriber::onKernelException()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 14
rs 10
1
<?php
2
/**
3
 * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
4
 *
5
 * Copyright (C) 2019 - 2020 Jan Böhmer (https://github.com/jbtronics)
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as published
9
 * by the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace App\EventSubscriber\LogSystem;
22
23
24
use App\Entity\LogSystem\UserNotAllowedLogEntry;
25
use App\Services\LogSystem\EventLogger;
26
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
27
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
28
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
29
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
30
31
/**
32
 * Write to event log when a user tries to access an forbidden page and recevies an 403 Access Denied message.
33
 * @package App\EventSubscriber\LogSystem
34
 */
35
class LogAccessDeniedSubscriber implements EventSubscriberInterface
36
{
37
    private $logger;
38
39
    public function __construct(EventLogger $logger)
40
    {
41
        $this->logger = $logger;
42
    }
43
44
    public function onKernelException(ExceptionEvent $event)
45
    {
46
        $throwable = $event->getThrowable();
47
        if ($throwable instanceof AccessDeniedHttpException) {
48
            $throwable = $throwable->getPrevious();
49
        }
50
        //Ignore everything except AccessDeniedExceptions
51
        if (!$throwable instanceof AccessDeniedException) {
52
            return;
53
        }
54
55
        $path = $event->getRequest()->getPathInfo();
56
        $log_entry = new UserNotAllowedLogEntry($path);
57
        $this->logger->logAndFlush($log_entry);
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public static function getSubscribedEvents()
64
    {
65
        return ['kernel.exception' => 'onKernelException'];
66
    }
67
}