溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django 權(quán)限認證(根據(jù)不同的用戶,設(shè)置不同的顯示和訪問權(quán)限)

發(fā)布時間:2020-09-12 02:48:41 來源:腳本之家 閱讀:169 作者:hahei2020 欄目:開發(fā)技術(shù)

示意圖:

Django 權(quán)限認證(根據(jù)不同的用戶,設(shè)置不同的顯示和訪問權(quán)限)

html:(模態(tài)框等 html和js代碼,參考:Django 創(chuàng)建/刪除用戶)

{# 權(quán)限管理 #}
  <div id="permissionManageDiv" >
    <div>
      <h5 >選擇用戶</h5>
      <hr  />
      <select name="usernamePermission" id="usernamePermission" class="selectpicker" data-live-search="true">
        {% for user in users %}
          <option value="{{ user.username }}">{{ user.username }}</option>
        {% endfor %}
      </select>
      <hr />
    </div>

    <div>
      <h5 >勾選權(quán)限</h5>
      <hr  />
      <div >
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">玩家管理</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="0" />
          </span>
        </div>
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">聯(lián)盟管理</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="1" />
          </span>
        </div>
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">公告郵件</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="2" />
          </span>
        </div>
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">訂單系統(tǒng)</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="3" />
          </span>
        </div>
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">禮包獎勵</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="4" />
          </span>
        </div>
      </div>

      <div>
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">客服反饋</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="5" />
          </span>
        </div>
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">玩家日志</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="6" />
          </span>
        </div>
        <div class="input-group input-group-lg" >
          <span class="input-group-addon">服務(wù)器管理</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="7" />
          </span>
        </div>
        <div class="input-group input-group-lg">
          <span class="input-group-addon">管理員管理</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="8" />
          </span>
        </div>
      </div>
    </div>
    <button type="button" id="changePermissionBtn" class="btn btn-default"  data-toggle="modal" data-target="#alertTip" data-whatever="重置權(quán)限?" >提&nbsp;&nbsp;交</button>
  </div>

js:

// 修改權(quán)限
function changePermission() {
  var permissionList = $('input[name="permissionList"]:checked');
  var permissions = '';
  $.each(permissionList, function (index, value, array) {
    if (index+1 == permissionList.length) {  // 最后一位,不加逗號
      permissions += permissionList[index].value;
    } else {
      permissions += permissionList[index].value + ', ';
    }
  });
  $.ajax({
    url: '/changePermission',
    type: 'POST',
    data: {
      username: $('#usernamePermission').val(),
      permissions: permissions
    },
    success: function (data, textStatus) {
      if (data == 1) {
        alert('修改成功!');
        window.location.href = 'index';

      } else if (data == -1) {
        alert('未知錯誤!');
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert(errorThrown);
    }
  })
}

Django models 中,建立 模型: (這一步很重要!?。。?

– 建立好后,記得用 makemigrations 和 migrate 同步一下!!

from django.db import models

class Permission(models.Model):
  class Meta:
    #權(quán)限信息,這里定義的權(quán)限的名字,后面是描述信息,描述信息是在django admin中顯示權(quán)限用的
    permissions = (
      ('views_slg_users_tem', '查看玩家管理'),
      ('views_slg_alliance_tem', '查看聯(lián)盟管理'),
      ('views_slg_mail_notice_tem', '查看公告郵件'),
      ('views_slg_order_tem', '查看訂單系統(tǒng)'),
      ('views_slg_reward_tem', '查看禮包獎勵'),
      ('views_slg_service_reply_tem', '查看客服反饋'),
      ('views_slg_user_log_tem', '查看玩家日志'),
      ('views_slg_server_tem', '查看服務(wù)器管理'),
      ('views_slg_manager_tem', '查看管理員管理'),
    )

建立好后,數(shù)據(jù)庫表(auth_permission)類似于這樣: (id 那一列,很重要??!我們后面添加權(quán)限要用到的!?。?/p>

Django 權(quán)限認證(根據(jù)不同的用戶,設(shè)置不同的顯示和訪問權(quán)限)

后端python–views視圖:

from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.views.decorators.http import require_http_methods
from django.http import HttpResponse
from django.shortcuts import render
from slg.models.slg.slg_manager_tem import db_change_permission)

# 修改權(quán)限
@login_required(login_url='slg:login')
@require_http_methods(["POST"])
@permission_required('slg.views_slg_manager_tem', login_url='slg:get_permissionDenied')
def change_permission(request):
  permissionsList = [
            'views_slg_users_tem',
            'views_slg_mail_notice_tem',
            'views_slg_order_tem',
            'views_slg_reward_tem', 
            'views_slg_service_reply_tem',
            'views_slg_user_log_tem', 
            'views_slg_server_tem', 
            'views_slg_manager_tem'
            ]
  username = request.POST['username']
  permissions = request.POST['permissions'].split(', ')

  if permissions[0] != '':  # 不為空時
    for index, value in enumerate(permissions):
      permissions[index] = permissionsList[int(value)]  # 將 數(shù)字 替換為 上面數(shù)組中的 字符串
    print(permissions)
  else:
    permissions = []

  changeResult = db_change_permission(username, permissions)
  return HttpResponse(changeResult)

后端python–models視圖:

from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from django.db.utils import IntegrityError
from . import db_models as db

# 修改權(quán)限
def db_change_permission(username, permissions):
  try:
    user = User.objects.get(username=username)
    if permissions:
      pers = []
      for per in permissions:
        db_per = db.AuthPermission.objects.filter(codename=per).values('id')[0]['id']  # 只把 id 取出來
        pers.append(db_per)
      #print(pers)  # 形如: [147, 150, 152] 數(shù)字為 auth_permission 中的 id
      user.user_permissions = pers # 這里,只能 加 id,加 codename 是不行的?。?!

    else:
      user.user_permissions.clear()
    User.objects.get(username=username)  # 刷新 緩存
    #print(user.get_all_permissions())

  except Exception:
    return -1
  else:
    return 1  # 修改成功

錯誤頁面相關(guān): (它是類似于:403, 404 等頁面的匯總,也需要設(shè)置相關(guān)路由)

permissionDenied.html:

<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
  <meta charset="UTF-8">
  <title>403</title>
</head>
<body>
  <h2>403</h2>
  <h3>You don't have enought permissions to this action!</h3>
</body>
</html>

view視圖:

from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods
from django.shortcuts import render

# GET 渲染 403頁面
@login_required(login_url='slg:login')
@require_http_methods(["GET", "POST"])
def get_permissionDenied(request):
  return render(request, 'slg/permissionDenied.html')

url路由:

'''總路由,路由分發(fā)地'''
from django.conf.urls import url, include

urlpatterns = [
  url(r'^', include('slg.urls.slg.error')),           # 錯誤頁面 相關(guān)路由
]
'''子路由,這里進入具體的html頁面'''
from django.conf.urls import url
from slg.views.slg import error

urlpatterns = [
  url(r'^permissionDenied$', error.get_permissionDenied, name='get_permissionDenied'), # 403頁面
]

正常頁面的 權(quán)限設(shè)置:

base.html:(模板頁面,所有頁面都繼承于此)

 {% if 'slg.views_slg_users_tem' in perms %}   {# 判斷 是否 有訪問權(quán)限,沒有的話,就不顯示該菜單 #}
      <li role="presentation" class="main-menu" id="top_one">
        <a href="{% url 'slg:get_slg_users_tem' %}" rel="external nofollow" ><span class="glyphicon glyphicon-fire"></span>玩家管理</a>
      </li>
    {% endif %}

其他 veiws視圖 中的設(shè)置:

from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User
from django.views.decorators.http import require_http_methods
from django.shortcuts import render

# GET 渲染頁面 (其他的POST請求中,最好也加入 @permission_required 用來限制訪問)
@login_required(login_url='slg:login')
@require_http_methods(["GET"])
@permission_required('slg.views_slg_users_tem', login_url='slg:get_permissionDenied') #權(quán)限裝飾器
def get_users_tem(request):
  perms = User.get_all_permissions(request.user)  #獲取 訪問請求 用戶的 所有權(quán)限
  context = {"perms": perms}
  return render(request, 'slg/slg_users_tem.html', context=context)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI