Django-restframework 基于token认证 + 权限管理

【models】

from django.db import models

# Create your models here.

############  用户登陆与认证  #########################################################
class UserInfo(models.Model):
    user_type_choices=(
        (1,'普通用户'),
        (2,'VIP'),
        (3,'SVIP'),
    )
    usertype=models.IntegerField(choices=user_type_choices)
    username=models.CharField(max_length=20)
    password=models.CharField(max_length=32)

    class Meta:
        managed=True


class UserToken(models.Model):
    token = models.CharField(max_length=300)
    user = models.OneToOneField(to='UserInfo', on_delete=models.CASCADE)

    class Meta:
        managed=True


【view层】

class Dog2(APIView):
    authentication_classes = [MyAuthentication2, ]
    permission_classes = [MyPermission,]
    def get(self, request, *args, **kwargs):
        res = {
            'code': 1000,
            'msg': {'msg': 'Dog'}
        }

        print('获取Dog')
        return HttpResponse(json.dumps(res))

    def post(self, requst, *args, **kwargs):
        return HttpResponse('提交Dog')

    def delete(self, request, *args, **kwargs):
        print('删除Dog')
        return HttpResponse('删除Dog')

    def put(self, request, *args, **kwargs):
        print('更新Dog')
        return HttpResponse('更新Dog')

【utils目录,存放认证、权限管理代码】

from rest_framework.authentication import BaseAuthentication
# 认证类
class MyAuthentication2(BaseAuthentication):
    def authenticate(self, request):
        token = request._request.GET.get('token')
        token_obj = UserToken.objects.filter(token=token).first()

        if not token_obj:
            raise exceptions.AuthenticationFailed('用户认证失败')
        return (token_obj.user, token_obj)
    # def authenticate_header(self, xxx):
    #     pass


# 权限管理
class MyPermission(object):
    message = '必须VIP才能访问'
    def has_permission(self, request, view):
        print('request.user ============> ')
        print(request.user)
        if request.user.usertype != 3:
            # 返回False表示认证失败
            return False
        # 返回False表示认证成功
        return True

【全局配置】

REST_FRAMEWORK = {
    # 全局使用的认证类
    # "DEFAULT_AUTHENTIVATION_CLASSES":['这里填写文件路径.类名'],
    # 全局使用的权限类
    "DEFAULT_PERMISSON_CLASSES":['orders.utils.permissions.MyPermission']
}

你可能感兴趣的:(django,Django,RestFramework,Python)