欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

laravel--通用后台管理系统--权限中间件

程序员文章站 2022-05-25 09:09:31
...

学习总结

1.通过Auth::user()获取用户的登录信息

2.通过$request->route()->action['controller']获取当前访问路由地址对应的控制器App\Http\Controllers\admins\Home@index

3.通过字符串函数stopos()获取控制器和方法,然后判断是否存在该菜单,菜单是否可用,是否有权限操作菜单

1.权限中间件RightsVerify.php

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Hamcrest\Arrays\IsArray;
  5. //引入数据库查询构造器,链式调用
  6. use Illuminate\Support\Facades\DB;
  7. //引入Auth类,获取当前登录的用户
  8. use Illuminate\Support\Facades\Auth;
  9. use function GuzzleHttp\json_decode;
  10. class RightsVerify
  11. {
  12. /**
  13. * Handle an incoming request.
  14. *
  15. * @param \Illuminate\Http\Request $request
  16. * @param \Closure $next
  17. * @return mixed
  18. */
  19. public function handle($request, Closure $next)
  20. {
  21. //获取当前登录用户的用户信息
  22. $user = Auth::user();
  23. //获取当前登录用户的角色id
  24. $gid = $user->gid;
  25. $gInfo = DB::table('admin_group')->where('gid',$gid)->item();
  26. if(!$gInfo):
  27. return response('不存在该角色',200);
  28. endif;
  29. //把所有当前用户可用的菜单保存在数组中
  30. $rights = [];
  31. if($gInfo['rights']):
  32. $rights = json_decode($gInfo['rights'],true);
  33. endif;
  34. //检查当前用户访问的是哪个菜单,是否有权限访问,是否有该菜单
  35. $curUrl = $request->route()->action['controller'];//返回当前访问的路由所对应的控制器和方法
  36. //App\Http\Controllers\admins\Home@index
  37. $pos = strrpos($curUrl,'\\');//从字符串右边开始查找\在字符串中的位置
  38. $curUrl = substr($curUrl,$pos+1);
  39. //Home@index
  40. $pos = strpos($curUrl,'@');//获取分隔符的位置
  41. $con = substr($curUrl,0,$pos);//获取要访问的控制器
  42. $act = substr($curUrl,$pos+1);//获取要访问的方法
  43. //在数据库中查找对应的菜单
  44. $curMenu = DB::table('admin_menu')->where('controller',$con)->where('action',$act)->item();
  45. if(!$curMenu):
  46. return response('不存在此功能',200);
  47. endif;
  48. if($curMenu['status']==1):
  49. return response('此功能已被禁用,请联系管理员开启此功能',200);
  50. endif;
  51. if(!(in_array($curMenu['mid'],$rights))):
  52. return response('没有权限使用此菜单,请更改权限后使用',200);
  53. endif;
  54. // echo '<pre>';
  55. // print_r($curMenu);
  56. // exit;
  57. return $next($request);
  58. }
  59. }

2.注册权限控制中间件app/kernel.php中的$routeMiddleware属性

  1. <?php
  2. namespace App\Http;
  3. use Illuminate\Foundation\Http\Kernel as HttpKernel;
  4. class Kernel extends HttpKernel
  5. {
  6. /**
  7. * The application's global HTTP middleware stack.
  8. *
  9. * These middleware are run during every request to your application.
  10. *
  11. * @var array
  12. */
  13. protected $middleware = [
  14. // \App\Http\Middleware\TrustHosts::class,
  15. \App\Http\Middleware\TrustProxies::class,
  16. \Fruitcake\Cors\HandleCors::class,
  17. \App\Http\Middleware\CheckForMaintenanceMode::class,
  18. \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
  19. \App\Http\Middleware\TrimStrings::class,
  20. \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
  21. ];
  22. /**
  23. * The application's route middleware groups.
  24. *
  25. * @var array
  26. */
  27. protected $middlewareGroups = [
  28. 'web' => [
  29. \App\Http\Middleware\EncryptCookies::class,
  30. \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
  31. \Illuminate\Session\Middleware\StartSession::class,
  32. // \Illuminate\Session\Middleware\AuthenticateSession::class,
  33. \Illuminate\View\Middleware\ShareErrorsFromSession::class,
  34. \App\Http\Middleware\VerifyCsrfToken::class,
  35. \Illuminate\Routing\Middleware\SubstituteBindings::class,
  36. ],
  37. 'api' => [
  38. 'throttle:60,1',
  39. \Illuminate\Routing\Middleware\SubstituteBindings::class,
  40. ],
  41. ];
  42. /**
  43. * The application's route middleware.
  44. *
  45. * These middleware may be assigned to groups or used individually.
  46. *
  47. * @var array
  48. */
  49. protected $routeMiddleware = [
  50. 'auth' => \App\Http\Middleware\Authenticate::class,
  51. 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
  52. 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
  53. 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
  54. 'can' => \Illuminate\Auth\Middleware\Authorize::class,
  55. 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
  56. 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
  57. 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
  58. 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  59. 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
  60. //注册权限控制中间件
  61. 'rights' => \App\Http\Middleware\RightsVerify::class,
  62. ];
  63. }

3.在web.php中使用中间件

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. /*
  4. |--------------------------------------------------------------------------
  5. | Web Routes
  6. |--------------------------------------------------------------------------
  7. |
  8. | Here is where you can register web routes for your application. These
  9. | routes are loaded by the RouteServiceProvider within a group which
  10. | contains the "web" middleware group. Now create something great!
  11. |
  12. */
  13. Route::get('/', function(){
  14. return view('welcome');
  15. });
  16. //登录页面
  17. Route::get('/admins/account/login','admins\Account@login')->name('login');//使用name()方法对路由进行命名
  18. //验证码图片
  19. Route::get('/admins/account/captcha','admins\Account@captcha');
  20. //登录操作
  21. Route::post('/admins/account/dologin','admins\Account@dologin');
  22. //后台首页
  23. //调用框架自带的auth中间件判断是否登录,namespace()方法指定控制器的命令空间,group()方法中是一个回调函数,把一组路由写在这个回调函数中
  24. Route::namespace('admins')->middleware(['auth','rights'])->group(function(){
  25. Route::get('/admins/home/index','Home@index');
  26. Route::get('/admins/home/welcome','Home@welcome');
  27. //账号管理
  28. Route::get('/admins/admin/index','Admin@index');
  29. //添加账号
  30. Route::get('/admins/admin/add','Admin@add');
  31. });