Newer
Older
gnexus-auth-client-php / examples / plain-php / stores.php
@Eugene Sukhodolskiy Eugene Sukhodolskiy 12 hours ago 2 KB Initial auth client package scaffold
<?php

declare(strict_types=1);

use GNexus\GAuth\Contract\PkceStoreInterface;
use GNexus\GAuth\Contract\StateStoreInterface;

final class SessionStateStore implements StateStoreInterface
{
    public function put(string $state, DateTimeImmutable $expiresAt, array $context = []): void
    {
        $_SESSION['gauth_state'][$state] = [
            'expires_at' => $expiresAt->format(DateTimeInterface::ATOM),
            'context' => $context,
        ];
    }

    public function has(string $state): bool
    {
        $record = $_SESSION['gauth_state'][$state] ?? null;

        if (! is_array($record)) {
            return false;
        }

        if (new DateTimeImmutable($record['expires_at']) < new DateTimeImmutable()) {
            unset($_SESSION['gauth_state'][$state]);

            return false;
        }

        return true;
    }

    public function getContext(string $state): array
    {
        if (! $this->has($state)) {
            return [];
        }

        return $_SESSION['gauth_state'][$state]['context'] ?? [];
    }

    public function forget(string $state): void
    {
        unset($_SESSION['gauth_state'][$state]);
    }
}

final class SessionPkceStore implements PkceStoreInterface
{
    public function put(string $state, string $verifier, DateTimeImmutable $expiresAt): void
    {
        $_SESSION['gauth_pkce'][$state] = [
            'verifier' => $verifier,
            'expires_at' => $expiresAt->format(DateTimeInterface::ATOM),
        ];
    }

    public function get(string $state): ?string
    {
        $record = $_SESSION['gauth_pkce'][$state] ?? null;

        if (! is_array($record)) {
            return null;
        }

        if (new DateTimeImmutable($record['expires_at']) < new DateTimeImmutable()) {
            unset($_SESSION['gauth_pkce'][$state]);

            return null;
        }

        return isset($record['verifier']) ? (string) $record['verifier'] : null;
    }

    public function forget(string $state): void
    {
        unset($_SESSION['gauth_pkce'][$state]);
    }
}