使用 Entrust 扩展包在 Laravel 5 中实现 RBAC 权限管理(二):使用篇

本次针对Laravel5.1.1版本进行的权限验证初窥,记录下进行的过程,以便后期的查阅。安装篇请参考这里

参考
https://packagist.org/packages/zizaco/entrust#5.2.x-dev
https://phphub.org/index.php/topics/166
http://laravelacademy.org/post/3761.html

[TOC]

实例

创建用户组和权限, 并授权用户

/**
 * Display a listing of the resource.
 * 用户列表
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $data = User::all();
    return view('user.index',compact('data'));
}

/**
 * Display a listing of the resource.
 * 用户组列表
 * @return \Illuminate\Http\Response
 */
public function role()
{
    $data = Role::all();
    return view('user.role_list',compact('data'));
}

/**
 * 新增用户组
 *
 * @param AddRoleRequest $request
 * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
 */
public function addRole(AddRoleRequest $request)
{
    $input = $request->except('_token');
    if($request->isMethod('post')){
        $validator = Validator::make($input, $request->rules(),$request->messages());
        if ($validator->fails()) {
            return redirect(route('addRole'))
                ->withErrors($validator)
                ->withInput();
        }

        $res = Role::insert($input);

        if($res){
            return redirect(route('addRole'));
        }else{
            return back()->with('errors','数据提交失败,请稍后重试!');
        }
    }
        return view('user.add_role');

}

/**
 * 编辑角色组
 * @param AddRoleRequest $request
 * @param Role $role
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
public function editRole(AddRoleRequest $request,Role $role)
{
    if($request->isMethod('post')){
        $input = $request->except('_token');
        $res = Role::where('id',$role->id)->update($input);
        if($res){
            return redirect(route('role'));
        }else{
            return back()->with('errors','数据提交失败,请稍后重试!');
        }
    }
    return view('user.edit_role',compact('role'));
}

/**
 * 删除角色组
 */
public function delRole()
{

}

/**
 * 权限列表
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
public function permissions()
{
    $data = Permission::all();
    return view('user.permissions',compact('data'));
}

/**
 * 新增权限
 * @param PermissionsRequest $request
 * @param Permission $permission
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
 */
public function addPermissions(PermissionsRequest $request,Permission $permission)
{
    $input = $request->except('_token');
    if($request->isMethod('post')){
        $res = $permission::create($input);

        if($res){
            return redirect(route('permissions'));
        }else{
            return back()->with('errors','数据提交失败,请稍后重试!');
        }
    }

    return view('user.add_permissions');
}

/**
 * 编辑权限
 * @param PermissionsRequest $request
 * @param Permission $permissions
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
 */
public function editPermissions(PermissionsRequest $request,Permission $permissions){
    if($request->isMethod('post')){
        $input = $request->except('_token');
        $res = $permissions::where('id','=',$permissions->id)->update($input);
        if($res){
            return redirect(route('permissions'));
        }else{
            return back()->with('errors','数据提交失败,请稍后重试!');
        }
    }

    return view('user.edit_permissions',compact('permissions'));
}

/**
 * 查看用户组所拥有的权限
 * @param Role $role
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
 */
public function permisionsToRole(Role $role)
{

    $perssions = Permission::get(); // 获取所有存在的权限

    $this_role_permissions = $role->permissions()->get(['id'])->toArray(); // 通过多对多获取当前用户组所有权限

    $this_permissions = []; // 当前用户所有权限集合
    foreach($this_role_permissions as $permission){
        $this_permissions[] = $permission['id'];
    }

    return view('user.perssions_to_role',compact('role','perssions','this_permissions'));
}

/**
 * 编辑用户组权限
 * @param Request $request
 * @param Role $role
 * @return \Illuminate\Http\RedirectResponse
 */
public function editPersissionToRole(Request $request ,Role $role)
{
    $input = $request->except('_token');

    $role->perms()->sync($input['role_id']);

    return back()->with('errors','更新用户组权限成功!');
}

/**
 * 将用户关联到用户组
 * @param Request $request
 * @param User $user
 * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
 */
public function addUserToRole(Request $request , User $user)
{
    $input = $request->except('_token');
    if($request->isMethod('post')){
        $user->roles()->sync( $input['id'] ); // 使用多对多关联模型将数据同步到 role_user中间表
        return back();
    }

    $roles = Role::all();
    $this_user_roles = $user->roles()->get(['id'])->toArray();

    $this_roles = []; // 当前用户所在用户组
    foreach($this_user_roles as $role){
        $this_roles[] = $role['id'];
    }
    return view('user.add_user_to_role',compact('user','roles','this_roles'));
}

在项目中的使用

基本权限判断

  • 判断用户是否属于某个用户组:

    $user->hasRole("owner");    // false
    $user->hasRole("admin");    // true
    
  • 判断用户是否拥有某个权限 (通过用户组):

    $user->can("create_post"); // true
    $user->can("edit_user"); // false
    

路由过滤

Entrust 还提供帮助方法, 用来做路由过滤,通过权限和角色过滤路由可以在app/Http/routes.php调用如下代码::

// 有 create_post 权限的用户, 才能访问 admin/posts 开头的链接

Entrust::routeNeedsPermission( 'admin/post*', 'create_post' );

// 属于 owner 用户组的人, 才能访问 admin/advanced* 开头的链接

Entrust::routeNeedsRole( 'admin/advanced*', 'owner' );

// 可以在第二个选项传参数组, 当前用户需要符合所有传参的用户组或者权限, 才能授权成功

Entrust::routeNeedsPermission( 'admin/post*', ['create_post','edit_user'] );
Entrust::routeNeedsRole( 'admin/advanced*', ['owner','writer'] );

GitHub地址:https://github.com/curder/laravel5_rbac

参考地址


最后编辑: 于 3年前

标签

评论列表(0)

    暂无评论