This commit is contained in:
2026-07-20 14:59:16 +08:00
parent cd1175b304
commit 77930b3232
9 changed files with 94 additions and 78 deletions

View File

@@ -1,17 +1,21 @@
<?php <?php
declare (strict_types = 1);
declare(strict_types=1);
namespace app; namespace app;
use think\App; use think\App;
use think\exception\ValidateException; use think\exception\ValidateException;
use think\Validate; use think\Validate;
use app\common\Trait\ApiResponse;
/** /**
* 控制器基础类 * 控制器基础类
*/ */
abstract class BaseController abstract class BaseController
{ {
use ApiResponse;
/** /**
* Request实例 * Request实例
* @var \think\Request * @var \think\Request
@@ -51,8 +55,7 @@ abstract class BaseController
} }
// 初始化 // 初始化
protected function initialize() protected function initialize() {}
{}
/** /**
* 验证数据 * 验证数据
@@ -90,5 +93,4 @@ abstract class BaseController
return $v->failException(true)->check($data); return $v->failException(true)->check($data);
} }
} }

View File

@@ -1,4 +1,5 @@
<?php <?php
namespace app; namespace app;
use think\db\exception\DataNotFoundException; use think\db\exception\DataNotFoundException;
@@ -9,12 +10,15 @@ use think\exception\HttpResponseException;
use think\exception\ValidateException; use think\exception\ValidateException;
use think\Response; use think\Response;
use Throwable; use Throwable;
use app\common\Trait\ApiResponse;
/** /**
* 应用异常处理类 * 应用异常处理类
*/ */
class ExceptionHandle extends Handle class ExceptionHandle extends Handle
{ {
use ApiResponse;
/** /**
* 不需要记录信息(日志)的异常类列表 * 不需要记录信息(日志)的异常类列表
* @var array * @var array
@@ -50,7 +54,20 @@ class ExceptionHandle extends Handle
*/ */
public function render($request, Throwable $e): Response public function render($request, Throwable $e): Response
{ {
// 添加自定义异常处理机制 // 验证器异常
if ($e instanceof ValidateException) {
return $this->error($e->getError(), 422); // 验证器没通过
};
// 请求异常
if ($e instanceof HttpException) {
return $this->error($e->getMessage(), $e->getStatusCode());
};
// 处理【自定义业务异常】(在 Service 层主动 throw 的错误)
if ($e instanceof \think\Exception) {
return $this->error($e->getMessage(), $e->getCode() ?: 400);
}
// 其他错误交给系统处理 // 其他错误交给系统处理
return parent::render($request, $e); return parent::render($request, $e);

View File

@@ -13,9 +13,7 @@ class CompanyAndOperators extends BaseController
*/ */
public function getAllOperators(TicketService $ticketService) public function getAllOperators(TicketService $ticketService)
{ {
$result = $ticketService->getAllOperators(); $result = $ticketService->getAllOperators();
return json(['code' => 200, 'msg' => '查询成功', 'data' => $result]); return json(['code' => 200, 'msg' => '查询成功', 'data' => $result]);
} }

View File

@@ -6,6 +6,28 @@ use think\facade\Session;
class Auth class Auth
{ {
/**
* 无需 admin 角色即可访问的路由名称(方法名小写)
*/
protected $publicActions = [];
/**
* 需要 admin 角色才能访问的路由名称(方法名小写)
*/
protected $adminActions = [
'deleteoperator',
'deletecompany',
'addcompany',
'addoperator',
'getallusers',
'addaccount',
'updateaccountstatus',
'deleteaccount',
'getexportdata',
'deleteticket',
'batchupdate',
];
public function handle($request, \Closure $next) public function handle($request, \Closure $next)
{ {
if (!Session::has('user_info')) { if (!Session::has('user_info')) {
@@ -13,9 +35,18 @@ class Auth
} }
$user = Session::get('user_info'); $user = Session::get('user_info');
$role = $user['role'] ?? 'user';
$request->login_user_id = $user['id'] ?? null; $request->login_user_id = $user['id'] ?? null;
$request->login_role = $user['role'] ?? null; $request->login_role = $role;
// 获取当前请求的路由方法名
$action = strtolower($request->action());
// admin 专用接口
if (in_array($action, $this->adminActions) && $role !== 'admin') {
return json(['code' => 403, 'msg' => '权限不足,仅管理员可执行此操作']);
}
return $next($request); return $next($request);
} }

View File

@@ -2,6 +2,7 @@
use think\facade\Route; use think\facade\Route;
use app\admin\middleware\Auth; use app\admin\middleware\Auth;
use app\middleware\CheckLogin;
Route::group(function () { Route::group(function () {
Route::get('ticketsfind', 'Ticket/ticketsFind'); Route::get('ticketsfind', 'Ticket/ticketsFind');
@@ -11,7 +12,6 @@ Route::group(function () {
Route::put('tickets/batch-update', 'Ticket/batchUpdate'); Route::put('tickets/batch-update', 'Ticket/batchUpdate');
Route::get('getticketdashboardstats', 'Ticket/getTicketDashboardStats'); Route::get('getticketdashboardstats', 'Ticket/getTicketDashboardStats');
Route::get('getUserStaffList', 'CompanyAndOperators/getStaffList'); Route::get('getUserStaffList', 'CompanyAndOperators/getStaffList');
Route::get('operators', 'CompanyAndOperators/getAllOperators'); Route::get('operators', 'CompanyAndOperators/getAllOperators');
Route::get('getOperatorList', 'CompanyAndOperators/TestgetAllOperators'); Route::get('getOperatorList', 'CompanyAndOperators/TestgetAllOperators');
@@ -26,4 +26,4 @@ Route::group(function () {
Route::delete('deleteAccount/:id', 'AccountManagement/deleteAccount'); Route::delete('deleteAccount/:id', 'AccountManagement/deleteAccount');
Route::post('getExportData', 'Utill/getExportData'); Route::post('getExportData', 'Utill/getExportData');
})->middleware(Auth::class); })->middleware([CheckLogin::class, Auth::class]);

View File

@@ -1,66 +1,46 @@
<?php <?php
namespace app\common\Trait; namespace app\common\Trait;
use think\Response; use think\Response;
use think\response\Json;
/**
* API 响应 Trait
* 提供统一的 JSON 响应格式
*/
trait ApiResponse trait ApiResponse
{ {
/** /**
* 成功响应 * 成功响应
* * @param string $message 提示信息
* @param mixed $data 响应数据 * @param mixed $data 返回数据
* @param string $msg 响应消息 * @param int $code 自定义业务状态码
* @param int $code 响应码 * @return Json
* @param int $httpCode HTTP状态码
* @return Response
*/ */
protected function successResponse($data = [], $msg = '成功', $code = 200, $httpCode = 200) protected function success(int $code = 200, string $message = '操作成功', mixed $data = []): Json
{ {
return json([ return $this->jsonResponse($code, $message, $data);
'code' => $code,
'msg' => $msg,
'data' => $data
], $httpCode);
} }
/** /**
* 错误响应 * 失败响应
* * @param string $message 错误提示信息
* @param string $msg 错误消息 * @param int $code 自定义业务状态码
* @param mixed $data 错误数据 * @param mixed $data 额外的错误数据(如验证未通过的具体字段)
* @param int $code 错误码 * @return Json
* @param int $httpCode HTTP状态码
* @return Response
*/ */
protected function errorResponse($msg = '失败', $data = null, $code = 400, $httpCode = 400) protected function error(int $code = 400, string $message = '操作失败', mixed $data = []): Json
{ {
return json([ return $this->jsonResponse($code, $message, $data);
'code' => $code,
'msg' => $msg,
'data' => $data
], $httpCode);
} }
/** /**
* 自定义响应 * 统一 JSON 返回格式
*
* @param int $code 响应码
* @param string $msg 响应消息
* @param mixed $data 响应数据
* @param int $httpCode HTTP状态码
* @return Response
*/ */
protected function customResponse($code, $msg, $data = [], $httpCode = 200) private function jsonResponse(int $code, string $message, mixed $data): Json
{ {
return json([ $result = [
'code' => $code, 'code' => $code,
'msg' => $msg, 'msg' => $message,
'data' => $data 'data' => $data,
], $httpCode); ];
return json($result);
} }
} }

View File

@@ -9,8 +9,7 @@ use think\facade\Session;
// 已完成 // 已完成
class Login extends BaseController class Login extends BaseController
{ {
/* /*
处理登录请求(已完成) 处理登录请求(已完成)
*/ */
@@ -20,14 +19,14 @@ class Login extends BaseController
// 验证数据 // 验证数据
if (empty($params['username']) || empty($params['password'])) { if (empty($params['username']) || empty($params['password'])) {
return json(['code' => 400, 'message' => '用户名和密码不能为空']); return $this->error(400, '用户名和密码不能为空');
} }
try { try {
$result = $authService->login($params['username'], $params['password']); $result = $authService->login($params['username'], $params['password']);
return json(['code' => 200, 'message' => '登录成功', 'data' => $result]); return $this->success(200, '登录成功', $result);
} catch (\Exception $e) { } catch (\Exception $e) {
return json(['code' => 400, 'message' => $e->getMessage(), 'data' => []]); return $this->error(400, $e->getMessage());
} }
} }
@@ -37,6 +36,6 @@ class Login extends BaseController
public function logout() public function logout()
{ {
Session::clear(); Session::clear();
return json(['code' => 200, 'message' => '退出成功']); return $this->success(200, '退出成功');
} }
} }

View File

@@ -7,7 +7,6 @@ class CheckLogin
{ {
/** /**
* 处理请求 * 处理请求
*
* @param \think\Request $request * @param \think\Request $request
* @param \Closure $next * @param \Closure $next
* @return Response * @return Response
@@ -17,7 +16,6 @@ class CheckLogin
if (!Session::has('user_info')) { if (!Session::has('user_info')) {
return json(['code' => 401, 'message' => '未登录']); return json(['code' => 401, 'message' => '未登录']);
} }
return $next($request); return $next($request);
} }
} }

View File

@@ -58,24 +58,15 @@ return [
'fields_cache' => false, 'fields_cache' => false,
], ],
'remote' => [ 'remote' => [
// 数据库类型 'type' => 'mysql',
'type' => env('REMOTE_DB_TYPE', 'mysql'), 'hostname' => '112.5.15.136',
// 服务器地址 'database' => '112_5_15_136_255',
'hostname' => env('REMOTE_DB_HOST', '127.0.0.1'), 'username' => '112_5_15_136_255',
// 数据库名 'password' => 'xz1YX1jswSWzkE4K',
'database' => env('REMOTE_DB_NAME', ''), 'hostport' => '3306',
// 用户名 'charset' => 'utf8mb4',
'username' => env('REMOTE_DB_USER', 'root'), 'prefix' => '',
// 密码 'break_reconnect' => true,
'password' => env('REMOTE_DB_PASS', ''),
// 端口
'hostport' => env('REMOTE_DB_PORT', '3306'),
// 数据库编码
'charset' => env('REMOTE_DB_CHARSET', 'utf8mb4'),
// 数据库表前缀
'prefix' => '',
// 远程连接建议开启断线重连
'break_reconnect' => true,
], ],
// 更多的数据库配置信息 // 更多的数据库配置信息