master

laravel/framework

Last updated at: 29/12/2023 09:23

MaintenanceModeBypassCookie.php

TLDR

This file contains the MaintenanceModeBypassCookie class, which is responsible for creating and validating maintenance mode bypass cookies.

Methods

create

This method creates a new maintenance mode bypass cookie. It takes a string $key parameter and returns an instance of the Symfony\Component\HttpFoundation\Cookie class.

isValid

This method determines if a given maintenance mode bypass cookie is valid. It takes two string parameters: $cookie, which represents the cookie value, and $key, which is used for verification. It returns a boolean value indicating whether the cookie is valid or not.

<?php

namespace Illuminate\Foundation\Http;

use Illuminate\Support\Carbon;
use Symfony\Component\HttpFoundation\Cookie;

class MaintenanceModeBypassCookie
{
    /**
     * Create a new maintenance mode bypass cookie.
     *
     * @param  string  $key
     * @return \Symfony\Component\HttpFoundation\Cookie
     */
    public static function create(string $key)
    {
        $expiresAt = Carbon::now()->addHours(12);

        return new Cookie('laravel_maintenance', base64_encode(json_encode([
            'expires_at' => $expiresAt->getTimestamp(),
            'mac' => hash_hmac('sha256', $expiresAt->getTimestamp(), $key),
        ])), $expiresAt, config('session.path'), config('session.domain'));
    }

    /**
     * Determine if the given maintenance mode bypass cookie is valid.
     *
     * @param  string  $cookie
     * @param  string  $key
     * @return bool
     */
    public static function isValid(string $cookie, string $key)
    {
        $payload = json_decode(base64_decode($cookie), true);

        return is_array($payload) &&
            is_numeric($payload['expires_at'] ?? null) &&
            isset($payload['mac']) &&
            hash_equals(hash_hmac('sha256', $payload['expires_at'], $key), $payload['mac']) &&
            (int) $payload['expires_at'] >= Carbon::now()->getTimestamp();
    }
}