亲宝软件园·资讯

展开

Django 权限认证(根据不同的用户,设置不同的显示和访问权限)

人气:0

示意图:

html:(模态框等 html和js代码,参考:Django 创建/删除用户

{# 权限管理 #}
  <div id="permissionManageDiv" style="margin-left: 10px; display: none;">
    <div>
      <h4 style="margin-top: 15px;">选择用户</h4>
      <hr style="margin-top: 5px;" />
      <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>
      <h4 style="margin-top: 15px;">勾选权限</h4>
      <hr style="margin-top: 5px;" />
      <div style="margin-bottom: 10px;">
        <div class="input-group input-group-lg" style="float: left; margin-right: 10px;">
          <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" style="float: left; margin-right: 10px;">
          <span class="input-group-addon">联盟管理</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="1" />
          </span>
        </div>
        <div class="input-group input-group-lg" style="float: left; margin-right: 10px;">
          <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" style="float: left; margin-right: 10px;">
          <span class="input-group-addon">订单系统</span>
          <span class="input-group-addon">
            <input type="checkbox" name="permissionList" value="3" />
          </span>
        </div>
        <div class="input-group input-group-lg" style="">
          <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" style="float: left; margin-right: 10px;">
          <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" style="float: left; margin-right: 10px;">
          <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" style="float: left; margin-right: 10px;">
          <span class="input-group-addon">服务器管理</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" style="width: 100px; margin-top: 15px;" data-toggle="modal" data-target="#alertTip" data-whatever="重置权限?" >提  交</button>
  </div>

js:

// 修改权限
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:
    #权限信息,这里定义的权限的名字,后面是描述信息,描述信息是在django admin中显示权限用的
    permissions = (
      ('views_slg_users_tem', '查看玩家管理'),
      ('views_slg_alliance_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', '查看管理员管理'),
    )

建立好后,数据库表(auth_permission)类似于这样: (id 那一列,很重要!!我们后面添加权限要用到的!!)

后端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)

# 修改权限
@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)]  # 将 数字 替换为 上面数组中的 字符串
    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

# 修改权限
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] 数字为 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  # 修改成功

错误页面相关: (它是类似于:403, 404 等页面的汇总,也需要设置相关路由)

permissionDenied.html:

<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
  <meta charset="UTF-8">
  <title>403</title>
</head>
<body>
  <h1>403</h1>
  <h2>You don't have enought permissions to this action!</h2>
</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路由:

'''总路由,路由分发地'''
from django.conf.urls import url, include

urlpatterns = [
  url(r'^', include('slg.urls.slg.error')),           # 错误页面 相关路由
]
'''子路由,这里进入具体的html页面'''
from django.conf.urls import url
from slg.views.slg import error

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

正常页面的 权限设置:

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

 {% if 'slg.views_slg_users_tem' in perms %}   {# 判断 是否 有访问权限,没有的话,就不显示该菜单 #}
      <li role="presentation" class="main-menu" id="top_one">
        <a href="{% url 'slg:get_slg_users_tem' %}" rel="external nofollow" style="margin-left: 5px;"><span class="glyphicon glyphicon-fire"></span>玩家管理</a>
      </li>
    {% endif %}

其他 veiws视图 中的设置:

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') #权限装饰器
def get_users_tem(request):
  perms = User.get_all_permissions(request.user)  #获取 访问请求 用户的 所有权限
  context = {"perms": perms}
  return render(request, 'slg/slg_users_tem.html', context=context)

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论