framework —— permission(权限)

framework —— permission(权限)

1.目录结构

  

2.urls.py:

from django.conf.urls import url
from django.contrib import admin
from app02 import views as app02_view


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hosts/',app02_view.HostView.as_view()),
    url(r'^auth/$',app02_view.AuthView.as_view()),
    url(r'^salary/',app02_view.SalaryView.as_view()),
    url(r'user/',app02_view.UserView.as_view())
]

3.utils.py:

from django.shortcuts import render,HttpResponse
from rest_framework.request import Request
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
from app02 import models




class MyAuthentication(BaseAuthentication):
    def authenticate(self,request):
        token = request.query_params.get('token')
        obj = models.Userinfo.objects.filter(token=token).first()
        if obj:
            return obj(obj.username,obj)
        raise  APIException('用户认证失败')

4.view.py:

from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.authentication import BaseAuthentication
import time
import hashlib
# Create your views here.

from app02 import models


#认证的时候用到,生成token, 权限这快可以不需要。
class MyAuthentication(BaseAuthentication):
    """
    All authentication classes should extend BaseAuthentication.
    """

    def authenticate(self, request):
        """
        Authenticate the request and return a two-tuple of (user, token).
        """
        token = request.query_params.get('token')
        obj = models.Userinfo.objects.filter(token=token).first()
        if obj:
            return (obj.username,obj)
        return None

    def authenticate_header(self, request):
        """
        Return a string to be used as the value of the `WWW-Authenticate`
        header in a `401 Unauthenticated` response, or `None` if the
        authentication scheme should return `403 Permission Denied` responses.
        """
        pass

class MyPermission(object):
    message = "无权访问"
    def has_permission(self,request,view):
        if request.user:
            # print(request.user)
            return True
        return False

class AdminPermission(object):
    message = "无权访问"
    def has_permission(self,request,view):
        if request.user == 'zxc':
            return True
        return False

class AuthView(APIView):
    authentication_classes = []
    def get(self,request):
        '''
        接收用户名和密码
        :param request:
        :return:
        '''
        ret ={"code":1000,"msg":None}
        user = request.query_params.get('user')
        pwd = request.query_params.get('pwd')
        user_obj = models.Userinfo.objects.filter(username=user,password=pwd).first()
        if not user_obj:
            ret['code'] = 1001
            ret['msg'] = "用户名或密码错误"
            return  Response(ret)

        #创建随机字符串
        ctime = time.time()
        key = "%s|%s"%(user,pwd)
        m = hashlib.md5()
        m.update(key.encode('utf-8'))
        token = m.hexdigest()
        #保存到数据
        user_obj.token = token
        user_obj.save()

        ret['token'] = token
        # return Response(ret)


class HostView(APIView):
    '''
    匿名用户和管理用户都能访问
    '''
    authentication_classes = [MyAuthentication,]
    permission_classes = []

    def get(self,request,*args,**kwargs):

        self.dispatch
        # print(request.user)
        # print(request.auth)
        return Response('主机列表')

class UserView(APIView):
    '''
    用户能访问
    '''
    authentication_classes = [MyAuthentication,]
    permission_classes = [MyPermission]

    def get(self,request,*args,**kwargs):
        print('========',request.user)
        return Response('用户列表')

class SalaryView(APIView):
    '''
    管理员能访问
    '''
    authentication_classes = [MyAuthentication,]
    permission_classes = [MyPermission,AdminPermission]

    def get(self,request,*args,**kwargs):
        return Response('薪资列表')
原文地址:https://www.cnblogs.com/zhongbokun/p/8423408.html