WizdomWeb/app/Utilities/HoneypotHelper.php

74 lines
1.9 KiB
PHP

<?php
/**
* File: HoneypotHelper.php
* Version: 1.0
* Path: /app/Utilities/HoneypotHelper.php
* Purpose: Provides honeypot-based bot protection with JS-injected token verification.
* Project: Wizdom Networks Website
*/
namespace WizdomNetworks\WizeWeb\Utilities;
class HoneypotHelper
{
const SESSION_KEY = 'wiz_hpt';
const FIELD_NAME = 'wiz_hpt';
/**
* Start session if needed and generate a honeypot token.
*/
public static function generate(): void
{
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION[self::SESSION_KEY])) {
$_SESSION[self::SESSION_KEY] = bin2hex(random_bytes(16));
}
}
/**
* Return the current honeypot token from the session.
*
* @return string|null
*/
public static function getToken(): ?string
{
return $_SESSION[self::SESSION_KEY] ?? null;
}
/**
* Validate the submitted honeypot token and invalidate it after use.
*
* @param string|null $submitted
* @return bool
*/
public static function validate(?string $submitted): bool
{
$expected = $_SESSION[self::SESSION_KEY] ?? null;
unset($_SESSION[self::SESSION_KEY]);
if (!$expected || !$submitted || $submitted !== $expected) {
Logger::warning("Honeypot validation failed. Expected: $expected, Got: $submitted");
return false;
}
return true;
}
/**
* Output the HTML for the honeypot field.
*
* @return string
*/
public static function renderField(): string
{
return sprintf(
'<input type="text" name="%s" id="%s" class="form-control" required style="position: absolute; left: -9999px;" tabindex="-1" autocomplete="off">',
self::FIELD_NAME,
self::FIELD_NAME
);
}
}