增加登录身份验证/解决权限无法撤销问题

develop
clumxc 4 months ago
parent 641f2caaeb
commit 07ade37d01

@ -0,0 +1,113 @@
<?php
require_once __DIR__ . '/../src/storage/UserRepository.php';
use MailServer\Storage\UserRepository;
session_start();
// 简单身份验证
if (!isset($_SESSION['admin_logged_in'])) {
header('Location: login.php');
exit;
}
$repo = new UserRepository();
$action = $_GET['action'] ?? '';
$message = '';
// 处理操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
switch ($_POST['action']) {
case 'create':
if ($repo->create($_POST['username'], $_POST['password'],
isset($_POST['is_admin']), $_POST['mailbox_size'])) {
$message = '用户创建成功';
}
break;
case 'toggle':
$repo->toggleActive($_POST['user_id'], $_POST['active']);
break;
case 'delete':
$repo->delete($_POST['user_id']);
break;
}
}
$users = $repo->getAll();
?>
<!DOCTYPE html>
<html>
<head>
<title>用户管理</title>
<style>
body { font-family: Arial; margin: 20px; }
.success { color: green; padding: 10px; background: #e8f5e8; }
table { border-collapse: collapse; width: 100%; margin: 20px 0; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background: #f5f5f5; }
.form-group { margin: 10px 0; }
input, select { padding: 5px; }
</style>
</head>
<body>
<h1> 邮件服务器用户管理</h1>
<?php if ($message): ?>
<div class="success"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>
<h2>创建新用户</h2>
<form method="POST">
<input type="hidden" name="action" value="create">
<div class="form-group">
<input type="email" name="username" placeholder="邮箱地址" required>
</div>
<div class="form-group">
<input type="password" name="password" placeholder="密码" required>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="is_admin"> 管理员
</label>
</div>
<div class="form-group">
<input type="number" name="mailbox_size" value="100" min="10" max="10240"> MB
</div>
<button type="submit">创建用户</button>
</form>
<h2>用户列表</h2>
<table>
<thead>
<tr>
<th>ID</th><th>邮箱</th><th>类型</th><th>状态</th><th>容量</th><th>创建时间</th><th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?php echo $user['id']; ?></td>
<td><?php echo htmlspecialchars($user['username']); ?></td>
<td><?php echo $user['is_admin'] ? '管理员' : '普通'; ?></td>
<td><?php echo $user['is_active'] ? '激活' : '禁用'; ?></td>
<td><?php echo $user['max_mailbox_size']; ?> MB</td>
<td><?php echo $user['created_at']; ?></td>
<td>
<form method="POST" style="display:inline;">
<input type="hidden" name="action" value="toggle">
<input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
<input type="hidden" name="active" value="<?php echo $user['is_active'] ? '0' : '1'; ?>">
<button type="submit"><?php echo $user['is_active'] ? '禁用' : '启用'; ?></button>
</form>
<form method="POST" style="display:inline;">
<input type="hidden" name="action" value="delete">
<input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
<button type="submit" onclick="return confirm('确定删除?')">删除</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>

@ -6,11 +6,13 @@ require_once __DIR__ . '/../src/utils/Security.php';
session_start();
// 简单身份验证
// 简单身份验证,检查用户是否已登录。如果未登录($_SESSION['user_id']不存在),则重定向到登录页面。
function requireAuth() {
if (!isset($_SESSION['user_id'])) {
header('Location: index.php');
exit;
if (basename($_SERVER['PHP_SELF']) !== 'index.php') {
header('Location: index.php');
exit;
}
}
}
@ -27,7 +29,7 @@ if (isset($_POST['login'])) {
$userRepo = new UserRepository();
$user = $userRepo->verifyPassword($username, $password);
if ($user && $user['is_active']) {
if ($user && $user['is_active'] && $user['is_admin']) {
// 登录成功,清除尝试记录
Security::clearLoginAttempts($username);
@ -36,7 +38,12 @@ if (isset($_POST['login'])) {
$_SESSION['is_admin'] = $user['is_admin'];
header('Location: index.php');
exit;
} else {
}else if($user && !$user['is_active']){
$error = "用户被禁用";
}else if($user && $user['is_active'] && !$user['is_admin']){
$error = "没有权限";
}
else{
// 登录失败,记录尝试
Security::recordLoginAttempt($username);
$error = "用户名或密码错误";
@ -53,6 +60,8 @@ if (basename($_SERVER['PHP_SELF']) === 'index.php' && !isset($_SESSION['user_id'
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>邮件服务器管理后台 - 登录</title>
<style>
body { font-family: Arial, sans-serif; max-width: 400px; margin: 50px auto; padding: 20px; }
@ -77,9 +86,6 @@ if (basename($_SERVER['PHP_SELF']) === 'index.php' && !isset($_SESSION['user_id'
</div>
<button type="submit" name="login">登录</button>
</form>
<p style="margin-top: 20px; font-size: 12px; color: #666; text-align: center;">
还没有账号?<a href="register.php" style="color: #007bff; text-decoration: none;">立即注册</a>
</p>
<p style="margin-top: 10px; font-size: 12px; color: #666;">
测试账号: admin@test.com / 123456<br>
普通账号: user1@test.com / 123456

@ -69,13 +69,18 @@ if (isset($_POST['update_user'])) {
}
}
if (isset($_POST['is_admin'])) {
/**if (isset($_POST['is_admin'])) {
$data['is_admin'] = (int)$_POST['is_admin'];
}
if (isset($_POST['is_active'])) {
$data['is_active'] = (int)$_POST['is_active'];
}
}**/
// 管理员权限总是更新
$data['is_admin'] = isset($_POST['is_admin']) ? 1 : 0;
// 激活状态也是
$data['is_active'] = isset($_POST['is_active']) ? 1 : 0;
if (empty($error) && !empty($data)) {
if ($userRepo->update($userId, $data)) {

@ -0,0 +1,196 @@
<?php
/**
* 邮件服务器管理工具 - 单文件版
* 用法: php admin_tool.php <命令> [参数...]
*/
// 加载配置和类
require_once __DIR__ . '/../config/database.php';
class AdminTool
{
private $db;
public function __construct()
{
$config = require __DIR__ . '/../config/database.php';
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']}";
$this->db = new PDO($dsn, $config['username'], $config['password'], $config['options']);
}
// 主入口
public function run($args)
{
if (count($args) < 2) {
$this->showHelp();
return;
}
$command = $args[1];
switch ($command) {
case 'list':
$this->listUsers();
break;
case 'create':
$this->createUser($args);
break;
case 'enable':
case 'disable':
$this->toggleUser($args, $command === 'enable');
break;
case 'delete':
$this->deleteUser($args);
break;
case 'help':
default:
$this->showHelp();
}
}
// 显示用户列表
private function listUsers()
{
$stmt = $this->db->query("
SELECT id, username, is_admin, is_active, max_mailbox_size, created_at
FROM users ORDER BY id
");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($users)) {
echo "暂无用户\n";
return;
}
echo "📋 用户列表 (" . count($users) . " 位)\n";
echo str_repeat("=", 70) . "\n";
foreach ($users as $user) {
printf("ID: %-4d | 邮箱: %-25s | 类型: %-6s | 状态: %-4s | 容量: %dMB | 创建: %s\n",
$user['id'],
$user['username'],
$user['is_admin'] ? '管理员' : '普通',
$user['is_active'] ? '激活' : '禁用',
$user['max_mailbox_size'],
$user['created_at']
);
}
}
// 创建用户
private function createUser($args)
{
if (count($args) < 4) {
echo "❌ 用法: php admin_tool.php create <邮箱> <密码> [管理员=0] [容量=100]\n";
echo " 示例: php admin_tool.php create user@test.com pass123 1 200\n";
return;
}
$username = $args[2];
$password = $args[3];
$isAdmin = isset($args[4]) ? (bool)$args[4] : false;
$mailboxSize = isset($args[5]) ? (int)$args[5] : 100;
// 检查用户是否存在
$check = $this->db->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
$check->execute([$username]);
if ($check->fetchColumn() > 0) {
echo "❌ 用户 {$username} 已存在\n";
return;
}
// 创建用户
$stmt = $this->db->prepare("
INSERT INTO users (username, password_hash, is_admin, max_mailbox_size)
VALUES (?, ?, ?, ?)
");
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$success = $stmt->execute([$username, $hashedPassword, $isAdmin ? 1 : 0, $mailboxSize]);
if ($success) {
echo "✅ 用户创建成功: {$username}\n";
echo " 类型: " . ($isAdmin ? "管理员" : "普通用户") . "\n";
echo " 邮箱容量: {$mailboxSize}MB\n";
} else {
echo "❌ 创建失败\n";
}
}
// 启用/禁用用户
private function toggleUser($args, $enable)
{
if (count($args) < 3) {
echo "❌ 用法: php admin_tool.php " . ($enable ? "enable" : "disable") . " <用户ID>\n";
echo " 示例: php admin_tool.php " . ($enable ? "enable" : "disable") . " 2\n";
return;
}
$userId = (int)$args[2];
$status = $enable ? 1 : 0;
$action = $enable ? "启用" : "禁用";
$stmt = $this->db->prepare("UPDATE users SET is_active = ? WHERE id = ?");
$success = $stmt->execute([$status, $userId]);
if ($success && $stmt->rowCount() > 0) {
echo "✅ 用户 ID {$userId} 已{$action}\n";
} else {
echo "❌ 操作失败(用户可能不存在)\n";
}
}
// 删除用户
private function deleteUser($args)
{
if (count($args) < 3) {
echo " 用法: php admin_tool.php delete <用户ID>\n";
echo " 示例: php admin_tool.php delete 2\n";
return;
}
$userId = (int)$args[2];
echo " 确认删除用户 ID {$userId}(y/N): ";
$confirm = trim(fgets(STDIN));
if (strtolower($confirm) !== 'y') {
echo "操作已取消\n";
return;
}
$stmt = $this->db->prepare("DELETE FROM users WHERE id = ?");
$success = $stmt->execute([$userId]);
if ($success && $stmt->rowCount() > 0) {
echo "用户 ID {$userId} 已删除\n";
} else {
echo "删除失败(用户可能不存在)\n";
}
}
// 显示帮助
private function showHelp()
{
echo "邮件服务器管理工具\n";
echo str_repeat("=", 40) . "\n";
echo "命令列表:\n";
echo " list - 显示所有用户\n";
echo " create <邮箱> <密码> [管理员] [容量] - 创建用户\n";
echo " enable <用户ID> - 启用用户\n";
echo " disable <用户ID> - 禁用用户\n";
echo " delete <用户ID> - 删除用户\n";
echo " help - 显示此帮助\n";
echo "\n示例:\n";
echo " php admin_tool.php list\n";
echo " php admin_tool.php create user@test.com password123 0 200\n";
echo " php admin_tool.php disable 2\n";
echo " php admin_tool.php delete 3\n";
}
}
// 运行工具
$tool = new AdminTool();
$tool->run($argv);
?>

@ -1,4 +1,8 @@
<?php
/**
* 数据库配置文件
* 使用环境变量或默认配置
*/
require_once __DIR__ . '/../../config/database.php';
class Database {

@ -1,11 +1,11 @@
<?php
require_once __DIR__ . '/Database.php';
require_once __DIR__ . '/../utils/Security.php';
/**
* 用户数据访问层
* 查客户信息、创建用户等
*/
class UserRepository {
private $db;

Loading…
Cancel
Save