~thirdplace/components

e4375d03c6c3f9f14b52751e262428494e3812db — Dag 2 years ago ae9aa50
fix: move out csrf mw
1 files changed, 0 insertions(+), 40 deletions(-)

D src/CsrfMiddleware.php
D src/CsrfMiddleware.php => src/CsrfMiddleware.php +0 -40
@@ 1,40 0,0 @@
<?php
declare(strict_types=1);

namespace Thirdplace;

final class CsrfMiddleware
{
	public function __invoke(Request $request): Request
    {
        if ($request->isPost()) {
            $tokenFromRequest = $request->post('csrf', [], true);

            if (!$tokenFromRequest) {
                throw new \Exception('Missing token from request');
            }
            if (!isset($tokenFromRequest['key'])) {
                throw new \Exception('Missing token key from request');
            }

            $tokenFromSession = $_SESSION['thirdplace'][$tokenFromRequest['key']] ?? null;

            if (!$tokenFromSession) {
                throw new \Exception('Unknown token key');
            }

            if (! hash_equals($tokenFromRequest['value'], $tokenFromSession['value'])) {
                throw new \Exception('Token mismatch');
            }
        }

        $token = [
            'key'   => sprintf('csrf_key_%s',   bin2hex(random_bytes(16))),
            'value' => sprintf('csrf_value_%s', bin2hex(random_bytes(16))),
        ];

        $_SESSION['thirdplace'][$token['key']] = $token;

        return $request->withAttribute('csrf', $token);
    }
}
\ No newline at end of file