/
user_session.php
106 lines (89 loc) · 3.23 KB
/
user_session.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
/**
* @package redaxo\core\login
*
* @internal
*/
class rex_user_session
{
use rex_singleton_trait;
private const SESSION_VAR_LAST_DB_UPDATE = 'last_db_update';
public function storeCurrentSession(rex_backend_login $login): void
{
$sessionId = session_id();
if (false === $sessionId || '' === $sessionId) {
return;
}
$userId = $login->getSessionVar(rex_login::SESSION_IMPERSONATOR, null);
if (null === $userId) {
$userId = $login->getSessionVar(rex_login::SESSION_USER_ID);
}
rex_sql::factory()
->setTable(rex::getTable('user_session'))
->setValue('session_id', session_id())
->setValue('user_id', $userId)
->setValue('ip', rex_request::server('REMOTE_ADDR', 'string'))
->setValue('useragent', rex_request::server('HTTP_USER_AGENT', 'string'))
->setValue('starttime', rex_sql::datetime($login->getSessionVar(rex_login::SESSION_START_TIME, time())))
->setValue('last_activity', rex_sql::datetime($login->getSessionVar(rex_login::SESSION_LAST_ACTIVITY)))
->insertOrUpdate();
$login->setSessionVar(self::SESSION_VAR_LAST_DB_UPDATE, time());
}
public function clearCurrentSession(): void
{
$sessionId = session_id();
if (false === $sessionId || '' === $sessionId) {
return;
}
rex_sql::factory()
->setTable(rex::getTable('user_session'))
->setWhere('session_id = ?', [session_id()])
->delete();
}
public function updateLastActivity(rex_backend_login $login): void
{
$sessionId = session_id();
if (false === $sessionId || '' === $sessionId) {
return;
}
// only once a minute
if ($login->getSessionVar(self::SESSION_VAR_LAST_DB_UPDATE, 0) > (time() - 60)) {
return;
}
$this->storeCurrentSession($login);
}
public static function updateSessionId(string $previousId, string $newId): void
{
rex_sql::factory()
->setTable(rex::getTable('user_session'))
->setWhere(['session_id' => $previousId])
->setValue('session_id', $newId)
->update();
}
public static function clearExpiredSessions(): void
{
rex_sql::factory()
->setTable(rex::getTable('user_session'))
->setWhere('UNIX_TIMESTAMP(last_activity) < ?', [time() - (int) rex::getProperty('session_duration')])
->delete();
}
public function removeSession(string $sessionId, int $userId): bool
{
$sql = rex_sql::factory()
->setTable(rex::getTable('user_session'))
->setWhere('session_id = ? and user_id = ?', [$sessionId, $userId])
->delete();
return $sql->getRows() > 0;
}
public function removeSessionsExceptCurrent(int $userId): void
{
$sessionId = session_id();
if (false === $sessionId || '' === $sessionId) {
return;
}
rex_sql::factory()
->setTable(rex::getTable('user_session'))
->setWhere('session_id != ? and user_id = ?', [$sessionId, $userId])
->delete();
}
}