65 lines
2.2 KiB
PHP
Executable File
65 lines
2.2 KiB
PHP
Executable File
<?php
|
|
namespace app\middleware;
|
|
|
|
use Closure;
|
|
use app\model\AuthRule;
|
|
use think\facade\Cache;
|
|
|
|
class Auth
|
|
{
|
|
public function handle($request, Closure $next)
|
|
{
|
|
$auth = session('auth');
|
|
if(!$auth){
|
|
return redirect(url('manager.login/index'));
|
|
}
|
|
// 角色权限
|
|
$rules = Cache::get('group_rules_'.$auth['groupId']);
|
|
$ruleNames = Cache::get('rule_names_'.$auth['groupId']);
|
|
//如果是超级管理员,不用验证权限,给予所有权限
|
|
if(empty($rules)){
|
|
$ruleNames = [];
|
|
if($auth['groupId'] == 1){
|
|
$rules = AuthRule::getListTree(0);
|
|
}else{
|
|
// 角色权限 + 基本权限
|
|
$rules = AuthRule::getAuthListByRuleIDs($auth['groupId']);
|
|
}
|
|
foreach($rules as &$rule){
|
|
if(!stripos($rule['name'],'/')){
|
|
$rule['name'] = $rule['name'].'/index';
|
|
}
|
|
$ruleNames[] = strtolower($rule['name']);
|
|
if(isset($rule['children']) && !empty($rule['children'])){
|
|
foreach($rule['children'] as &$child){
|
|
if(!stripos($child['name'],'/')){
|
|
$child['name'] = $child['name'].'/index';
|
|
}
|
|
$ruleNames[] = strtolower($child['name']);
|
|
}
|
|
}
|
|
|
|
}
|
|
// 对角色赋予权限缓存,角色权限更新时需要同步更新缓存
|
|
Cache::set('group_rules_'.$auth['groupId'], $rules);
|
|
Cache::set('rule_names_'.$auth['groupId'], $ruleNames);
|
|
}
|
|
if($auth['groupId'] == 1){
|
|
return $next($request);
|
|
}
|
|
|
|
$controller = strtolower(request()->controller());
|
|
$controller = str_replace('manager.', '', $controller);
|
|
$action = request()->action();
|
|
$name = strtolower($controller.'/'.$action);
|
|
if(!empty($ruleNames) && in_array($name, $ruleNames, true)){
|
|
return $next($request);
|
|
}
|
|
if(request()->isAjax()){
|
|
return json(['code' => 1,'msg' => '没有权限']);
|
|
}else{
|
|
exit('无操作权限') ;
|
|
}
|
|
|
|
}
|
|
} |