Last commit for auth.php: ea14716333dc0729842ce07a574bb168a580d89b

Allow overwriting config options with environment variables.

Piotr Pawlow [2017-03-19 21:08:31]
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:", [
  'secret:',
  'period:',
  'window:',
  'digest:',
  'digits:',
  'delay:'
]);
if (isset($options['c'])) $config = load_config($options['c']); else $config = new stdClass();
$config_default = load_config(__DIR__.'/config_default.json');

foreach($config_default as $k => $v) if (!isset($config->{$k})) $config->{$k} = $v;
foreach($options as $k => $v) if ($k !== 'c') $config->{$k} = $v;

$config->secret = strtr($config->secret, [' ' => '']);
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').' -');
ViewGit