<?php

namespace Modules\Auth\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Auth as AuthConfig;
use Modules\Auth\Models\UserSessionModel;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();
        $config  = config('Auth');

        if (! $session->get('isLoggedIn')) {
            $session->setFlashdata('error', 'Please log in to continue.');

            return redirect()->to($config->loginUrl);
        }

        // Idle timeout.
        $lastActivity = (int) $session->get('last_activity');
        if ($config->sessionIdleTimeoutMinutes > 0 && $lastActivity && (time() - $lastActivity) > ($config->sessionIdleTimeoutMinutes * 60)) {
            $session->destroy();
            $session->setFlashdata('error', 'Your session expired due to inactivity. Please log in again.');

            return redirect()->to($config->loginUrl);
        }

        // Confirm the tracked session row hasn't been revoked (e.g. via
        // "Force logout other devices" from another tab/device).
        $token = $session->get('session_token');
        if ($token) {
            $sessions = new UserSessionModel();
            if ($sessions->isRevoked($token)) {
                $session->destroy();
                $session->setFlashdata('error', 'You were signed out remotely. Please log in again.');

                return redirect()->to($config->loginUrl);
            }
            $sessions->touch($token);
        }

        $session->set('last_activity', time());
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Nothing to do after the response for this filter.
    }
}
