61 lines
1.5 KiB
PHP
61 lines
1.5 KiB
PHP
<?php
|
||
declare (strict_types = 1);
|
||
|
||
namespace app\middleware;
|
||
|
||
use think\facade\Session;
|
||
|
||
/**
|
||
* 管理员权限验证中间件
|
||
*/
|
||
class Admin
|
||
{
|
||
/**
|
||
* 处理请求
|
||
*
|
||
* @param \think\Request $request
|
||
* @param \Closure $next
|
||
* @return mixed
|
||
*/
|
||
public function handle($request, \Closure $next)
|
||
{
|
||
// 获取路径信息
|
||
$pathinfo = $request->pathinfo();
|
||
|
||
// 判断是否为API请求(非index页面)
|
||
$isApiRequest = $pathinfo !== 'admin' && strpos($pathinfo, 'admin/') === 0;
|
||
|
||
// 检查是否已登录
|
||
$username = Session::get('username');
|
||
|
||
if (empty($username)) {
|
||
// 如果是API请求,返回JSON
|
||
if ($isApiRequest || $request->isAjax()) {
|
||
return json([
|
||
'code' => 0,
|
||
'msg' => '请先登录',
|
||
]);
|
||
}
|
||
// 否则跳转到登录页
|
||
return redirect('/login');
|
||
}
|
||
|
||
// 检查是否为管理员
|
||
$isAdmin = Session::get('is_admin', false);
|
||
|
||
if (!$isAdmin) {
|
||
// 如果是API请求,返回JSON
|
||
if ($isApiRequest || $request->isAjax()) {
|
||
return json([
|
||
'code' => 0,
|
||
'msg' => '无权限访问,需要管理员权限',
|
||
]);
|
||
}
|
||
// 否则跳转到爬虫页面
|
||
return redirect('/crawler');
|
||
}
|
||
|
||
return $next($request);
|
||
}
|
||
}
|