1:  2:  3:  4:  5:  6:  7:  8:  9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 
<?php

declare(strict_types=1);

namespace Wtf\Auth\Storage;

use Wtf\Root;

class JWT extends Root implements StorageInterface
{
    /**
     * {@inheritdoc}
     */
    public function setUser(Root $user)
    {
        //@codeCoverageIgnoreStart
        if (!\class_exists(\Firebase\JWT\JWT::class)) {
            throw new \Exception('wtf/auth jwt storage requires wtf/rest or firebase/php-jwt packages installed');
        }
        //@codeCoverageIgnoreEnd
        $data = $user->getData();
        if ($data['password'] ?? null) {
            unset($data['password']);
        }

        return \Firebase\JWT\JWT::encode([
            'jti' => $user->getId().\time().\random_int(PHP_INT_MIN, PHP_INT_MAX),
            'iat' => $this->config('jwt.iat', \time()),
            'nbf' => $this->config('jwt.nbf', \time()),
            'iss' => $this->config('jwt.iss', \getenv('APP_HOST')),
            'aud' => $this->config('jwt.aud', \getenv('APP_HOST')),
            'exp' => $this->config('jwt.exp', \time() + 604800),
            'data' => $data,
        ], \getenv('APP_SECRET'), $this->config('jwt.algorithm', ['HS256'])[0]);
    }

    /**
     * {@inheritdoc}
     */
    public function getUser(): ?Root
    {
        //@codeCoverageIgnoreStart
        if (!\class_exists(\Firebase\JWT\JWT::class)) {
            throw new \Exception('wtf/auth jwt storage requires wtf/rest or firebase/php-jwt packages installed');
        }
        //@codeCoverageIgnoreEnd

        if ($token = $this->request->getAttribute($this->config('jwt.attribute', 'token'))) {
            $data = (array) (\is_object($token) && \property_exists($token, 'data') ? $token->data : ($token['data'] ?? $token));

            return $this->entity($this->config('auth.entity'))->setData($data);
        }

        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function isLoggedIn(): bool
    {
        return (bool) $this->getUser();
    }

    /**
     * {@inheritdoc}
     */
    public function logout(): void
    {
        //nothing to do here
    }
}