<?php

namespace pictpostpersonal\controller\middleware;

use pictpostpersonal\controller\ControllerBase;

use pictpostpersonal\CsrfUtility;
use pictpostpersonal\Result;
use pictpostpersonal\Request;


/**
 *  CSRFトークン確認用ミドルウェア
 *  CSRFトークが無効な場合処理を終了する
 */
class CSRFMiddleware extends ControllerBase
{
    function CSRFCheck(Request $req): ?Result
    {

        $token = $req->getArgs('csrf_token', '');
        if ($token == '' && isset($_SERVER['HTTP_X_CSRF_TOKEN'])) {
            $token = $_SERVER['HTTP_X_CSRF_TOKEN'];
        }

        if (!CsrfUtility::checkCSRFToken($token)) {
            $result = new Result();
            $result->next = false;
            $result->status = 403; //Forbidden
            $result->output = 'CSRFトークンが無効です';
            return $result;
        }
        return null;
    }
}
