Repository navigation
Expand file tree
/
Copy pathUserSession.php
More file actions
300 lines (257 loc) · 10.8 KB
/
Copy pathUserSession.php
File metadata and controls
300 lines (257 loc) · 10.8 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
/**
* This code is licensed under AGPLv3 license or Afterlogic Software License
* if commercial version of the product was purchased.
* For full statements of the licenses see LICENSE-AFTERLOGIC and LICENSE-AGPL3 files.
*/
namespace Aurora\System;
use Aurora\System\Models\AuthToken;
/**
* @license https://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0
* @license https://afterlogic.com/products/common-licensing Afterlogic Software License
* @copyright Copyright (c) 2019, Afterlogic Corp.
*
* @package Api
*/
class UserSession
{
public const TOKEN_VERSION = '4.0';
public static $aTokensCache = [];
public static function getTokenData($oAccount, $bSignMe = true)
{
return [
'token' => 'auth',
'sign-me' => $bSignMe,
'id' => $oAccount->IdUser,
'account' => $oAccount->Id,
'account_type' => get_class($oAccount)
];
}
public function Set($aData, $iTime = 0, $iExpire = 0)
{
$aData['@time'] = $iTime;
$aData['@expire'] = $iExpire;
$aData['@ver'] = self::TOKEN_VERSION;
if ($iExpire > 0) {
$aData['@expire'] = $iExpire;
}
$sAuthToken = Api::EncodeKeyValues(
$aData
);
if (\Aurora\Api::GetSettings()->GetValue('StoreAuthTokenInDB', false)) {
$account = $aData['account'] ?? 0;
$account_type = $aData['account_type'] ?? '';
$this->SetToDB($aData['id'], $account, $account_type, $sAuthToken);
}
return $sAuthToken;
}
public function UpdateTimestamp($sAuthToken, $iTime = 0)
{
$aData = $this->Get($sAuthToken);
$sNewAuthToken = $this->Set($aData, $iTime);
// Reissuing the token invalidates anything keyed off the old token value (e.g. the
// 2FA trusted-device AuthTokenHash in TwoFactorAuth\Manager::saveDevice()). Let
// listeners re-key their state to the new token instead of silently going stale.
$mResult = null;
$aArgs = [
'UserId' => $aData['id'] ?? null,
'OldAuthToken' => $sAuthToken,
'NewAuthToken' => $sNewAuthToken,
];
Api::GetModuleManager()->broadcastEvent(
'System',
'UserSession::RefreshAuthToken::after',
$aArgs,
$mResult
);
return $sNewAuthToken;
}
public function Get($sAuthToken)
{
$mAuthTokenData = false;
$mResult = true;
if (is_string($sAuthToken) && strlen($sAuthToken) !== 0) {
$bStoreAuthTokenInDB = \Aurora\Api::GetSettings()->GetValue('StoreAuthTokenInDB', false);
// check if the auth token is stored in the database
if ($bStoreAuthTokenInDB && !$this->GetFromDB($sAuthToken)) {
return false;
}
$mAuthTokenData = Api::DecodeKeyValues($sAuthToken);
$sReason = '';
// checking the validity of auth token data
if ($mAuthTokenData && isset($mAuthTokenData['id'])) {
$oUser = Api::getUserById((int) $mAuthTokenData['id']);
// check if user is disabled
if ($oUser && $oUser->IsDisabled) {
$mResult = false;
$sReason = 'user is disabled';
}
// check auth token version
if ($mResult) {
if ((isset($mAuthTokenData['@ver']) && $mAuthTokenData['@ver'] !== self::TOKEN_VERSION) || !isset($mAuthTokenData['@ver'])) {
$mResult = false;
$sReason = 'auth token version mismatch';
}
}
// check auth token expiration date
if ($mResult) {
$iExpireTime = (int) isset($mAuthTokenData['@expire']) ? $mAuthTokenData['@expire'] : 0;
if ($iExpireTime > 0 && $iExpireTime < time()) {
$mResult = false;
$sReason = 'auth token expired';
}
}
// checking the token is valid from timestamp
if ($mResult && isset($mAuthTokenData['account'], $mAuthTokenData['account_type']) && class_exists($mAuthTokenData['account_type'])) {
$iTime = (int) $mAuthTokenData['@time'];
$oAccount = $mAuthTokenData['account_type']::where('Id', $mAuthTokenData['account'])->first();
$iTokensValidFromTimestamp = (int) ($oAccount ? $oAccount->getExtendedProp('TokensValidFromTimestamp') : 0);
// Any token created before a password-change invalidation timestamp should be rejected,
// including tokens that were created without an explicit timestamp (for example, remember-me sessions).
if ($oAccount && $iTokensValidFromTimestamp > 0 && ($iTime === 0 || $iTokensValidFromTimestamp > $iTime)) {
$mResult = false;
$sReason = 'auth token invalidated by password change';
}
}
// check user sessions that are considered expired
if ($mResult) {
if ((isset($mAuthTokenData['sign-me']) && !((bool) $mAuthTokenData['sign-me'])) || (!isset($mAuthTokenData['sign-me']))) {
$iTime = 0;
if (isset($mAuthTokenData['@time'])) {
$iTime = (int) $mAuthTokenData['@time'];
}
$iExpireUserSessionsBeforeTimestamp = \Aurora\System\Api::GetSettings()->GetValue("ExpireUserSessionsBeforeTimestamp", 0);
if ($iExpireUserSessionsBeforeTimestamp > $iTime && $iTime > 0) {
$mResult = false;
$sReason = 'user sessions expired by admin';
}
}
}
} else {
$mResult = false;
$sReason = 'auth token could not be decoded';
}
if (!$mResult) {
$this->Delete($sAuthToken);
$mAuthTokenData = $mResult;
\Aurora\System\Api::Log('Auth token rejected: ' . ($sReason !== '' ? $sReason : 'unknown reason'));
\Aurora\System\Api::LogObject($mAuthTokenData);
}
}
return $mAuthTokenData;
}
public function Delete($sAuthToken)
{
if (is_string($sAuthToken) && \Aurora\Api::GetSettings()->GetValue('StoreAuthTokenInDB', false)) {
try {
$this->DeleteFromDB($sAuthToken);
} catch (\Aurora\System\Exceptions\DbException $oEx) {
// DB is not configured
}
}
if (is_string($sAuthToken)) {
unset(self::$aTokensCache[$sAuthToken]);
}
}
public function DeleteAllUserSessions($iUserId)
{
return AuthToken::where('UserId', $iUserId)->delete();
}
public function DeleteAllAccountSessions($oAccount)
{
if ($oAccount instanceof \Aurora\System\Classes\Account) {
$iAccountId = $oAccount->Id;
$sAccountType = get_class($oAccount);
if (\Aurora\Api::GetSettings()->GetValue('StoreAuthTokenInDB', false)) {
try {
AuthToken::where('AccountId', $iAccountId)->where('AccountType', $sAccountType)->delete();
} catch (\Aurora\System\Exceptions\DbException $oEx) {
// DB is not configured
}
} else {
if (class_exists($sAccountType)) {
$oAccount = $sAccountType::where('Id', $iAccountId)->first();
if ($oAccount) {
$oAccount->setExtendedProp('TokensValidFromTimestamp', time());
$oAccount->save();
}
}
}
self::$aTokensCache = [];
}
}
public function SetToDB($iUserId, $iAccountId, $sAccountType, $sAuthToken)
{
$sTokenHash = hash('sha256', $sAuthToken);
$oAuthToken = AuthToken::where('UserId', $iUserId)
->where('AccountId', $iAccountId)
->where('AccountType', $sAccountType)
->where('TokenHash', $sTokenHash)
->first();
if (!$oAuthToken) {
$oAuthToken = AuthToken::where('UserId', $iUserId)
->where('AccountId', $iAccountId)
->where('AccountType', $sAccountType)
->first();
if (!$oAuthToken) {
$oAuthToken = new AuthToken();
}
}
$oAuthToken->UserId = $iUserId;
$oAuthToken->AccountId = $iAccountId;
$oAuthToken->AccountType = $sAccountType;
$oAuthToken->TokenHash = $sTokenHash;
$oAuthToken->LastUsageDateTime = time();
try {
$oAuthToken->save();
} catch (\Aurora\System\Exceptions\DbException $oEx) {
// DB is not configured
}
}
public function GetFromDB($sAuthToken)
{
if (!isset(self::$aTokensCache[$sAuthToken])) {
$sTokenHash = hash('sha256', $sAuthToken);
try {
$oAuthToken = AuthToken::where('TokenHash', $sTokenHash)->first();
if ($oAuthToken) {
$oAuthToken->LastUsageDateTime = time();
$oAuthToken->save();
self::$aTokensCache[$sAuthToken] = $oAuthToken;
}
} catch (\Aurora\System\Exceptions\DbException $oEx) {
\Aurora\Api::LogException($oEx);
}
}
return isset(self::$aTokensCache[$sAuthToken]) ? self::$aTokensCache[$sAuthToken] : false;
}
public function DeleteFromDB($sAuthToken)
{
$sTokenHash = hash('sha256', $sAuthToken);
AuthToken::where('TokenHash', $sTokenHash)->delete();
}
public function DeleteByTokenHash($sTokenHash)
{
if (is_string($sTokenHash) && \Aurora\Api::GetSettings()->GetValue('StoreAuthTokenInDB', false)) {
try {
AuthToken::where('TokenHash', $sTokenHash)->delete();
} catch (\Aurora\System\Exceptions\DbException $oEx) {
// DB is not configured
}
}
}
public function GetExpiredAuthTokens($iDays)
{
$iTime = $iDays * 86400;
return AuthToken::query()->whereRaw('(LastUsageDateTime + ' . $iTime . ') < UNIX_TIMESTAMP()')->get();
}
public function DeleteExpiredAuthTokens($iDays)
{
$iTime = $iDays * 86400;
return AuthToken::query()->whereRaw('(LastUsageDateTime + ' . $iTime . ') < UNIX_TIMESTAMP()')->delete();
}
public function GetUserSessionsFromDB($iUserId)
{
return AuthToken::where('UserId', $iUserId)->get();
}
}