亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home php教程 PHP視頻 Detailed explanation of Laravel5 permission management method

Detailed explanation of Laravel5 permission management method

Dec 23, 2016 pm 05:27 PM

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();
    // 只要有一個(gè)有權(quán)限,就可以進(jìn)入這個(gè)請(qǐng)求
    foreach ($permits as $permit) {
      if ($permit == &#39;*&#39;) {
        return $next($request);
      }
      if ($admin->hasPermission($permit)) {
        return $next($request);
      }
    }
    echo "沒(méi)有權(quán)限,請(qǐng)聯(lián)系管理員";exit;
  }
  // 獲取當(dāng)前路由需要的權(quán)限
  public function getPermission($request)
  {
    $actions = $request->route()->getAction();
    if (empty($actions[&#39;permissions&#39;])) {
      echo "路由沒(méi)有設(shè)置權(quán)限";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;;
  // 判斷是否有某個(gè)權(quán)限
  public function hasPermission($permission)
  {
    $permission_db = $this->permissions;
    if(in_array($permission, $permission_db)) {
      return true;
    }
    return false;
  }
  // permission 是一個(gè)二維數(shù)組
  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);
  }
  // 全局設(shè)置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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72