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");

$config_options = ['secret', 'period', 'window', 'digest', 'digits', 'delay'];
$options = getopt("c:e::", array_map(function($e){return "$e:";}, $config_options));
if (isset($options['secret'])) echo "!!! PODAWANIE SEKRETU JAKO ARGUMENT NIE JEST BEZPIECZNE !!!\n";
if (isset($options['c'])) $config = load_config($options['c']); else $config = new stdClass();
$config_default = load_config(__DIR__.'/config_default.json');

foreach($config_options as $opt) {
  if (isset($options[$opt])) {
    $config->{$opt} = $options[$opt];
    continue;
  }
  if (isset($options['e'])) {
    $env_k = 'TOTP_'.strtoupper($opt);
    $env_v = getenv($env_k);
    if ($env_v !== FALSE) {
      $config->{$opt} = $env_v;
      putenv($env_k);
      continue;
    }
  }
  if (!isset($config->{$opt})) $config->{$opt} = $config_default->{$opt};
}

$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