权限组件
简单实例
models.py
class User(models.Model): name = models.CharField(max_length=32) pwd = models.CharField(max_length=32) user_type = models.IntegerField(choices=((1,"超级管理员"), (2,"会员"), (3,"游客")), default=3)
permisssion.py
from rest_framework.permissions import BasePermission class VIPPermission(BasePermission): message = "游客无法查看该部分内容" def has_permission(self, request, views): if request.user.user_type == 3: return False return True
auth.py
from rest_framework.authentication import BaseAuthentication from rest_framework.exceptions import AuthenticationFailed from app01 import models import hashlib def get_token(user_id): salt = "shan" md = hashlib.md5() # 通过id生成随机字符串,并加盐 md.update(str(user_id).encode("utf8")) md.update(salt.encode("utf8")) return md.hexdigest() class Authentication(BaseAuthentication): def authenticate(self, request): # 服务端不保存token的用户认证 # 从请求头中取出token和用户的id,再次通过id生成token去校验(这里可改进,将id拼接到token中,这样就无需另外传id) token = request.META.get("HTTP_TOKEN") user_id = request.META.get("HTTP_ID") if user_id: confirm_token = get_token(user_id) if confirm_token == token: user_obj = models.User.objects.filter(id=user_id).first() # 返回的第一个参数传给request.user,在后面可直接取得登录用户对象 return user_obj, True # request.user,request.auth raise AuthenticationFailed("您尚未登录")
settings.py
REST_FRAMEWORK = { # 配置全局的用户登录认证 "DEFAULT_AUTHENTICATION_CLASSES":["app01.service.auth.Authentication",], # 配置全局的权限限制 "DEFAULT_PERMISSION_CLASSES":["app01.service.permission.VIPPermission",] }
vies.py
from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rest_framework.views import APIView from app01 import models from django.core.exceptions import ObjectDoesNotExist from app01.service import auth from app01 import modelserializer class LoginView(APIView): authentication_classes = [] def post(self, request): respone = {"code": 100, "msg": "登录成功"} name = request.data.get("name") pwd = request.data.get('pwd') try: user_obj = models.User.objects.filter(name=name, pwd=pwd).get() token = auth.get_token(user_obj.id) respone["token"] = token except ObjectDoesNotExist as e: respone["code"] = 101 respone["msg"] = "用户名或密码错误" return Response(respone)
总结:
-写一个权限类 class MyPermision(BasePermission): message = '不是超级用户,查看不了' def has_permission(self,request,view): if request.user.user_type==1: return True else: return False -局部使用 -在视图类中配置: permission_classes=[MyPermision,] -全局使用 -在setting中配置 'DEFAULT_PERMISSION_CLASSES':['自定义的权限类'] -局部禁用: permission_classes=[] -返回的提示是中文: message=中文
源码分析
注:
权限类使用顺序:先用视图类中的权限类,再用settings里配置的权限类,最后用默认的权限类