"""This module contains the permission classes for the ``api`` app"""

from oauth2_provider.ext.rest_framework.permissions import TokenHasReadWriteScope
from rest_framework.permissions import BasePermission, IsAuthenticated


class IsAuthenticatedOrValidOAuthToken(BasePermission):
    """Permission class to check both oauth "client_credentials" and "classic" auth

    We must use this as the ``IsAuthenticated`` permission checks that a user is actually logged.
    In the case of the "client_credentials" authentication flow, we don't have a user, only an
    "application" (https://tools.ietf.org/html/rfc6749#section-1.3.4).
    In this case, we only test that a valid oauth token is provided.

    """

    def has_permission(self, request, view):
        """Check the permission to access the view given the current request"""

        return (
            IsAuthenticated().has_permission(request, view) or
            TokenHasReadWriteScope().has_permission(request, view)
        )
