58 lines
1.5 KiB
PHP
Executable File
58 lines
1.5 KiB
PHP
Executable File
<?php
|
|
|
|
namespace Modules\M3\Http\Middleware;
|
|
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class BasicAuth
|
|
{
|
|
public function handle(Request $request, Closure $next): mixed
|
|
{
|
|
$login = trim((string) m3_user());
|
|
$password = (string) m3_legacy_password();
|
|
|
|
if ($login !== '' && $this->checkPassword($login, $password, '%%SYSTEM%%')) {
|
|
return $next($request);
|
|
}
|
|
|
|
return $this->unauthorized();
|
|
}
|
|
|
|
private function checkPassword(string $login, string $password, string $passwordFile): bool
|
|
{
|
|
if (! is_readable($passwordFile)) {
|
|
return false;
|
|
}
|
|
|
|
$handle = fopen($passwordFile, 'rb');
|
|
if ($handle === false) {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
while (($line = fgets($handle)) !== false) {
|
|
$parts = explode(':', trim($line), 2);
|
|
if (count($parts) !== 2 || ! hash_equals($parts[0], $login)) {
|
|
continue;
|
|
}
|
|
|
|
$storedHash = trim($parts[1]);
|
|
|
|
return $storedHash !== '' && password_verify($password, $storedHash);
|
|
}
|
|
} finally {
|
|
fclose($handle);
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private function unauthorized(): Response
|
|
{
|
|
return response('INVALID USERNAME OR PASSWORD. ACCESS DENIED', 401)
|
|
->header('WWW-Authenticate', 'Basic realm="RESTRICTED ACCESS"');
|
|
}
|
|
}
|