Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:中间件的功能类似前置方法, 可以理解为构造方法中自动调用的方法
Auth::user()
获取用户的登录信息$request->route()->action['controller']
获取当前访问路由地址对应的控制器App\Http\Controllers\admins\Home@index
stopos()
获取控制器和方法,然后判断是否存在该菜单,菜单是否可用,是否有权限操作菜单
<?php
namespace App\Http\Middleware;
use Closure;
use Hamcrest\Arrays\IsArray;
//引入数据库查询构造器,链式调用
use Illuminate\Support\Facades\DB;
//引入Auth类,获取当前登录的用户
use Illuminate\Support\Facades\Auth;
use function GuzzleHttp\json_decode;
class RightsVerify
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//获取当前登录用户的用户信息
$user = Auth::user();
//获取当前登录用户的角色id
$gid = $user->gid;
$gInfo = DB::table('admin_group')->where('gid',$gid)->item();
if(!$gInfo):
return response('不存在该角色',200);
endif;
//把所有当前用户可用的菜单保存在数组中
$rights = [];
if($gInfo['rights']):
$rights = json_decode($gInfo['rights'],true);
endif;
//检查当前用户访问的是哪个菜单,是否有权限访问,是否有该菜单
$curUrl = $request->route()->action['controller'];//返回当前访问的路由所对应的控制器和方法
//App\Http\Controllers\admins\Home@index
$pos = strrpos($curUrl,'\\');//从字符串右边开始查找\在字符串中的位置
$curUrl = substr($curUrl,$pos+1);
//Home@index
$pos = strpos($curUrl,'@');//获取分隔符的位置
$con = substr($curUrl,0,$pos);//获取要访问的控制器
$act = substr($curUrl,$pos+1);//获取要访问的方法
//在数据库中查找对应的菜单
$curMenu = DB::table('admin_menu')->where('controller',$con)->where('action',$act)->item();
if(!$curMenu):
return response('不存在此功能',200);
endif;
if($curMenu['status']==1):
return response('此功能已被禁用,请联系管理员开启此功能',200);
endif;
if(!(in_array($curMenu['mid'],$rights))):
return response('没有权限使用此菜单,请更改权限后使用',200);
endif;
// echo '<pre>';
// print_r($curMenu);
// exit;
return $next($request);
}
}
$routeMiddleware
属性
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
//注册权限控制中间件
'rights' => \App\Http\Middleware\RightsVerify::class,
];
}
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function(){
return view('welcome');
});
//登录页面
Route::get('/admins/account/login','admins\Account@login')->name('login');//使用name()方法对路由进行命名
//验证码图片
Route::get('/admins/account/captcha','admins\Account@captcha');
//登录操作
Route::post('/admins/account/dologin','admins\Account@dologin');
//后台首页
//调用框架自带的auth中间件判断是否登录,namespace()方法指定控制器的命令空间,group()方法中是一个回调函数,把一组路由写在这个回调函数中
Route::namespace('admins')->middleware(['auth','rights'])->group(function(){
Route::get('/admins/home/index','Home@index');
Route::get('/admins/home/welcome','Home@welcome');
//账号管理
Route::get('/admins/admin/index','Admin@index');
//添加账号
Route::get('/admins/admin/add','Admin@add');
});