|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Modules\Auth\Filters; |
| 4 | + |
| 5 | +use Modules\Auth\Models\UserSessionModel; |
| 6 | +use CodeIgniter\Filters\FilterInterface; |
| 7 | +use CodeIgniter\HTTP\RequestInterface; |
| 8 | +use CodeIgniter\HTTP\ResponseInterface; |
| 9 | + |
| 10 | +/** |
| 11 | + * Security and Tracking Filter: User Session Tracker |
| 12 | + * |
| 13 | + * Designed to track the real-time device information and connection durations |
| 14 | + * of logged-in users. It also synchronously prevents database-controlled (DB-Driven) |
| 15 | + * session termination (revocation) at the Filter level. |
| 16 | + */ |
| 17 | +class SessionTracker implements FilterInterface |
| 18 | +{ |
| 19 | + /** |
| 20 | + * Intercepts the request before it reaches the Controller. |
| 21 | + * Checks for a permanent "Device ID" (Tracker ID) belonging to the user, generates one if missing. |
| 22 | + * Uses this ID to verify the active status in the database; if inactive, terminates the process and logs the user out. |
| 23 | + * |
| 24 | + * @param RequestInterface $request Incoming HTTP Request |
| 25 | + * @param mixed $arguments Additional arguments |
| 26 | + * @return mixed |
| 27 | + */ |
| 28 | + public function before(RequestInterface $request, $arguments = null) |
| 29 | + { |
| 30 | + helper('device'); |
| 31 | + |
| 32 | + $userId = auth()->id(); |
| 33 | + |
| 34 | + if (! $userId) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + $session = session(); |
| 39 | + $sessionId = $session->get('ci4ms_session_tracker_id'); |
| 40 | + |
| 41 | + if (! $sessionId) { |
| 42 | + $sessionId = bin2hex(random_bytes(16)); |
| 43 | + $session->set('ci4ms_session_tracker_id', $sessionId); |
| 44 | + } |
| 45 | + |
| 46 | + $model = new UserSessionModel(); |
| 47 | + |
| 48 | + $exists = $model->where('session_id', $sessionId)->first(); |
| 49 | + |
| 50 | + if (! $exists) { |
| 51 | + $agent = $request->getUserAgent(); |
| 52 | + $deviceInfo = extract_device_info($agent); |
| 53 | + |
| 54 | + $model->recordLogin( |
| 55 | + userId: (int) $userId, |
| 56 | + sessionId: $sessionId, |
| 57 | + deviceInfo: $deviceInfo, |
| 58 | + ip: $request->getIPAddress() |
| 59 | + ); |
| 60 | + } else { |
| 61 | + // If the current device's session status in the database has been remotely set to "is_active = 0", |
| 62 | + // forces the visitor out of their current device. |
| 63 | + if ($exists['is_active'] == 0) { |
| 64 | + auth()->logout(); |
| 65 | + session()->destroy(); |
| 66 | + return redirect()->route('login')->with('error', lang('Users.currentSessionTerminated')); |
| 67 | + } |
| 68 | + |
| 69 | + $model->touchSession($sessionId); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) |
| 74 | + { |
| 75 | + // No further manipulation needed afterwards. |
| 76 | + } |
| 77 | +} |
0 commit comments