forked from laysense/laysense.cn
53 lines
1.5 KiB
PHP
53 lines
1.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
require dirname(__DIR__) . '/vendor/autoload.php';
|
|
|
|
use App\Content\Database;
|
|
use App\Content\Passwords;
|
|
use App\Content\Repository;
|
|
|
|
$reset = ($argv[1] ?? '') === 'reset';
|
|
$email = strtolower(trim($argv[$reset ? 2 : 1] ?? ''));
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
fwrite(STDERR, "用法:php bin/admin.php [reset] admin@example.com\n");
|
|
exit(1);
|
|
}
|
|
|
|
fwrite(STDERR, "请输入至少 8 字符的管理员密码:");
|
|
$tty = function_exists('stream_isatty') && stream_isatty(STDIN);
|
|
if ($tty) {
|
|
exec('stty -echo');
|
|
}
|
|
try {
|
|
$password = rtrim((string) fgets(STDIN), "\r\n");
|
|
} finally {
|
|
if ($tty) {
|
|
exec('stty echo');
|
|
}
|
|
fwrite(STDERR, "\n");
|
|
}
|
|
if (!Passwords::isValidNew($password)) {
|
|
fwrite(STDERR, "密码至少 8 个字符,最多 72 字节。\n");
|
|
exit(1);
|
|
}
|
|
|
|
Database::initialize();
|
|
$hash = password_hash($password, PASSWORD_DEFAULT);
|
|
if ($reset) {
|
|
$repo = new Repository();
|
|
$user = $repo->administrator($email);
|
|
if (!$user || !$repo->changePassword($user, $hash)) {
|
|
fwrite(STDERR, "未能重设密码。请确认邮箱对应的账户存在,且未被同时修改。\n");
|
|
exit(1);
|
|
}
|
|
fwrite(STDOUT, "密码已重设,旧会话将失效。\n");
|
|
exit(0);
|
|
}
|
|
|
|
$query = Database::connect()->prepare('INSERT INTO users (email, password_hash) VALUES (?, ?)
|
|
ON CONFLICT (email) DO UPDATE SET password_hash = excluded.password_hash');
|
|
$query->execute([$email, $hash]);
|
|
fwrite(STDOUT, "管理员账户已就绪。\n");
|