提示
下面文章代码可能需要使用到的一些import 1
2
3
4
5
6
7
8
9
10import uuid
import datetime
import pandas as pd
from random import Random
from django.core.mail import EmailMessage
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated, IsAdminUser
我的目的
1.前后端分离
2.API接口的用户认证管理、权限管理、频率控制、角色控制即:
2.1. 判断是游客还是网站用户,若是用户则需要Token验证
2.2. 权限管理即游客只有读权限,而网站用户有读写权限
2.3. 频率控制 我这里不做展开
以上三个即为Django REST framework三大认证组件
2.4. 网站用户的角色控制(利用RBAC实现)自扩展
主要是下面二个组件和角色控制:
认证组件 rest_framework.authentication
TokenAuthentication 基于Token认证
BasicAuthentication 基于密码认证
SessionAuthentication 基于Session认证
BaseAuthentication 自定义认证
我这里主要是使用BaseAuthentication
权限组件 rest_framework.permissions
IsAdminUser 管理员权限
AllowAny 无需认证(默认)
......
BasePermission 自定义权限
我这里主要是使用BasePermission
角色组件 RBAC 暂未更新
认证与权限的使用
在视图类中添加: 1
2authentication_classes = [TokenAuth]
permission_classes = [IsAdminUser]
认证组件
继承BaseAuthentication基础认证类,例如我使用TokenAuth代码如下:
1
2
3
4
5
6
7
8
9
10
11from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
class TokenAuth(BaseAuthentication):
def authenticate(self,request):
token = request.META.get('HTTP_TOKEN')
user_token = UserToken.objects.all().filter(token=token).first()
if user_token:
return user_token.user, token
else:
raise AuthenticationFailed("认证失败")
同时我还使用了一个时间认证此处存疑!
1
2
3
4
5
6
7
8
9
10
11
12
13
14class DateAuth():
def authenticate_header(self, request):
pass
def authenticate(self, request):
if request.method == 'GET':
start_date = request.GET.get('start_date')
end_date = request.GET.get('end_date')
try:
start_date = datetime.datetime.strptime(start_date, r"%Y-%m-%d")
end_date = datetime.datetime.strptime(end_date, r"%Y-%m-%d")
request.start_date = start_date
request.end_date = end_date
except Exception as e:
raise AuthenticationFailed("时间有误")
再次提示,此处存疑!
这样我的视图层就可以这样写: views.py 1
2
3
4
5
6
7
8
9class LeaveView(APIView):
authentication_classes = [DateTimeAuth, TokenAuth]
# permission_classes = [IsAdminUser]
def get(self, request, *args, **kwargs):
start_date = request.start_date
end_date = request.end_date
return Response(statistic_leave(start_date, end_date))
权限
pass