Files
shengkao_pachong/app/service/UserService.php
2026-01-21 11:44:35 +08:00

285 lines
8.5 KiB
PHP

<?php
declare (strict_types = 1);
namespace app\service;
use app\model\User;
use think\facade\Db;
use app\service\ConfigService;
/**
* 用户服务类
* 用于处理用户账号管理相关逻辑
*/
class UserService
{
/**
* 管理员账号(固定)
*/
private const ADMIN_USERNAME = 'admin';
private const ADMIN_PASSWORD_DEFAULT = '123456';
private const ADMIN_PASSWORD_KEY = 'ADMIN_PASSWORD';
/**
* 获取管理员密码(优先读取配置,未设置则使用默认值)
*/
private function getAdminPassword(): string
{
$configService = new ConfigService();
$password = $configService->getConfig(self::ADMIN_PASSWORD_KEY, self::ADMIN_PASSWORD_DEFAULT);
return $password === '' ? self::ADMIN_PASSWORD_DEFAULT : $password;
}
/**
* 设置管理员密码
*/
private function setAdminPassword(string $newPassword): array
{
if (empty($newPassword)) {
return ['code' => 0, 'msg' => '新密码不能为空'];
}
$configService = new ConfigService();
return $configService->setConfig(self::ADMIN_PASSWORD_KEY, $newPassword);
}
/**
* 初始化数据库表
*/
public function initDatabase(): void
{
$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);
}
}
}
/**
* 读取所有账号
* @return array
*/
public function getAllUsers(): array
{
$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 [];
}
}
/**
* 验证登录(包括管理员和普通用户)
* @param string $username
* @param string $password
* @return array|false 返回用户信息或false
*/
public function verifyLogin(string $username, string $password)
{
// 验证管理员账号
if ($username === self::ADMIN_USERNAME && $password === $this->getAdminPassword()) {
return [
'username' => $username,
'is_admin' => true,
];
}
// 验证普通用户账号
$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;
}
/**
* 添加账号
* @param string $username
* @param string $password
* @return array ['code' => 1|0, 'msg' => string]
*/
public function addUser(string $username, string $password): array
{
if (empty($username) || empty($password)) {
return ['code' => 0, 'msg' => '用户名和密码不能为空'];
}
if ($username === self::ADMIN_USERNAME) {
return ['code' => 0, 'msg' => '不能添加管理员账号'];
}
$this->initDatabase();
try {
// 检查用户名是否已存在
$existUser = User::where('username', $username)->find();
if ($existUser) {
return ['code' => 0, 'msg' => '用户名已存在'];
}
// 添加新用户
$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' => '添加成功'];
} catch (\Exception $e) {
return ['code' => 0, 'msg' => '保存失败: ' . $e->getMessage()];
}
}
/**
* 删除账号
* @param string $username
* @return array ['code' => 1|0, 'msg' => string]
*/
public function deleteUser(string $username): array
{
if ($username === self::ADMIN_USERNAME) {
return ['code' => 0, 'msg' => '不能删除管理员账号'];
}
$this->initDatabase();
try {
$user = User::where('username', $username)->find();
if (!$user) {
return ['code' => 0, 'msg' => '用户不存在'];
}
$user->delete();
return ['code' => 1, 'msg' => '删除成功'];
} catch (\Exception $e) {
return ['code' => 0, 'msg' => '删除失败: ' . $e->getMessage()];
}
}
/**
* 检查是否为管理员
* @param string $username
* @return bool
*/
public function isAdmin(string $username): bool
{
return $username === self::ADMIN_USERNAME;
}
/**
* 用户自助修改密码(需验证旧密码)
*/
public function changeUserPassword(string $username, string $oldPassword, string $newPassword): array
{
if (empty($newPassword)) {
return ['code' => 0, 'msg' => '新密码不能为空'];
}
// 管理员走配置
if ($username === self::ADMIN_USERNAME) {
$current = $this->getAdminPassword();
if ($oldPassword !== $current) {
return ['code' => 0, 'msg' => '旧密码错误'];
}
return $this->setAdminPassword($newPassword);
}
$this->initDatabase();
$user = User::where('username', $username)->find();
if (!$user) {
return ['code' => 0, 'msg' => '用户不存在'];
}
if ($user->password !== $oldPassword) {
return ['code' => 0, 'msg' => '旧密码错误'];
}
$user->password = $newPassword;
$user->save();
return ['code' => 1, 'msg' => '密码修改成功'];
}
/**
* 管理员重置普通用户密码(无需旧密码)
*/
public function resetUserPassword(string $username, string $newPassword): array
{
if ($username === self::ADMIN_USERNAME) {
return ['code' => 0, 'msg' => '不能在此重置管理员密码'];
}
if (empty($username) || empty($newPassword)) {
return ['code' => 0, 'msg' => '用户名和新密码不能为空'];
}
$this->initDatabase();
$user = User::where('username', $username)->find();
if (!$user) {
return ['code' => 0, 'msg' => '用户不存在'];
}
$user->password = $newPassword;
$user->save();
return ['code' => 1, 'msg' => '重置成功'];
}
/**
* 管理员修改管理员密码(需要旧密码)
*/
public function changeAdminPassword(string $oldPassword, string $newPassword): array
{
if (empty($newPassword)) {
return ['code' => 0, 'msg' => '新密码不能为空'];
}
$current = $this->getAdminPassword();
if ($oldPassword !== $current) {
return ['code' => 0, 'msg' => '旧密码错误'];
}
return $this->setAdminPassword($newPassword);
}
}