Files
shengkao_pachong/app/middleware/Auth.php
杨志 a562c95b10 up
2026-01-21 09:15:50 +08:00

45 lines
1.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare (strict_types = 1);
namespace app\middleware;
/**
* 登录验证中间件
*/
class Auth
{
/**
* 处理请求
*
* @param \think\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, \Closure $next)
{
// 检查是否已登录
$username = session('username');
// 获取路径信息
$pathinfo = $request->pathinfo();
// 判断是否为API请求非index页面
$isApiRequest = $pathinfo !== 'crawler' && strpos($pathinfo, 'crawler/') === 0;
if (empty($username)) {
// 如果是API请求返回JSON
if ($isApiRequest || $request->isAjax()) {
header('Content-Type: application/json; charset=utf-8');
return json([
'code' => 0,
'msg' => '请先登录',
]);
}
// 否则跳转到登录页
return redirect('/login');
}
return $next($request);
}
}