Laravel中间件权限认证模块

先在app目录下面的Middleware目录新增Rightsvalidates.php文件

<?php

namespace app\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class Rightsvalidates
{

    public function handle($request, Closure $next)
    {
        $admin = Auth::guard('admin')->user();
        $role =DB::table('admin_group')->where('gid',$admin->group_id)->item();
        if (!$role){
        return response($this->_noRights('抱歉,角色不存在',$request),200);
    }

        $role['rights']=json_decode($role['rights'],true);
        $actions=$request->route()->getActionName();
        $action_arr=explode('@',$actions);

        $controllers=explode('\\',$action_arr[0]);
        $controller=$controllers[count($controllers)-1];
        $action=$action_arr[1];

        //查菜单
        $menu=DB::table('admin_menu')->where('controller',$controller)->where('action',$action)->item();
        if (!$menu){
            return response($this->_noRights('抱歉,菜单不存在',$request),200);
        }
        if ($menu['status']==1){
            return response($this->_noRights('抱歉,该菜单已被禁用',$request),200);
        }
        //查权限
        if (!in_array($menu['mid'],$role['rights'])){
            //如果验证失败,就不该输出这个页面
            return response($this->_noRights('抱歉,您没有权限操作',$request),200);
        }
        $admin=$admin->toArray();
        $admin['rights']=$role['rights'];
        $request->admin=$admin;
        return $next($request);
    }

    function _noRights($str,$request){
        if ($request->ajax()){
            $msg = json_encode(['code'=>1,'msg'=>$str]);
        }else{
            $msg='<h1>'.$str.'</h1>';
        }
        return $msg;
    }
}

之后在app\Http\kener.php注册

最后在web.php路由管理中调用

发表评论

电子邮件地址不会被公开。 必填项已用*标注