<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\PreventRequestForgery as Middleware;
use Illuminate\Http\Request;

class ForceCsrfOnLocalhost extends Middleware
{
    /**
     * Determine if the request has a valid origin based on the Sec-Fetch-Site header.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function hasValidOrigin($request)
    {
        // If it's localhost, we want to skip origin verification and fall back to token verification
        if ($this->isLocalhost($request)) {
            return false;
        }

        return parent::hasValidOrigin($request);
    }

    /**
     * Determine if the request is from localhost.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return bool
     */
    protected function isLocalhost($request)
    {
        $host = $request->getHost();

        return in_array($host, ['localhost', '127.0.0.1', '::1']) || str_ends_with($host, '.localhost');
    }
}
