Allow overwriting config options with environment variables.
Allow overwriting config options with environment variables.
<?php
include_once "vendor/autoload.php";
use OTPHP\TOTP;
function load_config($file) {
$json = file_get_contents($file);
if ($json === FALSE) die("Error reading config file $file\n");
$config = json_decode($json);
if (!is_object($config)) die("Bad config file $file\n");
return $config;
}
$lockfile = fopen(__FILE__, 'r');
if ($lockfile === FALSE) die("Cannot open lock file\n");
if (!flock($lockfile, LOCK_EX)) die("Cannot acquire exclisive lock\n");
$options = getopt("c:");
$config = load_config(@$options['c']);
$config_default = load_config(__DIR__.'/config_default.json');
foreach($config_default as $k => $v) if (!isset($config->{$k})) $config->{$k} = $v;
if (!preg_match('/^[A-Z2-7]+$/i', $config->secret)) die("Base32 encoded secret required\n");
$totp = new TOTP(null, $config->secret, $config->period, $config->digest, $config->digits);
while(true) {
echo "Czas serwera: ";
$now = new DateTime();
echo $now->format('Y-m-d H:i:s');
echo "\n";
echo "Podaj kod:\n";
$code = readline();
$verify_result = $totp->verify($code, null, $config->window);
sleep($config->delay);
if ($verify_result) {
break;
} else {
echo "Zły kod\n";
echo "Spróbuj ponownie\n";
}
}
fclose($lockfile);
$cmd = getenv('SSH_ORIGINAL_COMMAND');
if ($cmd !== FALSE) passthru($cmd);
else passthru(getenv('SHELL').' -');