Passed
Push — master ( 77290b...f3fb78 )
by Marcel
09:09
created

ActiveSessionsResolver::getSessionsForUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 12
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 18
rs 9.8666
1
<?php
2
3
namespace App\Security\Session;
4
5
use App\Entity\User;
6
use DateTimeImmutable;
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\Exception;
9
use Doctrine\DBAL\Schema\Schema;
10
use Doctrine\DBAL\Types\Types;
11
use Symfony\Component\HttpFoundation\RequestStack;
12
13
/**
14
 * Helper to resolve active sessions. As the default PdoSessionHandler does not support
15
 * this, we add support by storing the relationship between a user and his/her sessions
16
 * in a separate database table.
17
 *
18
 * We use an EventSubscriber (ActiveSessionsSubscriber.php) to create such relationship
19
 * after a successful login.
20
 */
21
class ActiveSessionsResolver {
22
23
    public function __construct(private readonly Connection $connection, private readonly RequestStack $requestStack) {
24
25
    }
26
27
    /**
28
     * @param User $user
29
     * @return ActiveSession[]
30
     * @throws Exception
31
     * @throws \Exception
32
     */
33
    public function getSessionsForUser(User $user): array {
34
        $result = $this->connection->executeQuery('SELECT * FROM session_user WHERE user_id = ?', [$user->getId()]);
35
        $sessions = [ ];
36
37
        $currentSessionId = $this->requestStack->getMainRequest()->getSession()->getId();
38
39
        foreach($result->fetchAllAssociative() as $row) {
40
            $sessions[] = new ActiveSession(
41
                (int)$row['user_id'],
42
                $row['session_id'],
43
                $row['user_agent'],
44
                new DateTimeImmutable($row['started_at']),
45
                $row['ip_address'],
46
                $row['session_id'] === $currentSessionId
47
            );
48
        }
49
50
        return $sessions;
51
    }
52
53
    public function configureSchema(Schema $schema, Connection $forConnection): void {
54
        if($this->connection !== $forConnection) {
55
            return;
56
        }
57
58
        if($schema->hasTable('session_user')) {
59
            return;
60
        }
61
62
        $this->addTableToSchema($schema);
63
    }
64
65
    private function addTableToSchema(Schema $schema): void {
66
        $table = $schema->createTable('session_user');
67
        $table->addColumn('user_id', Types::INTEGER, ['unsigned' => true, 'length' => 10]);
68
        $table->addColumn('session_id', Types::BINARY, ['length' => 128]);
69
        $table->addColumn('user_agent', Types::TEXT, ['notnull' => false]);
70
        $table->addColumn('started_at', Types::DATETIME_IMMUTABLE);
71
        $table->addColumn('ip_address', Types::STRING, ['length' => 45, 'notnull' => false ]);
72
        $table->addForeignKeyConstraint('user', ['user_id'], ['id'], ['onUpdate' => 'CASCADE', 'onDelete' => 'CASCADE']);
73
        $table->addForeignKeyConstraint('sessions', ['session_id'], ['sess_id'], ['onUpdate' => 'CASCADE', 'onDelete' => 'CASCADE']);
74
    }
75
}