Home >php教程 >PHP视频 >Detailed explanation of Laravel5 permission management method

Detailed explanation of Laravel5 permission management method

高洛峰
高洛峰Original
2016-12-23 17:27:101435browse

The example in this article describes the implementation method of Laravel5 permission management. Share it with everyone for your reference, the details are as follows:

Thoughts on permission management

Recently I used laravel to design the backend, and the backend needs to have permission management. Permission management is essentially divided into two parts, first authentication, and then permissions. The authentication part is very easy to do, that is, the administrator logs in and records the session. Laravel also comes with Auth to implement this. The most troublesome thing is permission authentication.

Permission authentication essentially means who has the authority to manage what. There are two dimensions here. Who is the user dimension. In the user dimension, the granularity of permission management can be one user, or it can be grouping users. If users are grouped, the logic involved is that one user can In multiple groups? On the other hand, when managing something, this thing has the dimension of things. A page is a thing, and an element on a page is also a thing. Or to put it more broadly, a function is a thing. Therefore, the most important thing for permission management is to confirm the granularity of these two dimensions. This is no longer a technical matter, this needs to be discussed.

Based on the above thinking, the permission management I want to do this time is based on individuals in the user dimension. It’s just that everyone’s permissions are different. In the east-west dimension, I set the route to the smallest unit, that is, set permission management for a single route.

The following thinking is what to use to mark permissions. You can use bits, characters, or integers. Later, I chose characters based on two considerations: 1. Characters are easy to understand and easy to search in the database. 2. I did not need to search for people with this authority according to a certain authority, that is, there was no need for reverse search. Using bits, the whole Type, etc. are of little significance.

Next, consider how to combine it with laravel. Since I need to set access permissions for each route, of course I hope to configure it in laravel's route.php routing management. The best thing is to have a parameter to set permission during Route::get. The advantage of this is that permission setting is simple. When deciding on routing, I wrote permission control conveniently. The disadvantage is that it is also obvious that you can only write one of the three methods of laravel routing. This is Route::(method).

Basically make the decision and get started.

Routing design

The basic routing is like this

Route::post('/admin/validate', ['uses' => 'AdminController@postValidate', 'permissions'=>['admin.validate', 'admin.index']]);

Here, after the basic routing action is set, a permissions attribute is set. This attribute is designed as an array, because for example, a post request, it may be triggered on a certain page , may also be triggered on another page, then this post request needs to have the routing permissions of both pages.

The permission control of admin.validate is used here. In this way, permissions can be grouped. Admin is all about admin-related groups. In the database, I will store a two-dimensional array, [admin] => ['validate' , 'index']; What is the advantage of storing it as a two-dimensional array instead of one dimension? Generally, the background display has two dimensions, one is the tab bar in the head, and the other is the nav bar on the left, that is to say, this two-dimensional There is a one-to-one correspondence between the array and the tab and nav columns in the background.

Middleware design

Okay, now we will hang up the middleware and set all routes to use this middleware

<?php namespace App\Http\Middleware;
use Illuminate\Support\Facades\Session;
use Closure;
class Permission {
  /**
   * Handle an incoming request.
   *
   * @param \Illuminate\Http\Request $request
   * @param \Closure $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
    $permits = $this->getPermission($request);
    $admin = \App\Http\Middleware\Authenticate::getAuthUser();
    // 只要有一个有权限,就可以进入这个请求
    foreach ($permits as $permit) {
      if ($permit == &#39;*&#39;) {
        return $next($request);
      }
      if ($admin->hasPermission($permit)) {
        return $next($request);
      }
    }
    echo "没有权限,请联系管理员";exit;
  }
  // 获取当前路由需要的权限
  public function getPermission($request)
  {
    $actions = $request->route()->getAction();
    if (empty($actions[&#39;permissions&#39;])) {
      echo "路由没有设置权限";exit;
    }
    return $actions[&#39;permissions&#39;];
  }
}

The most critical thing here is the getPermission function, from $request->route()-> ;getAction() to get the action definition of this route, and then get the route permissions defined in route.php from the permissions field.

Then the middleware above has:

admin−>hasPermission(admin−>hasPermission(permit);

This involves the design of the model.

Model design

<?php namespace App\Models\Admin;
use App\Models\Model as BaseModel;
class Admin extends BaseModel {
  protected $table = &#39;admin&#39;;
  // 判断是否有某个权限
  public function hasPermission($permission)
  {
    $permission_db = $this->permissions;
    if(in_array($permission, $permission_db)) {
      return true;
    }
    return false;
  }
  // permission 是一个二维数组
  public function getPermissionsAttribute($value)
  {
    if (empty($value)) {
      return [];
    }
    $data = json_decode($value, true);
    $ret = [];
    foreach ($data as $key => $value) {
      $ret[] = $key;
      foreach ($value as $value2) {
        $ret[] = "{$key}.{$value2}";
      }
    }
    return array_unique($ret);
  }
  // 全局设置permission
  public function setPermissionsAttribute($value)
  {
    $ret = [];
    foreach ($value as $item) {
      $keys = explode(&#39;.&#39;, $item);
      if (count($keys) != 2) {
        continue;
      }
      $ret[$keys[0]][] = $keys[1];
    }
    $this->attributes[&#39;permissions&#39;] = json_encode($ret);
  }
}

In the database, I store the two-dimensional array as json, and use the get and set methods of laravel's Attribute to complete the connection between the json in the database and the external program logic. Then hasPermission seems very easy, just judge in_array directly and it will be ok.

Follow-up

The logic of this permission authentication will be clear. Then if a tab or nav on the page needs to be displayed to users with different permissions, you only need to judge in the view

@if ($admin->hasPermission(&#39;admin.index&#39;))
@endif

to determine whether the user can see the tab.

Summary

This is a not too complicated user permissions implementation, but I feel it can meet most of the background needs. Of course, there may be many points that can be optimized. For example, can permission support regular expressions? If hasPermission is stored in nosql or pg, is it not necessary to perform json data parsing? A direct DB request can determine whether there is a permission or the like?

I hope this article will be helpful to everyone’s PHP program design based on the Laravel framework.

For more detailed explanations of Laravel5 permission management methods and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Related articles

See more