innhold/custom/tools/set-publiser-password.php

58 lines
1.6 KiB
PHP
Raw Normal View History

#!/usr/bin/env php
<?php
/**
* Set or reset the Basic Auth login for /publiser.
*
* Writes a bcrypt-hashed .htpasswd file (no dependency on the `htpasswd`
* binary being installed - Apache's mod_authn_file accepts $2y$ hashes).
*
* Usage:
* php custom/tools/set-publiser-password.php <username> <password>
* php custom/tools/set-publiser-password.php (interactive)
*/
$htpasswdPath = dirname(__DIR__, 2) . '/content/publiser/.htpasswd';
function prompt(string $question): string {
echo $question;
return trim(fgets(STDIN));
}
function promptHidden(string $question): string {
$isWindows = stripos(PHP_OS, 'WIN') === 0;
if (!$isWindows) {
system('stty -echo');
}
$value = prompt($question);
if (!$isWindows) {
system('stty echo');
echo "\n";
}
return $value;
}
$args = array_slice($argv, 1);
$username = $args[0] ?? prompt('Username: ');
$password = $args[1] ?? promptHidden('Password: ');
if ($username === '' || $password === '') {
fwrite(STDERR, "Username and password are required.\n");
exit(1);
}
if (str_contains($username, ':')) {
fwrite(STDERR, "Username cannot contain ':'.\n");
exit(1);
}
$hash = password_hash($password, PASSWORD_BCRYPT);
file_put_contents($htpasswdPath, "$username:$hash\n");
// World-readable: the web server user (www-data, varies by host/container)
// needs read access. This is safe - Apache denies direct HTTP access to
// this exact filename (content/publiser/.htaccess), and reaching it any
// other way already requires shell/filesystem access to the server.
chmod($htpasswdPath, 0644);
echo "Wrote $htpasswdPath for user \"$username\".\n";