认证,权限

model表:
from django.db import models
# Create your models here.
class UserInfo(models.Model):
useranme=models.CharField(max_length=32)
password=models.CharField(max_length=32)
user_role_type_choice=((1,'普通用户'),(2,'vip用户'),(3,'svip用户'))
user_role=models.IntegerField(choices=user_role_type_choice,verbose_name='用户角色')


url路由映射:
url(r'^PermissionView/$', views.PermissionView.as_view())



views部分:
from rest_framework.authentication import BaseAuthentication
class Authentition_Control(BaseAuthentication):
def authenticate(self, request):
print(request.GET)
username=request.GET.get('username')
password=request.GET.get('password')
print('username',username)
print('password',password)
exist=UserInfo.objects.filter(useranme=username,password=password).first()##后面如果不加first的话,默认是.all(),集合的形式
if exist:
print('验证通过')
return username,password
else:
return False,False
class Permission_control():
message='只有vip和svip才可以访问'
def has_permission(self,request,view):
# recv_username=request.user##注明一下,这个是已经在进行校验登录之后才有的权限
password=request.auth##这个是用户密码,可以是加密的用户密码
user=request.user
print('进行权限认证的用户是',user)
username_role=UserInfo.objects.get(useranme=user).get_user_role_display()
print(username_role)
if username_role=='svip用户':
print('成功')
return True
else:
return False
class PermissionView(APIView):
authentication_classes = [Authentition_Control]
permission_classes = [Permission_control]
def get(self,request):
print('访问成功')
return Response('ok')
posted @ 2018-11-15 23:26  风不再来  阅读(236)  评论(0编辑  收藏  举报