tp/app/admin/controller/UserController.php
2026-01-29 17:37:51 +08:00

145 lines
3.8 KiB
PHP

<?php
declare(strict_types=1);
namespace app\admin\controller;
use app\admin\BaseController;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Session;
use think\response\Json;
use app\model\AdminUser;
class UserController extends BaseController
{
/**
* 获取所有用户信息
* @return Json
*/
public function getAllUsers()
{
$users = AdminUser::where('delete_time', null)->field('id, account, name, phone, birth, email, qq, sex, group_id, status, last_login_ip, login_count, create_time, update_time')->select()->toArray();
return json([
'code' => 200,
'msg' => '获取成功',
'data' => [
'list' => $users,
'total' => count($users)
]
]);
}
/**
* 获取用户信息
* @return Json
*/
public function getUserInfo(int $id)
{
$user = AdminUser::where('id', $id)
->field('id, account, name, phone, email, birth, qq, sex, group_id, status, create_time, last_login_ip')
->find();
// 记录操作日志
$this->logSuccess('用户管理', '获取用户信息', ['id' => $id]);
return json([
'code' => 200,
'msg' => '获取成功',
'data' => $user
]);
}
/**
* 修改密码
* @return Json
*/
public function changePassword(int $id, string $password)
{
try {
AdminUser::where('id', $id)->update([
'password' => md5($password),
'update_time' => date('Y-m-d H:i:s')
]);
// 记录操作日志
$this->logSuccess('用户管理', '修改密码', ['id' => $id]);
return json([
'code' => 200,
'msg' => '修改成功'
]);
} catch (\Exception $e) {
// 记录失败日志
$this->logFail('用户管理', '修改密码', $e->getMessage());
return json([
'code' => 500,
'msg' => '修改失败'
]);
}
}
/**
* 添加用户
* @return Json
*/
public function addUser()
{
$data = request()->param();
$data['password'] = md5($data['password']);
$data['create_time'] = date('Y-m-d H:i:s');
$data['update_time'] = $data['create_time'];
$data['group_id'] = 2;
$id = AdminUser::insertGetId($data);
// 记录操作日志
$this->logSuccess('用户管理', '添加用户', ['data' => $data]);
return json([
'code' => 200,
'msg' => '添加成功',
'data' => ['id' => $id]
]);
}
/**
* 编辑用户
* @return Json
*/
public function editUser(int $id)
{
$data = request()->param();
unset($data['_t'], $data['id']);
$data['update_time'] = date('Y-m-d H:i:s');
AdminUser::where('id', $id)->update($data);
$this->logSuccess('用户管理', '编辑用户', ['id' => $id]);
return json([
'code' => 200,
'msg' => '编辑成功'
]);
}
/**
* 删除用户
* @return Json
*/
public function deleteUser(int $id)
{
$user = AdminUser::where('id', $id)->where('delete_time', null)->find();
if (!$user) {
return json([
'code' => 404,
'msg' => '用户不存在或已删除'
]);
}
AdminUser::where('id', $id)->update([
'delete_time' => date('Y-m-d H:i:s')
]);
$this->logSuccess('用户管理', '删除用户', ['id' => $id]);
return json([
'code' => 200,
'msg' => '删除成功'
]);
}
}