permissions.py 2.7 KB
Newer Older
1 2 3
from django.conf import settings
from rest_framework import permissions
from rest_framework.exceptions import PermissionDenied
4
from django.http import Http404
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23


class ApiKeyHeaderPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        """
        Check for permissions by matching the configured API key and header

        If settings.DEBUG is True and settings.EDX_API_KEY is not set or None,
        then allow the request. Otherwise, allow the request if and only if
        settings.EDX_API_KEY is set and the X-Edx-Api-Key HTTP header is
        present in the request and matches the setting.
        """
        api_key = getattr(settings, "EDX_API_KEY", None)
        return (
            (settings.DEBUG and api_key is None) or
            (api_key is not None and request.META.get("HTTP_X_EDX_API_KEY") == api_key)
        )


24 25 26 27 28 29 30 31 32 33 34 35 36
class ApiKeyHeaderPermissionIsAuthenticated(ApiKeyHeaderPermission, permissions.IsAuthenticated):
    """
    Allow someone to access the view if they have the API key OR they are authenticated.

    See ApiKeyHeaderPermission for more information how the API key portion is implemented.
    """
    def has_permission(self, request, view):
        #TODO We can optimize this later on when we know which of these methods is used more often.
        api_permissions = ApiKeyHeaderPermission.has_permission(self, request, view)
        is_authenticated_permissions = permissions.IsAuthenticated.has_permission(self, request, view)
        return api_permissions or is_authenticated_permissions


37 38 39 40 41 42 43 44 45 46 47
class IsAuthenticatedOrDebug(permissions.BasePermission):
    """
    Allows access only to authenticated users, or anyone if debug mode is enabled.
    """

    def has_permission(self, request, view):
        if settings.DEBUG:
            return True

        user = getattr(request, 'user', None)
        return user and user.is_authenticated()
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70


class IsUserInUrl(permissions.BasePermission):
    """
    Permission that checks to see if the request user matches the user in the URL.
    """
    def has_permission(self, request, view):
        # Return a 404 instead of a 403 (Unauthorized). If one user is looking up
        # other users, do not let them deduce the existence of an account.
        if request.user.username != request.parser_context.get('kwargs', {}).get('username', None):
            raise Http404()
        return True


class IsUserInUrlOrStaff(IsUserInUrl):
    """
    Permission that checks to see if the request user matches the user in the URL or has is_staff access.
    """
    def has_permission(self, request, view):
        if request.user.is_staff:
            return True

        return super(IsUserInUrlOrStaff, self).has_permission(request, view)