GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( af81b9...96f568 )
by Maximilian
03:34
created

SessionCleanupCommand   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 171
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 15

Test Coverage

Coverage 81.08%

Importance

Changes 9
Bugs 3 Features 0
Metric Value
wmc 9
c 9
b 3
f 0
lcom 1
cbo 15
dl 0
loc 171
ccs 60
cts 74
cp 0.8108
rs 9.1666

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 17 1
A configure() 0 18 1
C execute() 0 85 7
1
<?php
2
3
namespace Ma27\ApiKeyAuthenticationBundle\Command;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\Common\Collections\Criteria;
7
use Doctrine\Common\Collections\Selectable;
8
use Doctrine\Common\Persistence\ObjectManager;
9
use Ma27\ApiKeyAuthenticationBundle\Event\OnAfterCleanupEvent;
10
use Ma27\ApiKeyAuthenticationBundle\Event\OnApiKeyCleanupErrorEvent;
11
use Ma27\ApiKeyAuthenticationBundle\Event\OnBeforeSessionCleanupEvent;
12
use Ma27\ApiKeyAuthenticationBundle\Event\OnSuccessfulCleanupEvent;
13
use Ma27\ApiKeyAuthenticationBundle\Ma27ApiKeyAuthenticationEvents;
14
use Ma27\ApiKeyAuthenticationBundle\Model\Login\AuthenticationHandlerInterface;
15
use Ma27\ApiKeyAuthenticationBundle\Model\User\ClassMetadata;
16
use Psr\Log\LoggerInterface;
17
use Symfony\Component\Console\Command\Command;
18
use Symfony\Component\Console\Input\InputInterface;
19
use Symfony\Component\Console\Output\OutputInterface;
20
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
21
22
/**
23
 * Command which is responsible for the session cleanup.
24
 */
25
class SessionCleanupCommand extends Command
26
{
27
    /**
28
     * @var ObjectManager
29
     */
30
    private $om;
31
32
    /**
33
     * @var AuthenticationHandlerInterface
34
     */
35
    private $handler;
36
37
    /**
38
     * @var LoggerInterface
39
     */
40
    private $logger;
41
42
    /**
43
     * @var EventDispatcherInterface
44
     */
45
    private $eventDispatcher;
46
47
    /**
48
     * @var string
49
     */
50
    private $modelName;
51
52
    /**
53
     * @var ClassMetadata
54
     */
55
    private $classMetadata;
56
57
    /**
58
     * Constructor.
59
     *
60
     * @param ObjectManager                  $om
61
     * @param AuthenticationHandlerInterface $authenticationHandler
62
     * @param EventDispatcherInterface       $eventDispatcher
63
     * @param string                         $modelName
64
     * @param ClassMetadata                  $classMetadata
65
     * @param LoggerInterface                $logger
66
     */
67 1
    public function __construct(
68
        ObjectManager $om,
69
        AuthenticationHandlerInterface $authenticationHandler,
70
        EventDispatcherInterface $eventDispatcher,
71
        $modelName,
72
        ClassMetadata $classMetadata,
73
        LoggerInterface $logger = null
74
    ) {
75 1
        $this->om = $om;
76 1
        $this->handler = $authenticationHandler;
77 1
        $this->logger = $logger;
78 1
        $this->eventDispatcher = $eventDispatcher;
79 1
        $this->modelName = (string) $modelName;
80 1
        $this->classMetadata = $classMetadata;
81
82 1
        parent::__construct();
83 1
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88 1
    protected function configure()
89
    {
90 1
        $this
91 1
            ->setName('ma27:auth:session-cleanup')
92 1
            ->setDescription('Cleans all outdated sessions')
93 1
            ->setHelp(<<<'EOF'
94
The <info>ma27:auth:session-cleanup</info> command purges all api keys of users that were inactive for at least 5 days
95
96
The usage is pretty simple:
97
98
    <info>php app/console ma27:auth:session-cleanup</info>
99
100
NOTE: you have to enable the cleanup section of that bundle (please review the docs for more information)
101
102
<info>It's recommended to use a cronjob that purges old api keys every day/two days</info>
103
EOF
104 1
            );
105 1
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 1
    protected function execute(InputInterface $input, OutputInterface $output)
111
    {
112
        try {
113 1
            $dateTime = new \DateTime();
114
115 1
            $now = $dateTime->format('m/d/Y H:i:s');
116 1
            $message = sprintf('Starting session purge at %s', $now);
117 1
            $output->writeln(sprintf('<info>%s</info>', $message));
118 1
            if (null !== $this->logger) {
119
                @trigger_error('Logger support is deprecated!', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
120
                $this->logger->notice($message);
121
            }
122
123
            // search query
124 1
            $latestActivationPropertyName = $this->classMetadata->getPropertyName(ClassMetadata::LAST_ACTION_PROPERTY);
125 1
            $criteria = Criteria::create()
126 1
                ->where(Criteria::expr()->lte($latestActivationPropertyName, new \DateTime('-5 days')))
127 1
                ->andWhere(
128 1
                    Criteria::expr()->neq(
129 1
                        $this->classMetadata->getPropertyName(ClassMetadata::API_KEY_PROPERTY),
130
                        null
131 1
                    )
132 1
                );
133
134 1
            $repository = $this->om->getRepository($this->modelName);
135
136 1
            if ($repository instanceof Selectable) {
137
                // orm and mongodb have a Selectable implementation, so it is possible to query for old users
138
                $filteredUsers = $repository->matching($criteria);
139
            } else {
140
                // couchdb and phpcr unfortunately don't implement that feature,
141
                // so all users must be queried and filtered using the array collection
142 1
                $allUsers = new ArrayCollection($repository->findAll());
143 1
                $filteredUsers = $allUsers->matching($criteria);
144
            }
145
146 1
            $processedObjects = 0;
147
148 1
            $affectedUsers = $filteredUsers->toArray();
149 1
            $event = new OnBeforeSessionCleanupEvent($affectedUsers);
150 1
            $this->eventDispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::BEFORE_CLEANUP, $event);
151
152
            // purge filtered users
153 1
            foreach ($filteredUsers as $user) {
154 1
                $this->handler->removeSession($user, true);
155 1
                ++$processedObjects;
156 1
            }
157
158 1
            $message = sprintf('Processed %d items successfully', $processedObjects);
159 1
            $output->writeln(sprintf('<info>%s</info>', $message));
160 1
            if (null !== $this->logger) {
161
                $this->logger->notice($message);
162
            }
163
164 1
            $afterEvent = new OnSuccessfulCleanupEvent($affectedUsers);
165 1
            $this->eventDispatcher->dispatch(Ma27ApiKeyAuthenticationEvents::CLEANUP_SUCCESS, $afterEvent);
166
167 1
            $this->om->flush();
168
169 1
            $endTime = new \DateTime();
170 1
            $end = $endTime->format('m/d/Y H:i:s');
171
172 1
            $diff = $endTime->getTimestamp() - $dateTime->getTimestamp();
173 1
            $message = sprintf('Stopped cleanup at %s after %d seconds', $end, $diff);
174
175 1
            $output->writeln(sprintf('<info>%s</info>', $message));
176 1
            if (null !== $this->logger) {
177
                $this->logger->notice($message);
178
            }
179 1
        } catch (\Exception $ex) {
180
            $this->eventDispatcher->dispatch(
181
                Ma27ApiKeyAuthenticationEvents::CLEANUP_ERROR,
182
                new OnApiKeyCleanupErrorEvent($ex)
183
            );
184
185
            throw $ex;
186
        }
187
188 1
        $this->eventDispatcher->dispatch(
189 1
            Ma27ApiKeyAuthenticationEvents::AFTER_CLEANUP,
190 1
            new OnAfterCleanupEvent($affectedUsers)
191 1
        );
192
193 1
        return 0;
194
    }
195
}
196