10/23/2015 - 2:02 PM


from rest_framework.authentication import BaseAuthentication
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import BasePermission
from rest_framework.response import Response

class SessionAuthenticationWithoutCSRF(BaseAuthentication):
    def authenticate(self, request):
        request = request._request
        user = getattr(request, 'user', None)

        if not user or not user.is_active:
            return None

        return (user, None)

class IsTeamMember(BasePermission):
    message = 'You are not member of team.'

    def has_permission(self, request, view):
        if request.user.is_authenticated():
            return request.team in request.user.team_set.all()
        return False

class LinkHeaderPagination(LimitOffsetPagination):
    def get_paginated_response(self, data):
        next_url = self.get_next_link()
        previous_url = self.get_previous_link()

        if next_url is not None and previous_url is not None:
            link = '<{next_url}>; rel="next", <{previous_url}>; rel="prev"'
        elif next_url is not None:
            link = '<{next_url}>; rel="next"'
        elif previous_url is not None:
            link = '<{previous_url}>; rel="prev"'
            link = ''

        link = link.format(next_url=next_url, previous_url=previous_url)
        headers = {'Link': link} if link else {}

        return Response(data, headers=headers)

class SetterMixin:
    def create(self, validated_data):
        instance = super().create(validated_data)
        return self.run_setter(instance, validated_data)

    def update(self, instance, validated_data):
        updated_instance = super().update(instance, validated_data)
        self.run_setter(updated_instance, validated_data)

    def run_setter(self, instance, validated_data):
        for key, value in validated_data.items():
            setter_name = 'set_' + key

            setter = getattr(self, setter_name, None)
            if setter:
                setter(instance, value)

            setter = getattr(instance, setter_name, None)
            if setter:

        return instance