Browse Source

优化请求头部全部开发,错误返回请求错误码

master
wanghongjun 1 month ago
parent
commit
fe918fe4ed
  1. 17
      app/controller/admin/Base.php
  2. 17
      app/controller/api/Base.php
  3. 14
      app/controller/api/Miss.php
  4. 2
      app/middleware.php
  5. 9
      app/middleware/AdminAuth.php
  6. 20
      app/middleware/AdminResponse.php
  7. 2
      app/middleware/WikiAuth.php
  8. 9
      config/apiadmin.php
  9. 5
      config/cookie.php
  10. 3
      config/session.php
  11. 12
      route/apiRoute.php

17
app/controller/admin/Base.php

@ -80,16 +80,19 @@ class Base extends BaseController {
* @author zhaoxiang <zhaoxiang051405@gmail.com> * @author zhaoxiang <zhaoxiang051405@gmail.com>
*/ */
public function buildFailed(int $code, string $msg = '操作失败', array $data = []): Response { public function buildFailed(int $code, string $msg = '操作失败', array $data = []): Response {
$return = [ $return = ['code' => $code, 'msg' => $msg, 'data' => $data];
'code' => $code,
'msg' => $msg,
'data' => $data
];
if (Env::get('APP_DEBUG') && $this->debug) { if (Env::get('APP_DEBUG') && $this->debug) {
$return['debug'] = $this->debug; $return['debug'] = $this->debug;
} }
// 根据 code 映射 HTTP 状态码
return json($return); $httpCode = match($code) {
ReturnCode::AUTH_ERROR => 401,
ReturnCode::ACCESS_TOKEN_TIMEOUT => 401,
ReturnCode::INVALID => 404,
//ReturnCode::NO_PERMISSION => 403,
default => 400,
};
return json($return, $httpCode);
} }
/** /**

17
app/controller/api/Base.php

@ -36,16 +36,19 @@ class Base extends BaseController {
} }
public function buildFailed(int $code, string $msg = '操作失败', array $data = []): Response { public function buildFailed(int $code, string $msg = '操作失败', array $data = []): Response {
$return = [ $return = ['code' => $code, 'msg' => $msg, 'data' => $data];
'code' => $code,
'msg' => $msg,
'data' => $data
];
if (Env::get('APP_DEBUG') && $this->debug) { if (Env::get('APP_DEBUG') && $this->debug) {
$return['debug'] = $this->debug; $return['debug'] = $this->debug;
} }
// 根据 code 映射 HTTP 状态码
return json($return); $httpCode = match($code) {
ReturnCode::AUTH_ERROR => 401,
ReturnCode::ACCESS_TOKEN_TIMEOUT => 401,
ReturnCode::INVALID => 404,
//ReturnCode::NO_PERMISSION => 403,
default => 400,
};
return json($return, $httpCode);
} }
protected function debug($data): void { protected function debug($data): void {

14
app/controller/api/Miss.php

@ -3,6 +3,7 @@ declare (strict_types=1);
namespace app\controller\api; namespace app\controller\api;
use app\util\ReturnCode;
use think\Exception; use think\Exception;
use think\facade\App; use think\facade\App;
use think\Response; use think\Response;
@ -10,17 +11,6 @@ use think\Response;
class Miss extends Base { class Miss extends Base {
public function index(): Response { public function index(): Response {
$version = config('apiadmin.APP_VERSION'); return $this->buildFailed(ReturnCode::INVALID);
if (!$version) {
throw new Exception('请先执行安装脚本,完成项目初始化!');
} else {
return $this->buildSuccess([
'Product' => config('apiadmin.APP_NAME'),
'ApiVersion' => $version,
'TpVersion' => App::version(),
'Company' => config('apiadmin.COMPANY_NAME'),
'ToYou' => "I'm glad to meet you(终于等到你!)"
]);
}
} }
} }

2
app/middleware.php

@ -7,5 +7,5 @@ return [
// \think\middleware\LoadLangPack::class, // \think\middleware\LoadLangPack::class,
// Session初始化 // Session初始化
\think\middleware\SessionInit::class, \think\middleware\SessionInit::class,
\think\middleware\AllowCrossDomain::class, //\think\middleware\AllowCrossDomain::class,
]; ];

9
app/middleware/AdminAuth.php

@ -17,7 +17,8 @@ class AdminAuth {
*/ */
public function handle($request, \Closure $next): Response { public function handle($request, \Closure $next): Response {
$header = config('apiadmin.CROSS_DOMAIN'); $header = config('apiadmin.CROSS_DOMAIN');
$ApiAuth = $request->header('Api-Auth', ''); //$ApiAuth = $request->header('Api-Auth', '');
$ApiAuth = $request->header('token', '');
if ($ApiAuth) { if ($ApiAuth) {
$userInfo = cache('Login:' . $ApiAuth); $userInfo = cache('Login:' . $ApiAuth);
if ($userInfo) { if ($userInfo) {
@ -28,7 +29,7 @@ class AdminAuth {
'code' => ReturnCode::AUTH_ERROR, 'code' => ReturnCode::AUTH_ERROR,
'msg' => 'ApiAuth不匹配', 'msg' => 'ApiAuth不匹配',
'data' => [] 'data' => []
])->header($header); ], 403)->header($header);
} else { } else {
$request->API_ADMIN_USER_INFO = $userInfo; $request->API_ADMIN_USER_INFO = $userInfo;
} }
@ -37,9 +38,9 @@ class AdminAuth {
} else { } else {
return json([ return json([
'code' => ReturnCode::AUTH_ERROR, 'code' => ReturnCode::AUTH_ERROR,
'msg' => '缺少ApiAuth', 'msg' => 'ApiAuth不匹配',
'data' => [] 'data' => []
])->header($header); ], 403)->header($header);
} }
} }
} }

20
app/middleware/AdminResponse.php

@ -6,9 +6,23 @@ namespace app\middleware;
use think\facade\Config; use think\facade\Config;
use think\Response; use think\Response;
class AdminResponse { class AdminResponse
{
public function handle($request, \Closure $next): Response { public function handle($request, \Closure $next): Response
return $next($request)->header(Config::get('apiadmin.CROSS_DOMAIN')); {
$response = $next($request);
$origin = $request->header('origin', '');
$whitelist = Config::get('apiadmin.CORS_ORIGIN_WHITELIST', []);
if ($origin && in_array($origin, $whitelist, true)) {
$response->header(['Access-Control-Allow-Origin' => $origin]);
}
$response->header([
'Vary' => 'Origin',
'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS',
'Access-Control-Allow-Headers' => 'Api-Auth,token,Authorization,Content-Type,X-Requested-With',
'Access-Control-Allow-Credentials' => 'true',
]);
return $response;
} }
} }

2
app/middleware/WikiAuth.php

@ -30,7 +30,7 @@ class WikiAuth {
'code' => ReturnCode::AUTH_ERROR, 'code' => ReturnCode::AUTH_ERROR,
'msg' => 'ApiAuth不匹配', 'msg' => 'ApiAuth不匹配',
'data' => [] 'data' => []
])->header($header); ], 403)->header($header);
} else { } else {
$request->API_WIKI_USER_INFO = $userInfo; $request->API_WIKI_USER_INFO = $userInfo;
} }

9
config/apiadmin.php

@ -27,7 +27,7 @@ return [
//跨域配置 //跨域配置
'CROSS_DOMAIN' => [ 'CROSS_DOMAIN' => [
'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Origin' => '',
'Access-Control-Allow-Methods' => 'POST,PUT,GET,DELETE', 'Access-Control-Allow-Methods' => 'POST,PUT,GET,DELETE',
'Access-Control-Allow-Headers' => 'Version, Access-Token, User-Token, Api-Auth, User-Agent, Keep-Alive, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Token', 'Access-Control-Allow-Headers' => 'Version, Access-Token, User-Token, Api-Auth, User-Agent, Keep-Alive, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Token',
'Access-Control-Allow-Credentials' => 'true' 'Access-Control-Allow-Credentials' => 'true'
@ -35,4 +35,11 @@ return [
//后台列表默认一页显示数量 //后台列表默认一页显示数量
'ADMIN_LIST_DEFAULT' => 20, 'ADMIN_LIST_DEFAULT' => 20,
'CORS_ORIGIN_WHITELIST' => [
'https://ljclf.dgyq-water.com',
'http://10.44.8.11',
'http://localhost:8000',
// 其他需要的前端域名
],
]; ];

5
config/cookie.php

@ -10,9 +10,10 @@ return [
// cookie 有效域名 // cookie 有效域名
'domain' => '', 'domain' => '',
// cookie 启用安全传输 // cookie 启用安全传输
'secure' => false, 'secure' => true,
// httponly设置 // httponly设置
'httponly' => false, 'httponly' => true,
'samesite' => 'Lax', // 防 CSRF
// 是否使用 setcookie // 是否使用 setcookie
'setcookie' => true, 'setcookie' => true,
]; ];

3
config/session.php

@ -16,4 +16,7 @@ return [
'expire' => 1440, 'expire' => 1440,
// 前缀 // 前缀
'prefix' => '', 'prefix' => '',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
]; ];

12
route/apiRoute.php

@ -17,12 +17,12 @@ Route::group('api', function() {
Route::rule('InvoiceIssuance/getErrorInfo', 'api.InvoiceIssuance/getErrorInfo', 'get')->middleware(\app\middleware\WechatAuth::class); Route::rule('InvoiceIssuance/getErrorInfo', 'api.InvoiceIssuance/getErrorInfo', 'get')->middleware(\app\middleware\WechatAuth::class);
Route::rule('InvoiceIssuance/validateFeePay', 'api.InvoiceIssuance/validateFeePay', 'post')->middleware(\app\middleware\WechatAuth::class); Route::rule('InvoiceIssuance/validateFeePay', 'api.InvoiceIssuance/validateFeePay', 'post')->middleware(\app\middleware\WechatAuth::class);
// 测试FeeService 接口 // 测试FeeService 接口
Route::rule('Test/index', 'api.Test/index', 'get'); // Route::rule('Test/index', 'api.Test/index', 'get');
Route::rule('Test1/index', 'api.Test1/index', 'get'); // Route::rule('Test1/index', 'api.Test1/index', 'get');
Route::rule('Test/index', 'api.Test/apiInvoiceIssuance', 'post'); // Route::rule('Test/index', 'api.Test/apiInvoiceIssuance', 'post');
Route::rule('Test/saveSummaryReport', 'api.Test/saveSummaryReport', 'post'); // Route::rule('Test/saveSummaryReport', 'api.Test/saveSummaryReport', 'post');
Route::rule('Test/apiFinalReport', 'api.Test/apiFinalReport', 'post'); // Route::rule('Test/apiFinalReport', 'api.Test/apiFinalReport', 'post');
Route::rule('InvoiceIssuance/downFile', 'api.InvoiceIssuance/downFile', 'get'); // Route::rule('InvoiceIssuance/downFile', 'api.InvoiceIssuance/downFile', 'get');
//MISS路由定义 //MISS路由定义
//Route::miss('api.Miss/index'); //Route::miss('api.Miss/index');
});//->middleware(app\middleware\ApiResponse::class) });//->middleware(app\middleware\ApiResponse::class)

Loading…
Cancel
Save