快速使用

认证,根据用户携带的 token/其他 获取当前用户信息。

权限,读取认证中获取的用户信息,判断当前用户是否有权限访问,例如:普通用户、管理员、超级用户,不同用户具有不同的权限。

  1. class UserInfo(models.Model):
  2. role_choices = ((1, "普通用户"), (2, "管理员"), (3, "超级管理员"),)
  3. role = models.IntegerField(verbose_name="角色", choices=role_choices, default=1)
  4. username = models.CharField(verbose_name="用户名", max_length=32)
  5. password = models.CharField(verbose_name="密码", max_length=64)
  6. token = models.CharField(verbose_name="TOKEN", max_length=64, null=True, blank=True)

image.png
image.png

image.png
image.png

  1. import uuid
  2. from rest_framework.views import APIView
  3. from rest_framework.request import Request
  4. from rest_framework.response import Response
  5. from rest_framework.authentication import BaseAuthentication
  6. from rest_framework.permissions import BasePermission
  7. from rest_framework.exceptions import AuthenticationFailed
  8. # Create your views here.
  9. from app01 import models
  10. class AuthView(APIView):
  11. '''提交的数据 {"username": "mufeng", "password": "123456"}
  12. '''
  13. def post(self, request, *args, **kwargs):
  14. print(request.data)
  15. username = request.data.get('username')
  16. password = request.data.get('password')
  17. user_object = models.UserInfo.objects.filter(username=username, password=password).first()
  18. if not user_object:
  19. return Response({'code': 1000, 'data': '用户名或密码错误'})
  20. token = str(uuid.uuid4())
  21. user_object.token = token
  22. user_object.save()
  23. res = {'code': 0, 'data': {'token': token, 'name': username}}
  24. return Response(res)
  25. class TokenAuthentication(BaseAuthentication):
  26. def authenticate(self, request):
  27. msg = {'code': 1002, 'data': '认证失败'}
  28. token = request.query_params.get('token')
  29. if not token:
  30. raise AuthenticationFailed(msg)
  31. user_object = models.UserInfo.objects.filter(token=token).first()
  32. if not user_object:
  33. raise AuthenticationFailed(msg)
  34. return user_object, token
  35. class PermissionA(BasePermission):
  36. message = {"code": 1003, 'data': "无权访问"}
  37. def has_permission(self, request, view):
  38. if request.user.role == 2:
  39. return True
  40. return False
  41. # 暂时先这么写
  42. def has_object_permission(self, request, view, obj):
  43. return True
  44. class OrderView(APIView):
  45. authentication_classes = [TokenAuthentication]
  46. permission_classes = [PermissionA, ]
  47. def get(self, request, *args, **kwargs):
  48. return Response({'code': 1000, 'data': '认证成功'})

多个权限类

当开发过程中需要用户同时具备多个权限(缺一不可)时,可以用多个权限类来实现。

权限组件内部处理机制:按照列表的顺序逐一执行 has_permission 方法,如果返回True,则继续执行后续的权限类;如果返回None或False,则抛出权限异常并停止后续权限类的执行。

  1. from django.db import models
  2. # Create your models here.
  3. # models.py
  4. class Role(models.Model):
  5. """ 角色表 """
  6. title = models.CharField(verbose_name="名称", max_length=32)
  7. class UserInfo(models.Model):
  8. username = models.CharField(verbose_name="用户名", max_length=32)
  9. password = models.CharField(verbose_name="密码", max_length=64)
  10. token = models.CharField(verbose_name="TOKEN", max_length=64, null=True, blank=True)
  11. roles = models.ManyToManyField(verbose_name="角色", to="Role")
  1. import uuid
  2. from rest_framework.views import APIView
  3. from rest_framework.request import Request
  4. from rest_framework.response import Response
  5. from rest_framework.authentication import BaseAuthentication
  6. from rest_framework.permissions import BasePermission
  7. from rest_framework.exceptions import AuthenticationFailed
  8. # Create your views here.
  9. from app01 import models
  10. class AuthView(APIView):
  11. '''提交的数据 {"username": "mufeng", "password": "123456"}
  12. '''
  13. def post(self, request, *args, **kwargs):
  14. print(request.data)
  15. username = request.data.get('username')
  16. password = request.data.get('password')
  17. user_object = models.UserInfo.objects.filter(username=username, password=password).first()
  18. if not user_object:
  19. return Response({'code': 1000, 'data': '用户名或密码错误'})
  20. token = str(uuid.uuid4())
  21. user_object.token = token
  22. user_object.save()
  23. res = {'code': 0, 'data': {'token': token, 'name': username}}
  24. return Response(res)
  25. class TokenAuthentication(BaseAuthentication):
  26. def authenticate(self, request):
  27. msg = {'code': 1002, 'data': '认证失败'}
  28. token = request.query_params.get('token')
  29. if not token:
  30. raise AuthenticationFailed(msg)
  31. user_object = models.UserInfo.objects.filter(token=token).first()
  32. if not user_object:
  33. raise AuthenticationFailed(msg)
  34. return user_object, token
  35. class PermissionA(BasePermission):
  36. message = {"code": 1003, 'data': "无权访问"}
  37. def has_permission(self, request, view):
  38. exists = request.user.roles.filter(title="员工").exists()
  39. if exists:
  40. return True
  41. return False
  42. def has_object_permission(self, request, view, obj):
  43. return True
  44. class PermissionB(BasePermission):
  45. message = {"code": 1003, 'data': "无权访问"}
  46. def has_permission(self, request, view):
  47. exists = request.user.roles.filter(title="主管").exists()
  48. if exists:
  49. return True
  50. return False
  51. def has_object_permission(self, request, view, obj):
  52. return True
  53. class OrderView(APIView):
  54. authentication_classes = [TokenAuthentication, ]
  55. permission_classes = [PermissionA, PermissionB] # 既是员工,又是主管
  56. def get(self, request, *args, **kwargs):
  57. return Response({"code": 0, "data": {"user": None, 'list': [1, 2, 3]}})

image.png
image.png
image.png

image.png

全局配置

  1. REST_FRAMEWORK = {
  2. "DEFAULT_PERMISSION_CLASSES":["xxxx.xxxx.xx.类名","xxxx.xxxx.xx.类名",]
  3. }