V2EX 首页   注册   登录
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  PHP

Laravel 中使用路由控制权限(不限于 Laravel,只是一种思想)

  •  
  •   DavidNineRoc · 2 小时 21 分钟前 · 190 次点击

    Start

    权限设计是后台管理很重要的一个功能,所以要好好设计。 PHP 已经有很多这方面的packages了,就不用我们重复造轮子了。当然,如果你愿意可以从头开始~


    PS

    以前做权限认证的方式有好几种,我说说常用的两种吧!

    1. 每一个页面认证当前需要的权限一次
    2. 在统一的地方(中间件)验证 先上一下简单的表结构(只保留重要的信息)数据库的模型 ER 图 (ps:这个设计中,用户不会直接拥有权限,只能通过角色继承权限。有很多packages会提供用户可以直接拥有权限功能)

    Model

    模型关联关系处理:

    1. User 模型
    <?php
    
    namespace App\Models;
    
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        use Notifiable;
    	
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];
    
    	// 用户和角色的模型关联关系
        public function roles()
        {
            return $this->belongsToMany(Role::class);
        }
    	
    	/****************************************
    	* 封装一个方法方便使用
    	* 1. 需要的权限
    	* 2. 遍历当期那用户拥有的所有角色
    	* 3. 再通过角色判断是否有当前需要的权限
    	****************************************/
    	public function hasPermission($permissionName)
    	{
    		foreach ($this->roles as $role) {
    			if ($role->permisssions()->where('name', $permissionName)->exists()) {
    				return true;;
    			}
    		}
    		
    		return false;
    	}
    }
    
    
    1. Role 模型
    <?php
    
    namespace App\Models;
    
    class Role extends Model
    {
    	// 用户和角色的模型关联关系
        public function users()
        {
            return $this->belongsToMany(User::class);
        }
    	
    	// 角色和权限的模型关联关系
    	public function permissions()
        {
            return $this->belongsToMany(Permission::class);
        }
    }
    
    1. Permission 模型
    <?php
    
    namespace App\Models;
    
    class Role extends Model
    {
    	// 角色和权限的模型关联关系
        public function roles()
        {
            return $this->belongsToMany(Role::class);
        }
    }
    

    Database Seed

    • 插入一些记录:
    ########################################
    # users:
    +-------+---------+-----------+
    | id    | name    |  password |
    +-----------------+-----------+
    |   1   |  gps    |  123456   |
    +-----------------+-----------+
    |   2   |  david  |  123456   |
    +-----------------+-----------+
    ########################################
    # roles:
    +-------+---------+
    | id    | name    |
    +-----------------+
    |   1   |  admin  |
    +-----------------+
    ########################################
    # permissions:
    +-------+-----------------+
    | id    |       name      |
    +-------------------------+
    |   1   | create_product  |
    |   2   | delete_product  |
    +-------------------------+
    ########################################
    # role_user (用户 gps 拥有 admin 角色身份)
    +---------+---------+
    | role_id | user_id |
    +---------+---------+
    |   1     |   1     |
    +------------------+
    ########################################
    # permission_role (角色 admin 拥有创建商品和删除商品的权限)
    +---------+---------------+
    | role_id | permission_id |
    +---------+---------------+
    |   1     |      1        |
    |   1     |      2        |
    +-------------------------+
    

    First

    第一种大概介绍一下:

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Models\Product;
    
    class ProductsController extends Controller
    {
        public function store(Request $request)
        {
    		// 判断当前登录的用户是否有权限
    		if (! $request->user()->hasPermission('create_product')) {
    			abort(403);
    		}
    		
    		// do something
    		
            return back()->with('status', '添加商品成功');
        }
    
    
        public function destroy(Product $product)
        {
    		// 判断当前登录的用户是否有权限
    		if (! $request->user()->hasPermission('delete_product')) {
    			abort(403);
    		}
    		
    		// do something
    		
            return back()->with('status', '删除商品成功');
        }
    }
    

    Two

    通过上面的代码我们可以看到,即使封装了权限验证的代码,还是要在不同的方法进行验证,而且可扩展性不高,这时候我们只需要在权限表加一个字段,就可以解决问题

    1. permissions (加多一个 route 字段, 如果不在 laravel 中使用,可以加一个 url 字段匹配)
    +-------+------------------+------+-----+---------+----------------+
    | Field | Type             | Null | Key | Default | Extra          |
    +-------+------------------+------+-----+---------+----------------+
    | id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
    | name  | varchar(191)     | NO   |     | NULL    |                |
    | route | varchar(191)     | NO   |     | NULL    |                |
    +-------+------------------+------+-----+---------+----------------+
    2. 这时候插入数据的时候,我们只要做好相关的录入
    +-------+-----------------+------------------+
    | id    |       name      |      route       |
    +-------------------------+------------------+
    |   1   | create_product  | products.store   |
    |   2   | delete_product  | products.destroy |
    +-------------------------+------------------+
    

    添加好数据的时候,我们就不用再控制器里验证了,我们只需要新建一个中间件。

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Route;
    use App\Models\Permission;
    
    class PermissionAuth
    {
        /**
         * 把这个中间件放入路由组,把需要的验证的路由
    	 * 放入这个中间组里
         */
        public function handle($request, Closure $next)
        {
    		/****************************************
    		* 获取当前路由的别名,如果没有返回 null
    		* (不在 laravel 中使用时,可以获取当前 url )
    		****************************************/
            $route = Route::currentRouteName();
    
            // 判断权限表中这条路由是否需要验证
            if ($permission = Permission::where('route', $route)->first()) {
                // 当前用户不拥有这个权限的名字
                if (! auth()->user()->hasPermission($permission->name)) {
                    return response()->view('errors.403', ['status' => "权限不足,需要:{$permission->name}权限"]);
                }
            }
    
            return $next($request);
        }
    }
    
    

    END

    如果是在 laravel 中使用,已经有轮子了,请使用 https://github.com/spatie/laravel-permission

    5 回复  |  直到 2018-03-27 14:33:09 +08:00
        1
    SouthCityCowBoy   1 小时 28 分钟前
    写的很好,我一直在用 entrust,思想是一样的
        2
    brett   1 小时 2 分钟前
    laravel 本来就自带策略哦
        3
    linxb   53 分钟前
    一般都是直接在路由做控制,laravel-permission 挺好用的
        4
    shench   50 分钟前
    写的很好,我已经在用你推荐的包了
        5
    ifconfig   48 分钟前
    @SouthCityCowBoy 请教下用 entrust 的话要自己写界面管理权限么,还是有推荐
    DigitalOcean
    关于   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   鸣谢   ·   2940 人在线   最高记录 3541   ·  
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.0 · 27ms · UTC 07:21 · PVG 15:21 · LAX 00:21 · JFK 03:21
    ♥ Do have faith in what you're doing.
    沪ICP备16043287号-1