1、增加表字段:
from django.db import models
class UserInfo(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
email = models.CharField(max_length=64)
user_type_choices = ((0,'普通用户'),(1,'管理员'))
user_type = models.IntegerField(choices=user_type_choices,default=0)
class Token(models.Model):
value = models.CharField(max_length=64) # session_key
user = models.OneToOneField(UserInfo) # 只能登陆一次,再次登陆则会重新生成token值
2、权限源码流程:
# step 1
def dispatch(self, request, *args, **kwargs):
try:
self.initial(request, *args, **kwargs)
# step 2
def initial(self, request, *args, **kwargs):
self.perform_authentication(request) # 先进行用户认证
self.check_permissions(request) # 随后获取权限
# step 3
def check_permissions(self, request):
for permission in self.get_permissions():
# 若 has_permission 返回 True 则有权限,反之,无权限
if not permission.has_permission(request, self):
self.permission_denied(
request, message=getattr(permission, 'message', None)
)
# step 4
def get_permissions(self):
return [permission() for permission in self.permission_classes]
# 默认的AllowAny类允许所有用户登录
class AllowAny(BasePermission):
def has_permission(self, request, view):
return True
3、获取默认的权限类:
class UserView(APIView):
def get(self,request,*args,**kwargs):
print(self.permission_classes) # [<class 'rest_framework.permissions.AllowAny'>]
from rest_framework.permissions import AllowAny,BasePermission
class AllowAny(BasePermission):
def has_permission(self, request, view):
return True
4、自定义权限类:
from rest_framework.permissions import BasePermission
class MyPermission(BasePermission):
message = '无权限访问' # 定制错误信息
def has_permission(self, request, view):
# 已经过认证
user = request._request.user
if user:
if user.user_type == 1:
return True
return False
class Permission(object):
# 利用继承指定权限类
permission_classes = [MyPermission,]
5、使用示例:
# 路由
from django.conf.urls import url
from app01.views import UserView,GroupView
urlpatterns = [
url(r'^users/', UserView.as_view()),
url(r'^user_groups/', GroupView.as_view()),
]
# 视图
class UserView(Auth,APIView):
"""指定了认证类,只有认证通过才能访问"""
def get(self,request,*args,**kwargs):
return HttpResponse('<h1>用户界面</h1>')
class GroupView(Auth,Permission,APIView):
"""指定了认证和权限类,先要通过认证且只有管理者才能访问"""
def get(self,request,*args,**kwargs):
return HttpResponse('<h1>用户组界面</h1>')
6、测试:
# alex 为普通用户,对应的token值为 9c4cb1631b3a5ead33fb09f6349c4bc7
# kate 为管理者,对应的token值为 3cfc1dfab9d2b130e44cbf86b1099206
http://127.0.0.1:8000/users/?tk=9c4cb1631b3a5ead33fb09f6349c4bc7
http://127.0.0.1:8000/users/?tk=3cfc1dfab9d2b130e44cbf86b1099206
# 都能正常登陆
http://127.0.0.1:8000/user_groups/?tk=9c4cb1631b3a5ead33fb09f6349c4bc7
'''
HTTP 403 Forbidden
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"detail": "无权限访问"
}
'''
http://127.0.0.1:8000/user_groups/?tk=3cfc1dfab9d2b130e44cbf86b1099206
# 由于是管理用户可以正常访问
原文地址:https://www.cnblogs.com/fqh202/p/9397717.html
时间: 2024-11-12 09:38:30