CoreFiles by mySites.guru
PreviewTokenService.php156 lines, 3,910 bytes, from Joomla_6.2.0-beta1-Beta-Full_Package.zip
Raw History Compare with 6.1.0-beta3
md5
3192e82803f0cb682203cb22426dd1d2
sha1
a19ccda326b073a5e6399e80fd5cb059ee803f23
sha256
58b55d7d706907b5bcf4b37f788421e07a82b78f42d09474dfa17203b2c35046
<?php

/**
 * @package         Joomla.Administrator
 * @subpackage      com_content
 *
 * @copyright       (C) 2026 Open Source Matters, Inc. <https://www.joomla.org>
 * @license         GNU General Public License version 2 or later; see LICENSE.txt
 */

namespace Joomla\Component\Content\Administrator\Service;

// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects

/**
 * Service class for generating and validating article preview tokens.
 *
 * Tokens are URL-safe, HMAC-SHA256 signed, and time-limited.
 * They allow unauthenticated public access to article previews without
 * requiring a frontend login or published state.
 *
 * Usage:
 *   $helper = new PreviewTokenService($app->get('secret'));
 *   $token  = $helper->createToken($articleId, 24);
 *   $valid  = $helper->validateToken($token, $articleId);
 *
 * @since  6.2.0
 */
class PreviewTokenService
{
    /**
     * The secret key used to sign and verify preview tokens.
     *
     * @var string
     */
    private string $secret;

    /**
     * @param   string  $secret  The secret key
     *
     * @since   6.2.0
     */
    public function __construct(string $secret)
    {
        $this->secret = $secret;
    }

    /**
     * Generate a signed preview token for a given article.
     *
     * @param   int  $id                The article ID.
     * @param   int  $expiresInMinutes  Number of minutes before the token expires.
     *
     * @return  string
     *
     * @since   6.2.0
     */
    public function createToken(int $id, int $expiresInMinutes): string
    {
        $payload = $this->encode(json_encode([
            'id'  => $id,
            'exp' => time() + ($expiresInMinutes * 60),
        ]));

        $signature = $this->encode(hash_hmac('sha256', $payload, $this->secret, true));

        return $payload . '.' . $signature;
    }

    /**
     * Validate a preview token against a given article ID.
     *
     * Checks that the token:
     * - Has a valid structure
     * - Has not been tampered with (HMAC signature check)
     * - Has not expired
     * - Belongs to the expected article
     *
     * @param   string  $token  The preview token from the URL.
     * @param   int     $id     The expected article ID.
     *
     * @return  bool
     *
     * @since   6.2.0
     */
    public function validateToken(string $token, int $id): bool
    {
        $parts = explode('.', $token);

        if (\count($parts) !== 2) {
            return false;
        }

        [$payload, $signature] = $parts;

        if (!hash_equals($this->encode(hash_hmac('sha256', $payload, $this->secret, true)), $signature)) {
            return false;
        }

        $decoded = $this->decode($payload);

        if ($decoded === false) {
            return false;
        }

        $data = json_decode($decoded, true);

        if (!\is_array($data) || !isset($data['id'], $data['exp'])) {
            return false;
        }

        if (!\is_int($data['id']) || !\is_int($data['exp'])) {
            return false;
        }

        if ($data['id'] !== $id) {
            return false;
        }

        return time() < $data['exp'];
    }

    /**
     * Encode binary data to URL-safe Base64 string.
     *
     * @param   string  $data
     *
     * @return  string
     *
     * @since   6.2.0
     */
    private function encode(string $data): string
    {
        return str_replace('=', '', strtr(base64_encode($data), '+/', '-_'));
    }

    /**
     * Decode a URL-safe Base64 string to binary data.
     *
     * @param   string  $data
     *
     * @return  string|false
     *
     * @since   6.2.0
     */
    private function decode(string $data): string|false
    {
        if ($remainder = \strlen($data) % 4) {
            $data .= str_repeat('=', 4 - $remainder);
        }

        return base64_decode(strtr($data, '-_', '+/'));
    }
}

No other release has this exact content. See every version of this file.