laravel 中的rbac自己简单的实现
Posted 段佳伟的小憩屋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel 中的rbac自己简单的实现相关的知识,希望对你有一定的参考价值。
用户表
CREATE TABLE `sys_user` (
`id` varchar(64) COLLATE utf8_bin NOT NULL COMMENT ‘用户编号‘,
`ids` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘自增的id‘,
`login_name` varchar(100) COLLATE utf8_bin NOT NULL COMMENT ‘登录名‘,
`password` varchar(100) COLLATE utf8_bin NOT NULL COMMENT ‘密码‘,
`name` varchar(30) COLLATE utf8_bin DEFAULT NULL COMMENT ‘姓名‘,
`email` varchar(200) COLLATE utf8_bin NOT NULL COMMENT ‘邮箱‘,
`phone` varchar(20) COLLATE utf8_bin NOT NULL COMMENT ‘电话‘,
`mobile` varchar(20) COLLATE utf8_bin DEFAULT NULL COMMENT ‘手机‘,
`login_ip` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT ‘最后登陆IP‘,
`login_date` datetime DEFAULT NULL COMMENT ‘最后登陆时间‘,
`login_flag` int(11) DEFAULT NULL COMMENT ‘是否可登录,1:可登陆,0:不可登陆‘,
`user_type` int(11) DEFAULT NULL COMMENT ‘用户类型‘,
`photo` varchar(1000) COLLATE utf8_bin DEFAULT NULL COMMENT ‘用户头像(暂定保存路径)‘,
`create_time` datetime DEFAULT NULL COMMENT ‘创建时间(申请时间)‘,
`update_time` datetime DEFAULT NULL COMMENT ‘更新时间(每次修改需要更新)‘,
`status` int(1) DEFAULT ‘2‘ COMMENT ‘状态,0:无效;1:有效;2:待审核‘,
`unit_price` double DEFAULT ‘0‘ COMMENT ‘用户单价(单位:元)‘,
`balance` double DEFAULT ‘0‘ COMMENT ‘用户余额(单位:元)‘,
`password_md5` char(100) COLLATE utf8_bin DEFAULT NULL COMMENT ‘md5密码‘,
PRIMARY KEY (`ids`,`id`),
KEY `IDX_SYS_USER_LOGINNAME` (`login_name`),
KEY `IDX_SYS_USER_PHONE` (`phone`),
KEY `IDX_SYS_USER_MOBILE` (`mobile`),
KEY `IDX_SYS_USER_EMAIL` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
角色组
CREATE TABLE `sys_role` (
`id` varchar(64) COLLATE utf8_bin NOT NULL COMMENT ‘角色ID‘,
`ids` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘role表中的自增id‘,
`name` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT ‘角色名称‘,
`create_time` datetime DEFAULT NULL COMMENT ‘创建时间‘,
`update_time` datetime DEFAULT NULL COMMENT ‘更新时间‘,
`remarks` varchar(500) COLLATE utf8_bin DEFAULT NULL COMMENT ‘角色说明‘,
PRIMARY KEY (`ids`,`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
用户角色组关系表
CREATE TABLE `sys_user_role` (
`user_id` varchar(64) COLLATE utf8_bin NOT NULL COMMENT ‘用户ID‘,
`role_id` varchar(64) COLLATE utf8_bin NOT NULL COMMENT ‘角色ID‘,
`user_ids` int(11) NOT NULL COMMENT ‘user表中的自增id‘,
`role_ids` int(11) NOT NULL COMMENT ‘role表中的自增id‘
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
权限表
CREATE TABLE `sys_menu` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘编号‘,
`parent_id` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT ‘父级编号‘,
`id_path` varchar(2000) COLLATE utf8_bin DEFAULT NULL COMMENT ‘编号路径‘,
`name` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT ‘功能菜单名称‘,
`name_path` varchar(2000) COLLATE utf8_bin DEFAULT NULL COMMENT ‘功能菜单路径‘,
`sort` decimal(10,0) DEFAULT NULL COMMENT ‘排序‘,
`href` varchar(2000) COLLATE utf8_bin DEFAULT NULL COMMENT ‘链接‘,
`icon` varchar(1000) COLLATE utf8_bin DEFAULT NULL COMMENT ‘图标路径‘,
`permission` varchar(200) COLLATE utf8_bin DEFAULT NULL COMMENT ‘shiro权限标识‘,
`is_show` int(1) DEFAULT NULL COMMENT ‘是否在菜单中显示,1:显示,0:不显示‘,
`remarks` varchar(2000) COLLATE utf8_bin DEFAULT NULL COMMENT ‘功能菜单描述‘,
`platform` tinyint(2) DEFAULT ‘0‘ COMMENT ‘平台 1 php后台‘,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=70012 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
权限角色关系表
CREATE TABLE `sys_role_menu` (
`role_id` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT ‘角色ID‘,
`menu_id` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT ‘菜单ID‘,
`role_ids` int(11) NOT NULL COMMENT ‘role表中的自增id‘
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
验证当前用户的权限需要 先获取当前用户的信息(id) 然后去用户角色表中查找他对应的角色 然后再去角色权限表中查找出当前的用户的权限列表 看当前访问的路由是否在权限列表中 如果在就可以访问 如果不在就禁止访问
这些信息都需要保存到session中 然后验证的时候再取出来
login.php
<?php namespace iqiyi\Http\Controllers; use iqiyi\Models\SysRoleMenu; use iqiyi\Models\SysUserRole; use iqiyi\Models\SysRole; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use iqiyi\Models\SysUser; use Illuminate\Support\Facades\DB; class Login extends Controller { public function __construct() { DB::connection()->enableQueryLog(); // 开启查询日志 } /** * @param Request $request * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void * */ public function index(Request $request) { DB::connection()->enableQueryLog(); $username = $request->username; $password = $request->password; $errors = $request->errors; $password = md5($password.config(‘iqiyi.md5key‘,‘Iqiyi‘)); $users = SysUser::where([‘login_name‘=>$username,‘password_md5‘=>$password])->first(); //echo $users[‘id‘]; //dd($users); $pri = []; // if($users){ // // 角色 // $roleids = []; // $role = SysUserRole::where(‘user_id‘,$users->id)->select(‘role_id‘)->where(‘role_id‘,‘<>‘,‘‘)->get(); // foreach ($role as $k=>$v){ // $roleids[] = $v[‘role_id‘]; // } // // 权限 // $menu = SysRoleMenu::whereIn(‘role_id‘,$roleids)->select(‘m.href‘)->leftjoin(‘sys_menu as m‘,‘sys_role_menu.menu_id‘,‘=‘,‘m.id‘)->get()->toArray(); // // foreach ($menu as $k=>$v){ // $pri[] = $v[‘href‘]; // } //// print_r(DB::getQueryLog()); //// dd($users, $menu, $pri); // } if($users){ // 角色 $roleids = []; $role = SysUserRole::where(‘user_ids‘,$users->ids)->select(‘role_ids‘)->where(‘role_ids‘,‘<>‘,‘‘)->get(); foreach ($role as $k=>$v){ $roleids[] = $v[‘role_ids‘]; } // 权限 $menu = SysRoleMenu::whereIn(‘role_ids‘,$roleids)->select(‘m.href‘)->leftjoin(‘sys_menu as m‘,‘sys_role_menu.menu_id‘,‘=‘,‘m.id‘)->get()->toArray(); foreach ($menu as $k=>$v){ $pri[] = $v[‘href‘]; } // print_r(DB::getQueryLog()); // dd($users, $role, $roleids, $menu, $pri); } // 权限判断 // if($pri && $users){ // Session::put(‘userid‘,$users[‘id‘]); // Session::put(‘login_name‘,$users[‘login_name‘]); // Session::put(‘pri‘,json_encode($pri)); // echo 1; // $sessions = $request->session()->all(); // dump($sessions); // die; // return redirect(‘/‘); // } if($pri && $users){ Session::put(‘userid‘,$users[‘ids‘]); Session::put(‘login_name‘,$users[‘login_name‘]); Session::put(‘pri‘,json_encode($pri)); // dump($users); // echo 1; // $sessions = $request->session()->all(); // dump($sessions); // die; return redirect(‘/‘); } $error = ‘‘; if($username && !$users){ $error = ‘用户名或密码错误‘; } if(!$pri && $users){ $error = ‘用户没有权限‘; } return view(‘login‘)->with([ ‘error‘=>$error, ‘errors‘=>$errors, ]); } /** * @param Request $request */ public function logout(Request $request){ Session::forget(‘userid‘); return redirect(‘/‘); } //$queries = \DB::getQueryLog(); // 获取查询日志 //dd($queries); // 即可查看执行的sql,传入的参数等等 }
middleware/authAdmin.php (中间件)
<?php namespace iqiyi\Http\Middleware; use Closure; use Illuminate\Support\Facades\Session; class authAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $userid = Session::get(‘userid‘); //dd(json_decode($pri,true)); $pri = Session::get(‘pri‘); // dump($userid, $pri); if (!$userid || !$pri) { return redirect(‘/login‘); } $url = $request->getRequestUri(); $postion = strpos($url, ‘?‘); // 有?的标志 if ($postion) { $url = substr($url, 0, strpos($url, ‘?‘)); // 把路径后面的?参数去掉 } $pri = json_decode($pri,true); // dd($userid, $url, $postion, $pri); if ($url ==‘/‘) { return $next($request); } if( !in_array($url,$pri)){ // echo ‘error‘; // return view(‘error‘); return response()->view(‘error‘); } if( !$userid){ return redirect(‘/login?errors=没有权限‘); } return $next($request); } }
给控制器配置中间件
routes/web.php
<?php /* |-------------------------------------------------------------------------- | 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::group([‘middleware‘ => [‘\iqiyi\Http\Middleware\VerifyCsrfToken::class‘]], function () { //支付订单 Route::any(‘order/{action}‘, function(\iqiyi\Http\Controllers\Order $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); // 报告 Route::any(‘report/{action}‘, function(\iqiyi\Http\Controllers\Report $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); // 数据统计 Route::any(‘statistics/{action}‘, function(\iqiyi\Http\Controllers\Statistics $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); // 图片管理 Route::any(‘img/{action}‘, function(\iqiyi\Http\Controllers\Img $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); //dump($request); })->middleware(‘authAdmin‘); // 用户管理 Route::any(‘user/{action}‘, function(\iqiyi\Http\Controllers\User $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); // 角色管理 Route::any(‘role/{action}‘, function(\iqiyi\Http\Controllers\Role $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); // 菜单管理 Route::any(‘menu/{action}‘, function(\iqiyi\Http\Controllers\Menu $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); Route::any(‘/login‘, ‘[email protected]‘); Route::any(‘logout‘, ‘[email protected]‘); Route::any(‘/‘, ‘[email protected]‘)->middleware(‘authAdmin‘); Route::any(‘import‘, ‘[email protected]‘)->middleware(‘authAdmin‘); Route::any(‘import/{action}‘,function(\iqiyi\Http\Controllers\Import $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); Route::any(‘stock/{action}‘,function(\iqiyi\Http\Controllers\Stock $index, $action,\Illuminate\Http\Request $request ){ return $index->$action($request); })->middleware(‘authAdmin‘); Route::get(‘downreport/{filename}/{expname}‘, function($filename,$expname) { return response()->download(storage_path(‘report/‘.$filename),$expname.‘.xls‘); })->middleware(‘authAdmin‘); // Route::any(‘channel/{action}‘,function(\iqiyi\Http\Controllers\Channel $index, $action,\Illuminate\Http\Request $request ){ // return $index->$action($request); // })->middleware(‘authAdmin‘); Route::any(‘importlist‘, ‘[email protected]‘)->middleware(‘authAdmin‘); });
->middleware(‘xxx‘)
以上是关于laravel 中的rbac自己简单的实现的主要内容,如果未能解决你的问题,请参考以下文章