laravel扩展权限校验中间键
1.在Middleware文件夹中创建权限校验中间键也可以用命令(php artisan make:middleware Rightvalidate)
2.Rightvalidate.php写入你要校验的内容
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class Rightvalidate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// 通过$request获取当前访问的菜单id
$url = $request->route()->getActionName();
//分割url拿到方法名称
$res = explode('@', $url);
$action = $res[1]; // 方法名称
//分割URL拿到控制器名称
$res = explode('\\', $res[0]);
$controller = $res[count($res)-1];//控制器名称
// 到数据库中查询菜单id
$curmenu = DB::table('xpcms_admin_menu')->where('controller',$controller)->where('action',$action)->first();
//判断控制器方法是否存在
if(!$curmenu){
return response($this->_norights($request,'当前菜单不存在'),200);
}
//获得登录用户的信息
$_admin = Auth::user()->toArray();
// 管理员的group_id
$group_id = $_admin['group_id'];
// 查询管理组拥有的权限
$rights = DB::table('xpcms_admin_group')->where('gid',$group_id)->first();
if(!$rights){
return response($this->_norights($request,'该角色不存在'),200);
}
// 该用户所能访问的菜单id列表
$mymenus = json_decode($rights->rights,true);
// 当前菜单的id在不在$mymenus里?
if(!in_array($curmenu->mid,$mymenus)){
return response($this->_norights($request,'权限不足'),200);
}
return $next($request);
}
private function _norights($request,$msg){
// 检测访问method
// 如果是浏览器地址栏请求,直接返回$msg
// 如果是ajax请求,返回json
if($request->ajax()){
return json_encode(array('code'=>1,'msg'=>$msg));
}else{
return $msg;
}
}
}
3.在Kernel.php注册你的中间键
4.启用你的中间键