后台框架搭建
后台验证用户名和密码
使用Auth::attempt方法验证,返回true或者false<br />注意引用 use Illuminate\Support\Facades\Auth;
<br />注意在model中指定查询的表名 protected $table='xpcms_admin';
if (Auth::attempt(['username'=>$username,'password'=>$pwd,'status'=>1])){
return json_encode(array('code'=>0,'msg'=>'登录成功'));
}else{
return json_encode(array('code'=>1,'msg'=>'登录失败'));
}
使用auth中间件验证登录
实现直接输入路由,验证是否登录,没登录直接跳转到登录页面
Route::get('/admins/account/login', 'admins\Account@login')->name('login');
Route::get('/admins/home/index', 'admins\Home@index')->middleware('auth');
使用自定义中间件控制访问菜单权限
通过session查出group_id,group_id对应group表中的gid,可以查出当前登录者的权限范围rights<br />通过controller和action查出访问的mid,看看这个mid在不在登陆者权限范围内,就可以决定是否能够访问该菜单
定义中间件
<?php
//权限验证中间件
namespace app\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class Rightvalidates{
public function handle($request,Closure $next){
//通过$request获取当前访问的菜单id
$url = $request->route()->getActionName();
$res = explode('@',$url);
//取出方法名称
$action = $res[1];
$res = explode('\\',$res[0]);
$controller = $res[count($res)-1];
$curmenu = DB::table('xpcms_admin_menu')->where('controller',$controller)->where('action',$action)->first();
if (!$curmenu){
return response('当前菜单不存在',200);
}
//使用Auth的user方法,从session中取出attempt存的信息
$_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('该角色不存在',200);
}
//该用户所能访问的菜单id列表
$mymenus = json_decode($rights->rights,true);
//当前菜单的id在不在$mymenus里面?
if (!in_array($curmenu->mid,$mymenus)){
return response('权限不足',200);
}
return $next($request);
}
}
注册中间件
在 \App\Http\Middleware
中注册
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,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
//权限校验中间件
'rightvalidates' => \App\Http\Middleware\Rightvalidates::class,
];
触发中间件
Route::namespace('admins')->middleware(['auth','rightvalidates'])->group(function (){
Route::get('/admins/home/index', 'Home@index');
Route::get('/admins/home/welcome', 'Home@welcome');
});
路由分组管理
Route::namespace('admins')->middleware('auth')->group(function (){
Route::get('/admins/home/index', 'Home@index');
Route::get('/admins/home/welcome', 'Home@welcome');
});