-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathAuth.php
More file actions
345 lines (290 loc) · 13.6 KB
/
Copy pathAuth.php
File metadata and controls
345 lines (290 loc) · 13.6 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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<?php
/**
*
* Copyright (C) 2015-2019 FeatherBB
* based on code by (C) 2008-2015 FluxBB
* and Rickard Andersson (C) 2002-2008 PunBB
* License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
*
* $app = new \Slim\Slim();
* $app->add(new \Slim\Extras\Middleware\FeatherBBAuth());
*
*/
namespace FeatherBB\Middleware;
use FeatherBB\Core\Database as DB;
use FeatherBB\Core\Error;
use FeatherBB\Core\Interfaces\Cache as CacheInterface;
use FeatherBB\Core\Interfaces\Container;
use FeatherBB\Core\Interfaces\ForumEnv;
use FeatherBB\Core\Interfaces\ForumSettings;
use FeatherBB\Core\Interfaces\Lang;
use FeatherBB\Core\Interfaces\Perms;
use FeatherBB\Core\Interfaces\Prefs;
use FeatherBB\Core\Interfaces\User;
use FeatherBB\Core\Track;
use FeatherBB\Core\Utils;
use FeatherBB\Model\Auth as AuthModel;
use FeatherBB\Model\Cache;
use Firebase\JWT\JWT;
class Auth
{
protected function getCookieData($authCookie = null)
{
if ($authCookie) {
/*
* Extract the jwt from the Bearer
*/
list($jwt) = sscanf($authCookie, 'Bearer %s');
if ($jwt) {
try {
/*
* decode the jwt using the key from config
*/
$secretKey = base64_decode(ForumEnv::get('JWT_TOKEN'));
$token = JWT::decode($jwt, $secretKey, [ForumEnv::get('JWT_ALGORITHM')]);
return $token;
} catch (\Firebase\JWT\ExpiredException $e) {
// TODO: (Optional) add flash message to say token has expired
return false;
} catch (\Firebase\JWT\SignatureInvalidException $e) {
// If token secret has changed (config.php file removed then regenerated)
return false;
}
} else {
// Token is not present (or invalid) in cookie
return false;
}
} else {
// Auth cookie is not present in headers
return false;
}
}
public function updateOnline()
{
// Define this if you want this visit to affect the online list and the users last visit data
if (!defined('FEATHER_QUIET_VISIT')) {
// Update the online list
if (!User::get()->logged) {
User::get()->logged = Container::get('now');
// With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
switch (ForumEnv::get('DB_TYPE')) {
case 'mysql':
case 'mysqli':
case 'mysql_innodb':
case 'mysqli_innodb':
case 'sqlite':
case 'sqlite3':
DB::table('online')->rawExecute('REPLACE INTO '.ForumEnv::get('DB_PREFIX').'online (user_id, ident, logged) VALUES(:user_id, :ident, :logged)', [':user_id' => User::get()->id, ':ident' => User::get()->username, ':logged' => User::get()->logged]);
break;
default:
DB::table('online')->rawExecute('INSERT INTO '.ForumEnv::get('DB_PREFIX').'online (user_id, ident, logged) SELECT :user_id, :ident, :logged WHERE NOT EXISTS (SELECT 1 FROM '.ForumEnv::get('DB_PREFIX').'online WHERE user_id=:user_id)', [':user_id' => User::get()->id, ':ident' => User::get()->username, ':logged' => User::get()->logged]);
break;
}
// Reset tracked topics
Track::setTrackedTopics(null);
} else {
// Special case: We've timed out, but no other user has browsed the forums since we timed out
if (User::get()->logged < (Container::get('now')-ForumSettings::get('o_timeout_visit'))) {
DB::table('users')->where('id', User::get()->id)
->findOne()
->set('last_visit', User::get()->logged)
->save();
User::get()->last_visit = User::get()->logged;
}
$idle_sql = (User::get()->idle == '1') ? ', idle=0' : '';
DB::table('online')->rawExecute('UPDATE '.ForumEnv::get('DB_PREFIX').'online SET logged='.Container::get('now').$idle_sql.' WHERE user_id=:user_id', [':user_id' => User::get()->id]);
// Update tracked topics with the current expire time
$cookie_tracked_topics = Container::get('cookie')->get(ForumEnv::get('COOKIE_NAME').'_track');
if (isset($cookie_tracked_topics)) {
Track::setTrackedTopics(json_decode($cookie_tracked_topics, true));
}
}
} else {
if (!User::get()->logged) {
User::get()->logged = User::get()->last_visit;
}
}
}
public function updateUsersOnline()
{
// Fetch all online list entries that are older than "o_timeout_online"
$select_update_users_online = ['user_id', 'ident', 'logged', 'idle'];
$result = DB::table('online')
->selectMany($select_update_users_online)
->whereLt('logged', Container::get('now')-ForumSettings::get('o_timeout_online'))
->findMany();
foreach ($result as $cur_user) {
// If the entry is a guest, delete it
if ($cur_user['user_id'] == '1') {
DB::table('online')->where('ident', $cur_user['ident'])
->deleteMany();
} else {
// If the entry is older than "o_timeout_visit", update last_visit for the user in question, then delete him/her from the online list
if ($cur_user['logged'] < (Container::get('now')-ForumSettings::get('o_timeout_visit'))) {
DB::table('users')->where('id', $cur_user['user_id'])
->findOne()
->set('last_visit', $cur_user['logged'])
->save();
DB::table('online')->where('user_id', $cur_user['user_id'])
->deleteMany();
} elseif ($cur_user['idle'] == '0') {
DB::table('online')->where('user_id', $cur_user['user_id'])
->updateMany('idle', 1);
}
}
}
}
public function checkBans()
{
// Admins and moderators aren't affected
if (User::isAdminMod() || !Container::get('bans')) {
return;
}
// Add a dot or a colon (depending on IPv4/IPv6) at the end of the IP address to prevent banned address
// 192.168.0.5 from matching e.g. 192.168.0.50
$user_ip = Utils::getIp();
$user_ip .= (strpos($user_ip, '.') !== false) ? '.' : ':';
$bans_altered = false;
$is_banned = false;
foreach (Container::get('bans') as $cur_ban) {
// Has this ban expired?
if ($cur_ban['expire'] != '' && $cur_ban['expire'] <= time()) {
DB::table('bans')->where('id', $cur_ban['id'])
->deleteMany();
$bans_altered = true;
continue;
}
if ($cur_ban['username'] != '' && \utf8\to_lower(User::get()->username) == \utf8\to_lower($cur_ban['username'])) {
$is_banned = true;
}
if ($cur_ban['ip'] != '') {
$cur_ban_ips = explode(' ', $cur_ban['ip']);
$num_ips = count($cur_ban_ips);
for ($i = 0; $i < $num_ips; ++$i) {
// Add the proper ending to the ban
if (strpos($user_ip, '.') !== false) {
$cur_ban_ips[$i] = $cur_ban_ips[$i].'.';
} else {
$cur_ban_ips[$i] = $cur_ban_ips[$i].':';
}
if (substr($user_ip, 0, strlen($cur_ban_ips[$i])) == $cur_ban_ips[$i]) {
$is_banned = true;
break;
}
}
}
if ($is_banned) {
DB::table('online')
->where('ident', User::get()->username)
->deleteMany();
throw new Error(__('Ban message').' '.(($cur_ban['expire'] != '') ? __('Ban message 2').' '.strtolower(Utils::formatTime($cur_ban['expire'], true)).'. ' : '').(($cur_ban['message'] != '') ? __('Ban message 3').'<br /><br /><strong>'.Utils::escape($cur_ban['message']).'</strong><br /><br />' : '<br /><br />').__('Ban message 4').' <a href="mailto:'.Utils::escape(ForumSettings::get('o_admin_email')).'">'.Utils::escape(ForumSettings::get('o_admin_email')).'</a>.', 403, false, true);
}
}
// If we removed any expired bans during our run-through, we need to regenerate the bans cache
if ($bans_altered) {
CacheInterface::store('bans', Cache::getBans());
}
}
public function maintenanceMessage()
{
// Admins and moderators aren't affected
if (User::isAdminMod()) {
return;
}
// Deal with newlines, tabs and multiple spaces
$pattern = ["\t", ' ', ' '];
$replace = ['    ', '  ', '  '];
$message = str_replace($pattern, $replace, ForumSettings::get('o_maintenance_message'));
if (ForumSettings::get('o_maintenance') == 1) {
throw new Error($message, 403, false, true);
}
}
private function loadDefaultUser()
{
$user = AuthModel::loadUser(1);
$user->is_guest = true;
$user->is_admmod = false;
return $user;
}
/**
* @param $req
* @param $res
* @param $next
* @return mixed
*/
public function __invoke($req, $res, $next)
{
$authCookie = Container::get('cookie')->get(ForumEnv::get('COOKIE_NAME'));
$jwt = false;
try {
$jwt = $this->getCookieData($authCookie);
} catch (\Exception $e) {
$user = $this->loadDefaultUser();
// Add $user as guest to DIC
Container::set('user', $user);
}
if ($jwt && $user = AuthModel::loadUser($jwt->data->userId)) {
// Load permissions and preferences for logged user
Perms::getUserPermissions($user);
$user->prefs = Prefs::loadPrefs($user);
$expires = ($jwt->exp > Container::get('now') + ForumSettings::get('o_timeout_visit')) ? Container::get('now') + 1209600 : Container::get('now') + ForumSettings::get('o_timeout_visit');
$user->is_guest = false;
if (!is_dir(ForumEnv::get('FEATHER_ROOT').'featherbb/lang/'.$user->prefs['language'])) {
Prefs::setUser($user, ['language' => ForumSettings::get('language')]);
}
if (!file_exists(ForumEnv::get('FEATHER_ROOT').'style/themes/'.$user->prefs['style'].'/style.css')) {
Prefs::setUser($user, ['style' => ForumSettings::get('style')]);
}
// Add user to DIC
Container::set('user', $user);
// Refresh cookie to avoid re-logging between idle
$jwt = AuthModel::generateJwt($user, $expires);
AuthModel::setCookie('Bearer '.$jwt, $expires);
$this->updateOnline();
} else {
$user = $this->loadDefaultUser();
// Update online list
if (!$user->logged) {
$user->logged = time();
// With MySQL/MySQLi/SQLite, REPLACE INTO avoids a user having two rows in the online table
switch (ForumEnv::get('DB_TYPE')) {
case 'mysql':
case 'mysqli':
case 'mysql_innodb':
case 'mysqli_innodb':
case 'sqlite':
case 'sqlite3':
DB::table('online')->rawExecute('REPLACE INTO '.ForumEnv::get('DB_PREFIX').'online (user_id, ident, logged) VALUES(1, :ident, :logged)', [':ident' => Utils::getIp(), ':logged' => $user->logged]);
break;
default:
DB::table('online')->rawExecute('INSERT INTO '.ForumEnv::get('DB_PREFIX').'online (user_id, ident, logged) SELECT 1, :ident, :logged WHERE NOT EXISTS (SELECT 1 FROM '.ForumEnv::get('DB_PREFIX').'online WHERE ident=:ident)', [':ident' => Utils::getIp(), ':logged' => $user->logged]);
break;
}
} else {
DB::table('online')->where('ident', Utils::getIp())
->updateMany('logged', time());
}
// Load permissions and preferences for guest user
Perms::getUserPermissions($user);
$user->prefs = Prefs::loadPrefs($user);
// Add $user as guest to DIC
Container::set('user', $user);
}
Lang::load('common');
// Load bans from cache
if (!CacheInterface::isCached('bans')) {
CacheInterface::store('bans', Cache::getBans());
}
// Add bans to the container
Container::set('bans', CacheInterface::retrieve('bans'));
// load theme assets, also set setStyle, also init template engine, also load template config
Container::get('template')->setStyle($user->prefs['style']);
// Check if current user is banned
$this->checkBans();
// Check if we have to display the maintenance message
$this->maintenanceMessage();
// Update online list
$this->updateUsersOnline();
return $next($req, $res);
}
}