?rest_framework/request.py中部分認證和權限代碼
def _authenticate(self):"""Attempt to authenticate the request using each authentication instancein turn."""for authenticator in self.authenticators:try:user_auth_tuple = authenticator.authenticate(self)except exceptions.APIException:self._not_authenticated()raiseif user_auth_tuple is not None:self._authenticator = authenticatorself.user, self.auth = user_auth_tuplereturnself._not_authenticated()def _not_authenticated(self):"""Set authenticator, user & authtoken representing an unauthenticated request.Defaults are None, AnonymousUser & None."""self._authenticator = Noneif api_settings.UNAUTHENTICATED_USER:self.user = api_settings.UNAUTHENTICATED_USER()else:self.user = None
認證后將user存儲到了request中,為了權限使用時候可以進行判斷(紅色)
class UserLoginPermission(BasePermission):
? ? def has_permission(self, request, view):
? ? ? ? return isinstance(request.user,User)
?
?
?
實例:
authentication.py
from django.core.cache import cache
from rest_framework.authentication import BaseAuthenticationclass TokenAuthentication(BaseAuthentication):def authenticate(self, request):token = request.query_params.get("token")user = cache.get(token)if user:return user ,token
permissions.py
from rest_framework.permissions import BasePermissionfrom App.models import Userclass UserLoginPermission(BasePermission):def has_permission(self, request, view):return isinstance(request.user,User)def has_object_permission(self, request, view, obj):if obj.b_author.id == request.user.id:return True
?
?
?