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

yipeiwu_com5年前Python基础

示意图:

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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python读取xlsx的方法

如下所示: import xlrd data = xlrd.open_workbook('path') # 第1个sheet table = data.sheet()[0]...

python3调用百度翻译API实现实时翻译

今天需要做一个翻译的工具,找到之前写过的有道翻译,已经不能用了,最后看到百度翻译还不错,不过官方版本是Python2,我需要Python3,就自己写了一个: # coding: ut...

Python的内存泄漏及gc模块的使用分析

一般来说在 Python 中,为了解决内存泄漏问题,采用了对象引用计数,并基于引用计数实现自动垃圾回收。 由于Python 有了自动垃圾回收功能,就造成了不少初学者误认为自己从此过上了好...

解决tensorflow由于未初始化变量而导致的错误问题

我写的这个程序 import tensorflow as tf sess=tf.InteractiveSession() x=tf.Variable([1.0,2.0]) a=tf...

Python利用requests模块下载图片实例代码

本文主要介绍的是关于Python利用requests模块下载图片的相关,下面话不多说了,来一起看看详细的介绍吧 MySQL中事先保存好爬取到的图片链接地址。 然后使用多线程把图片下载到本...