<?php

namespace Velis\Mvc\Controller\RestRequestHandler;

use Phalcon\Http\RequestInterface;
use Velis\App;
use Velis\Lang;
use Velis\Mvc\Controller\Exception\ForbiddenException;

class VerifyCsrfToken extends AbstractRestRequestHandler
{
    private const CSRF_PROTECTED_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];

    public function handle(RequestInterface $request): void
    {
        if (in_array($request->getMethod(), self::CSRF_PROTECTED_METHODS)) {
            if ($request->getHeader('X-CSRF-TOKEN') != App::$session->csrfToken) {
                $message = Lang::get('GENERAL_ACCESS_DENIED');

                if ($_SERVER['ON_DEV']) {
                    $message .= ' - token mismatch';
                }

                throw new ForbiddenException($message);
            }
        }

        $this->handleNext($request);
    }
}
