diff --git a/app/Exceptions/Admin/AuthException.php b/app/Exceptions/Admin/AuthException.php index dbac6721ffc7a1e95df533459f90000c3fd07f9a..0b31538a9fd01432f8e039240d57cb5a060f0892 100644 --- a/app/Exceptions/Admin/AuthException.php +++ b/app/Exceptions/Admin/AuthException.php @@ -9,9 +9,9 @@ use Illuminate\Http\Request; class AuthException extends Exception { protected $admin_id = 0; - public function __construct(string $message = "", int $code = 0, int $admin_id = 0) + public function __construct(string $message = "", int $http_status = 401, int $admin_id = 0) { - parent::__construct($message, $code); + parent::__construct($message, $http_status); $this->admin_id = $admin_id; } @@ -19,10 +19,9 @@ class AuthException extends Exception { if ($request->expectsJson()) { // 登录日志 - AdminLoginLog::getInstance()->add($this->admin_id, 0, $this->msg); + AdminLoginLog::getInstance()->add($this->admin_id, 0, $this->getMessage()); - $this->setHttpCode(401); - return $this->errorJson($this->msg); + return $this->errorJson($this->getMessage(), $this->getCode()); } } } diff --git a/app/Exceptions/Admin/AuthTokenException.php b/app/Exceptions/Admin/AuthTokenException.php index 70d58bd884c87a069ae4d13581f598532192e3cd..f26a62cc0577d64d1c5a9671305189f323c846e7 100644 --- a/app/Exceptions/Admin/AuthTokenException.php +++ b/app/Exceptions/Admin/AuthTokenException.php @@ -9,9 +9,9 @@ use Illuminate\Http\Request; class AuthTokenException extends Exception { protected $admin_id = 0; - public function __construct(string $message = "", int $code = 0, int $admin_id = 0) + public function __construct(string $message = "", int $http_status = 401, int $admin_id = 0) { - parent::__construct($message, $code); + parent::__construct($message, $http_status); $this->admin_id = $admin_id; } @@ -19,10 +19,9 @@ class AuthTokenException extends Exception { if ($request->expectsJson()) { // 登录日志 - AdminLoginLog::getInstance()->add($this->admin_id, 0, $this->msg); + AdminLoginLog::getInstance()->add($this->admin_id, 0, $this->getMessage()); - $this->setHttpCode(401); - return $this->errorJson($this->msg); + return $this->errorJson($this->getMessage(), $this->getCode()); } } } diff --git a/app/Exceptions/Exception.php b/app/Exceptions/Exception.php index 7bc73604d49a7bf9454ae5ed47f62b9e7a9022ae..5607556e3b4acdffdadb1feddb462a81f5878562 100644 --- a/app/Exceptions/Exception.php +++ b/app/Exceptions/Exception.php @@ -11,10 +11,11 @@ class Exception extends \Exception protected $msg; - public function __construct($message = "success", $code = 0, Throwable $previous = null) + public function __construct($message = "success", $http_status = 400, Throwable $previous = null) { - parent::__construct($message, $code, $previous); + parent::__construct($message, $http_status, $previous); $this->msg = $message; + $this->setHttpCode($http_status); } } diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php index d48b3ad2bd5915df6bdc095a39fcf959037cd4c6..1b9b6a256b804ed0fc0cbfe2eb91929c7f7a1aa0 100644 --- a/app/Exceptions/Handler.php +++ b/app/Exceptions/Handler.php @@ -3,6 +3,7 @@ namespace App\Exceptions; use App\Traits\Json; +use Illuminate\Contracts\Container\BindingResolutionException; use Illuminate\Validation\ValidationException; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; @@ -68,22 +69,24 @@ class Handler extends ExceptionHandler // 控制器不存在 if ($exception instanceof BindingResolutionException){ - return $this->setJsonReturn($exception); + return $this->setJsonReturn($exception, 400); } // 模型不存在 if ($exception instanceof ModelNotFoundException){ - return $this->setJsonReturn($exception); + return $this->setJsonReturn($exception, 400); } // 验证器类的错误监听 if($exception instanceof ValidationException){ + $this->setHttpCode(400); return $this->errorJson($exception->validator->errors()->first()); } // 自定义Exception类的错误监听 if($exception instanceof Exception){ - return $this->setJsonReturn($exception); + $http_code = $exception->getCode(); + return $this->setJsonReturn($exception, $http_code); } // ErrorException类的监听 @@ -95,17 +98,15 @@ class Handler extends ExceptionHandler return parent::render($request, $exception); } - private function setJsonReturn($exception) + private function setJsonReturn($exception, $http_status = false) { $APP_DEBUG = env('APP_DEBUG'); // 设置HTTP的状态码 - $http_status = isset($http_status) ? $http_status : (method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() : 200); - - // 可设置`status`,但是也要限制 - $status = $exception->getCode() != 1 ? 0 : 1; + $http_status = $http_status ? $http_status : (method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() : (method_exists($exception, 'getCode') ? $exception->getCode() : 200)); - return $this->errorJson($exception->getMessage(), $status, [], $APP_DEBUG ? [ + $this->setHttpCode($http_status); + return $this->errorJson($exception->getMessage(), $http_status, [], $APP_DEBUG ? [ 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'code' => $exception->getCode(), diff --git a/app/Exceptions/InternalException.php b/app/Exceptions/InternalException.php index b9429b263b54b628a4123be4376a92f775aa479b..8b76c69f0772e113ff2ad6de6848c4c1692de329 100644 --- a/app/Exceptions/InternalException.php +++ b/app/Exceptions/InternalException.php @@ -6,16 +6,15 @@ use Illuminate\Http\Request; class InternalException extends Exception { - public function __construct(string $message, string $msg = '系统内部错误', int $code = 500) + public function __construct(string $message = '系统内部错误', int $http_status = 500) { - parent::__construct($message, $code); - $this->msg = $msg; + parent::__construct($message, $http_status); } public function render(Request $request) { if ($request->expectsJson()) { - return response()->json(['msg' => $this->msg], $this->code); + return response()->json(['msg' => $this->getMessage()], $this->getCode()); } } } diff --git a/app/Exceptions/InvalidRequestException.php b/app/Exceptions/InvalidRequestException.php index 954e53a066d79a7d8bb654dfd753db704324f6de..a6a1b7c736e8dba70c526e09cda089591b71958a 100644 --- a/app/Exceptions/InvalidRequestException.php +++ b/app/Exceptions/InvalidRequestException.php @@ -6,15 +6,15 @@ use Illuminate\Http\Request; class InvalidRequestException extends Exception { - public function __construct(string $message = "", int $code = 0) + public function __construct(string $message = "", int $http_status = 400) { - parent::__construct($message, $code); + parent::__construct($message, $http_status); } public function render(Request $request) { if ($request->expectsJson()) { - return $this->errorJson($this->msg); + return $this->errorJson($this->getMessage(), $this->getCode()); } } } diff --git a/app/Modules/Admin/Http/Middleware/AdminLog.php b/app/Modules/Admin/Http/Middleware/AdminLog.php index 34fa6f7119778b42d1dc8effe71b0b08d6ceab20..23615fa3eb13238cff8bdf81acbdc2f206fb2caa 100644 --- a/app/Modules/Admin/Http/Middleware/AdminLog.php +++ b/app/Modules/Admin/Http/Middleware/AdminLog.php @@ -26,7 +26,8 @@ class AdminLog if ($method != 'GET'){ $ip_agent = get_client_info(); - $admin_log = \App\Modules\Admin\Entities\Log\AdminLog::getInstance()->create([ + + $log_data = [ 'request_data' => json_encode($request->all()), 'admin_id' => !empty(auth($guard)->user()) ? auth($guard)->user()->admin_id : 0, 'created_ip' => $ip_agent['ip'] ?? get_ip(), @@ -38,7 +39,7 @@ class AdminLog 'request_url' => URL::full() ?? get_this_url(), // 默认值 'log_status' => 0, - ]); + ]; $log_status = 0; try{ @@ -49,21 +50,18 @@ class AdminLog // 根据接口响应,存储返回状态与文本提示语 $log_status = $response_body_content->status; - $log_description = empty($adminlog->log_description) ? $response_body_content->msg : $adminlog->log_description; + $log_description = empty($log_data['log_description']) ? $response_body_content->msg : $log_data['log_description']; }catch(\Exception $e){ $log_description = $e->getMessage(); $response = $this->errorJson($log_description); } // 同步更新响应状态与文本,在`handler`层可能会被异常终止 - $admin_log->update( - [ - 'log_duration' => microtime(true) - LARAVEL_START, - // 根据接口响应,存储返回状态与文本提示语 - 'log_status' => $log_status, - 'description' => $log_description, - ] - ); + $log_data['log_duration'] = microtime(true) - LARAVEL_START; + // 根据接口响应,存储返回状态与文本提示语 + $log_data['log_status'] = $log_status; + $log_data['description'] = $log_description; + \App\Modules\Admin\Entities\Log\AdminLog::getInstance()->create($log_data); return $response; } diff --git a/app/Modules/Admin/Http/Middleware/CheckAuth.php b/app/Modules/Admin/Http/Middleware/CheckAuth.php index 26fd33d784c39a67033e8c50f9b978dd91d70a7f..f87267613daba3e9d7844f0bb4605cd88aa733ca 100644 --- a/app/Modules/Admin/Http/Middleware/CheckAuth.php +++ b/app/Modules/Admin/Http/Middleware/CheckAuth.php @@ -29,12 +29,12 @@ class CheckAuth $auth = Auth()->guard($this->guard); try { if ( !$auth->check() ) { //未登录踢回,给予错误返回提示 - return $this->errorJson('认证失败,请重新登录!', -1); + return $this->errorJson('认证失败,请重新登录!', 401); } } catch (TokenExpiredException $e) { - return $this->errorJson($e->getMessage(), -1); + return $this->errorJson($e->getMessage(), 401); } catch (TokenInvalidException $e) { - return $this->errorJson($e->getMessage(), -1); + return $this->errorJson($e->getMessage(), 401); } catch (JWTException $e) { return $this->errorJson($e->getMessage()); } diff --git a/app/Modules/Admin/Http/Middleware/CheckIpBlacklist.php b/app/Modules/Admin/Http/Middleware/CheckIpBlacklist.php index bfd47b0cd68a896f768ad1443fcd66957210ac31..bf0834bb69046038054f4d43cf2e81efd40b91a4 100644 --- a/app/Modules/Admin/Http/Middleware/CheckIpBlacklist.php +++ b/app/Modules/Admin/Http/Middleware/CheckIpBlacklist.php @@ -34,6 +34,10 @@ class CheckIpBlacklist $ip_blacklists_array = array_flip($ip_blacklists_array); if (isset($ip_blacklists_array[$client_ip])){ $msg = '您的IP段在系统黑名单中,禁止访问!'; + if ($request->expectsJson()){ + $this->setHttpCode(403); + return $this->errorJson($msg); + } abort(403, $msg); } } diff --git a/app/Modules/Admin/Http/Middleware/CheckRabc.php b/app/Modules/Admin/Http/Middleware/CheckRabc.php index dec3e915c29bc76466c3bcfdf2056217b6a60285..15bf0046c23877bb918895dc98da551551d980d3 100644 --- a/app/Modules/Admin/Http/Middleware/CheckRabc.php +++ b/app/Modules/Admin/Http/Middleware/CheckRabc.php @@ -29,7 +29,7 @@ class CheckRabc $this->guard = 'admin'; // 开始验证路由权限 if (!$this->checkRabc($request, Auth()->guard($this->guard)->user()->getAuthIdentifier(), $load_error)){ - return $this->errorJson('无权限' . (empty($load_error) ? '!' : ',' . $load_error), -2); + return $this->errorJson('无权限' . (empty($load_error) ? '!' : ',' . $load_error), 403); } return $next($request); diff --git a/app/Modules/Admin/Resources/vue-element-admin/utils/request.js b/app/Modules/Admin/Resources/vue-element-admin/utils/request.js index b3df91fb34ddb1cd904b6bbba8a894aeaaf209bc..84d48b3856eced883ee55a6c24d30b91ce40872e 100644 --- a/app/Modules/Admin/Resources/vue-element-admin/utils/request.js +++ b/app/Modules/Admin/Resources/vue-element-admin/utils/request.js @@ -8,13 +8,10 @@ import { getToken } from '@/utils/auth'; -console.log(process); -// console.log(process.env); -// console.log(process.env.VUE_APP_BASE_API); +// console.log(process); // process失效了,默认为当前URL为请求地址 process.env.VUE_APP_BASE_API = window.location.origin + window.location.pathname; -// console.log(process.env.VUE_APP_BASE_API); let timeout = 15000; @@ -69,7 +66,6 @@ service.interceptors.response.use( */ response => { const res = response.data; - // if the custom code is not 20000, it is judged as an error. if (res.status !== 1) { Message({ @@ -98,21 +94,44 @@ service.interceptors.response.use( } }, error => { + let callback = null; console.log('err' + error); // for debug let msg = error.msg; if (error.response == undefined){ msg = '超时 ' + timeout + ' ms,请刷新!'; }else{ switch (error.response.status) { - case 404: + case 400: msg = error.response.statusText; break; case 401: // 认证失败 - msg = error.response.data.msg; + msg = error.response.data.msg ? error.response.data.msg : error.response.statusText; + callback = function(){ + // to re-login + MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', + 'Confirm logout', { + confirmButtonText: 'Re-Login', + cancelButtonText: 'Cancel', + type: 'warning' + }).then(() => { + store.dispatch('user/resetToken').then(() => { + location.reload(); + }) + }) + }; + break; + case 404: + msg = error.response.statusText; break; - case 500: // 认证失败 + case 403: + msg = error.response.data.msg ? error.response.data.msg : error.response.statusText; + break; + case 500: msg = error.response.statusText; break; + default: + msg = error.response.data.msg ? error.response.data.msg : error.response.statusText; + break; } } Message({ @@ -120,6 +139,12 @@ service.interceptors.response.use( type: 'error', duration: 5 * 1000 }); + + // 执行闭包 + if (callback){ + callback(); + } + return Promise.reject(error); } ) diff --git a/app/Modules/Admin/Services/AuthService.php b/app/Modules/Admin/Services/AuthService.php index 9aebc8ab4c798244869d2a1e1ba8214e4a151c12..28634c3fb3dfaad8f718208814f173de22d7671a 100644 --- a/app/Modules/Admin/Services/AuthService.php +++ b/app/Modules/Admin/Services/AuthService.php @@ -4,7 +4,6 @@ namespace App\Modules\Admin\Services; use App\Exceptions\Admin\AuthException; use App\Exceptions\Admin\AuthTokenException; -use App\Exceptions\InvalidRequestException; use App\Modules\Admin\Entities\Log\AdminLoginLog; use App\Modules\Admin\Entities\Rabc\Admin; use App\Modules\Admin\Entities\Rabc\AdminMenu; @@ -21,7 +20,6 @@ class AuthService extends Service * @param $data * @return array * @throws AuthException - * @throws InvalidRequestException */ public function login($data) { @@ -60,7 +58,7 @@ class AuthService extends Service /** * 获取拥有的权限 - * + * * @throws \App\Exceptions\Admin\AuthTokenException */ public function getRabcList() diff --git a/app/Modules/Admin/Services/BaseService.php b/app/Modules/Admin/Services/BaseService.php index a1ea49a39162dc723138761644ebb390f11f9145..8737960382ac61b08592d43accaa2c3275f2e9c5 100644 --- a/app/Modules/Admin/Services/BaseService.php +++ b/app/Modules/Admin/Services/BaseService.php @@ -87,7 +87,7 @@ class BaseService extends Service } $this->detail = $this->model->find($params[$primaryKey]); if (!$this->detail){ - throw new Exception('编辑信息不存在!'); + throw new Exception('编辑信息不存在!', 403); } foreach ($this->model->setFilterFields($params) as $field => $value){ $this->detail->$field = $value ?? ''; diff --git a/app/Traits/Json.php b/app/Traits/Json.php index 99c86b53f96f8d678a11a5a220127fd53d5e8650..575eec8ee2e3449ab2673c4a67fcb371b43e62b7 100644 --- a/app/Traits/Json.php +++ b/app/Traits/Json.php @@ -10,12 +10,12 @@ trait Json public function successJson($data = [], $msg = 'success', $other = []) { - return $this->myAjaxReturn(array_merge(['data' => $data, 'msg' => $msg, 'status' => 1], $other)); + return $this->myAjaxReturn(array_merge(['data' => $data, 'msg' => $msg, 'http_code' => 200], $other)); } - public function errorJson($msg = 'error', $status = 0, $data = [], $other = []) + public function errorJson($msg = 'error', $http_code = 0, $data = [], $other = []) { - return $this->myAjaxReturn(array_merge(['msg' => $msg, 'status' => $status, 'data' => $data], $other)); + return $this->myAjaxReturn(array_merge(['msg' => $msg, 'http_code' => $http_code, 'data' => $data], $other)); } public function setHttpCode(int $http_code): void @@ -34,9 +34,24 @@ trait Json public function myAjaxReturn($data) { $data['data'] = $data['data'] ?? []; - $data['status'] = intval($data['status'] ?? (empty($data['data']) ? 0 : 1)); + // $data['status'] = intval($data['status'] ?? (empty($data['data']) ? 0 : 1)); + if(!isset($data['http_code'])) $data['http_code'] = $this->http_code; + switch ($data['http_code']){ + case 200: + $data['status'] = 1; + break; + case 400: + $data['status'] = 0; + break; + case 401: + $data['status'] = -1; + break; + case 403: + $data['status'] = -2; + break; + } $data['msg'] = $data['msg'] ?? (empty($data['status']) ? '数据不存在!' : 'success'); - return response()->json($data, $this->http_code); + return response()->json($data, $data['http_code']); } } diff --git "a/\345\276\205\345\256\236\347\216\260\345\212\237\350\203\275\345\210\227\350\241\250.md" "b/\345\276\205\345\256\236\347\216\260\345\212\237\350\203\275\345\210\227\350\241\250.md" new file mode 100644 index 0000000000000000000000000000000000000000..7f2ec560f0d5b136544bd9c481bf8e452f7c34f0 --- /dev/null +++ "b/\345\276\205\345\256\236\347\216\260\345\212\237\350\203\275\345\210\227\350\241\250.md" @@ -0,0 +1,3 @@ +- API的响应状态码设置http状态码 +- 关于页面的按钮权限优化 + - 如果无权限则不展示,那么需要新加接口,效验当前的所有按钮权限 \ No newline at end of file