This commit is contained in:
杨志
2026-01-21 08:53:45 +08:00
parent f9c34127c7
commit a962e06a18
14 changed files with 574 additions and 222 deletions

View File

@@ -3,17 +3,15 @@ declare (strict_types = 1);
namespace app\service;
use app\model\User;
use think\facade\Db;
/**
* 用户服务类
* 用于处理用户账号管理相关逻辑
*/
class UserService
{
/**
* 账号数据文件路径
*/
private const USERS_FILE = 'users.json';
/**
* 管理员账号(固定)
*/
@@ -21,58 +19,65 @@ class UserService
private const ADMIN_PASSWORD = '123456';
/**
* 初始化账号数据文件
* 初始化数据库表
*/
private function initUsersFile(): void
public function initDatabase(): void
{
$filePath = $this->getUsersFilePath();
if (!file_exists($filePath)) {
$dir = dirname($filePath);
if (!is_dir($dir)) {
mkdir($dir, 0755, true);
$dbPath = dirname(dirname(__DIR__)) . '/runtime/database.db';
$dbDir = dirname($dbPath);
// 确保runtime目录存在
if (!is_dir($dbDir)) {
mkdir($dbDir, 0755, true);
}
// 连接SQLite数据库
try {
$connection = Db::connect('sqlite');
// 创建用户表(如果不存在)
$sql = "CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME NOT NULL
)";
$connection->execute($sql);
} catch (\Exception $e) {
// 如果连接失败,尝试创建数据库文件
if (!file_exists($dbPath)) {
touch($dbPath);
chmod($dbPath, 0666);
}
file_put_contents($filePath, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
}
/**
* 获取账号数据文件路径
* @return string
*/
private function getUsersFilePath(): string
{
// 获取项目根目录
$rootPath = dirname(dirname(__DIR__));
$runtimePath = $rootPath . '/runtime';
if (!is_dir($runtimePath)) {
mkdir($runtimePath, 0755, true);
}
return $runtimePath . '/' . self::USERS_FILE;
}
/**
* 读取所有账号
* @return array
*/
public function getAllUsers(): array
{
$this->initUsersFile();
$filePath = $this->getUsersFilePath();
$content = file_get_contents($filePath);
$users = json_decode($content, true);
return is_array($users) ? $users : [];
}
/**
* 保存账号数据
* @param array $users
* @return bool
*/
private function saveUsers(array $users): bool
{
$this->initUsersFile();
$filePath = $this->getUsersFilePath();
return file_put_contents($filePath, json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)) !== false;
$this->initDatabase();
try {
$users = User::select()->toArray();
// 确保返回关联数组格式
$result = [];
foreach ($users as $user) {
$result[] = [
'id' => $user['id'] ?? null,
'username' => $user['username'] ?? '',
'password' => $user['password'] ?? '',
'created_at' => $user['created_at'] ?? '',
];
}
return $result;
} catch (\Exception $e) {
// 如果表不存在,返回空数组
return [];
}
}
/**
@@ -92,16 +97,19 @@ class UserService
}
// 验证普通用户账号
$users = $this->getAllUsers();
foreach ($users as $user) {
if (isset($user['username']) && $user['username'] === $username) {
if (isset($user['password']) && $user['password'] === $password) {
return [
'username' => $username,
'is_admin' => false,
];
}
$this->initDatabase();
try {
$user = User::where('username', $username)->find();
if ($user && $user->password === $password) {
return [
'username' => $username,
'is_admin' => false,
];
}
} catch (\Exception $e) {
// 忽略数据库错误
}
return false;
@@ -123,26 +131,25 @@ class UserService
return ['code' => 0, 'msg' => '不能添加管理员账号'];
}
$users = $this->getAllUsers();
$this->initDatabase();
// 检查用户名是否已存在
foreach ($users as $user) {
if (isset($user['username']) && $user['username'] === $username) {
try {
// 检查用户名是否已存在
$existUser = User::where('username', $username)->find();
if ($existUser) {
return ['code' => 0, 'msg' => '用户名已存在'];
}
}
// 添加新用户
$users[] = [
'username' => $username,
'password' => $password,
'created_at' => date('Y-m-d H:i:s'),
];
if ($this->saveUsers($users)) {
// 添加新用户
$user = new User();
$user->username = $username;
$user->password = $password;
$user->created_at = date('Y-m-d H:i:s');
$user->save();
return ['code' => 1, 'msg' => '添加成功'];
} else {
return ['code' => 0, 'msg' => '保存失败'];
} catch (\Exception $e) {
return ['code' => 0, 'msg' => '保存失败: ' . $e->getMessage()];
}
}
@@ -157,23 +164,20 @@ class UserService
return ['code' => 0, 'msg' => '不能删除管理员账号'];
}
$users = $this->getAllUsers();
$newUsers = [];
$this->initDatabase();
foreach ($users as $user) {
if (isset($user['username']) && $user['username'] !== $username) {
$newUsers[] = $user;
try {
$user = User::where('username', $username)->find();
if (!$user) {
return ['code' => 0, 'msg' => '用户不存在'];
}
}
if (count($newUsers) === count($users)) {
return ['code' => 0, 'msg' => '用户不存在'];
}
if ($this->saveUsers($newUsers)) {
$user->delete();
return ['code' => 1, 'msg' => '删除成功'];
} else {
return ['code' => 0, 'msg' => '保存失败'];
} catch (\Exception $e) {
return ['code' => 0, 'msg' => '删除失败: ' . $e->getMessage()];
}
}