Python rest_framework.permissions.AllowAny() Examples

The following are 22 code examples of rest_framework.permissions.AllowAny(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.permissions , or try the search function .
Example #1
Source File: yasg.py    From django-bananas with MIT License 6 votes vote down vote up
def get_schema_view(self):
        view = get_schema_view(
            openapi.Info(
                title="Django Bananas Admin API Schema",
                default_version=BananasVersioning.default_version,
                description="API for django-bananas.js",
                # terms_of_service="https://www.google.com/policies/terms/",
                # license=openapi.License(name="BSD License"),
            ),
            # validators=["flex", "ssv"],
            public=False,
            generator_class=BananasOpenAPISchemaGenerator,
            authentication_classes=(SessionAuthentication,),
            permission_classes=(permissions.AllowAny,),
            patterns=self.urls,
        )
        view.versioning_class = BananasVersioning

        return view 
Example #2
Source File: views.py    From django-rest-authemail with GNU General Public License v3.0 6 votes vote down vote up
def post(self, request, format=None):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            email = serializer.data['email']

            try:
                user = get_user_model().objects.get(email=email)
                if user.is_verified and user.is_active:
                    password_reset_code = \
                        PasswordResetCode.objects.create_reset_code(user)
                    password_reset_code.send_password_reset_email()
                    content = {'email': email}
                    return Response(content, status=status.HTTP_201_CREATED)

            except get_user_model().DoesNotExist:
                pass

            # Since this is AllowAny, don't give away error.
            content = {'detail': _('Password reset not allowed.')}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response(serializer.errors,
                status=status.HTTP_400_BAD_REQUEST) 
Example #3
Source File: test_cache.py    From course-discovery with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_should_not_cache_if_waffled(self, waffle_active):
        """ Verify that the decorator does not cache the waffle flag is turned off """
        def key_func(**kwargs):  # pylint: disable=unused-argument
            return self.cache_response_key

        class TestView(views.APIView):
            permission_classes = [permissions.AllowAny]
            renderer_classes = [JSONRenderer]

            @compressed_cache_response(key_func=key_func)
            def get(self, request, *args, **kwargs):
                return Response('test response')

        with override_flag('compressed_cache.TestView.get', active=waffle_active):

            view_instance = TestView()
            view_instance.headers = {}  # pylint: disable=attribute-defined-outside-init
            view_instance.dispatch(request=self.request)

        # Verify nothing was cached
        if waffle_active:
            self.assertIsNot(cache.get(self.cache_response_key), None)
        else:
            self.assertIs(cache.get(self.cache_response_key), None) 
Example #4
Source File: test_cache.py    From course-discovery with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_should_not_cache_for_non_json_responses(self):
        """ Verify that the decorator does not cache if the response is not json """
        def key_func(**kwargs):  # pylint: disable=unused-argument
            return 'non_json_cache_key'

        class TestView(views.APIView):
            permission_classes = [permissions.AllowAny]
            renderer_classes = [BrowsableAPIRenderer]  # Non-json responses

            @compressed_cache_response(key_func=key_func)
            def get(self, request, *args, **kwargs):
                return Response('test response')

        view_instance = TestView()
        view_instance.headers = {}  # pylint: disable=attribute-defined-outside-init
        view_instance.dispatch(request=self.request)

        # Verify nothing was cached
        self.assertEqual(cache.get('non_json_cache_key'), None) 
Example #5
Source File: test_cache.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_should_handle_getting_compressed_response_from_cache(self):
        """ Verify that the decorator correctly returns compressed responses """
        def key_func(**kwargs):  # pylint: disable=unused-argument
            return self.cache_response_key

        class TestView(views.APIView):
            permission_classes = [permissions.AllowAny]
            renderer_classes = [JSONRenderer]

            @compressed_cache_response(key_func=key_func)
            def get(self, request, *args, **kwargs):
                return Response('test response')

        view_instance = TestView()
        view_instance.headers = {}  # pylint: disable=attribute-defined-outside-init
        compressed_cached_response = Response('compressed cached test response')
        view_instance.finalize_response(request=self.request, response=compressed_cached_response)
        compressed_cached_response.render()

        # Rendered content is compressed before response goes into the cache
        response_triple = (
            zlib.compress(compressed_cached_response.rendered_content),
            compressed_cached_response.status_code,
            compressed_cached_response._headers.copy(),  # pylint: disable=protected-access
        )
        cache.set(self.cache_response_key, response_triple)

        response = view_instance.dispatch(request=self.request)
        self.assertEqual(response.content.decode('utf-8'), '"compressed cached test response"') 
Example #6
Source File: views.py    From Django-Angular-Ionic with MIT License 5 votes vote down vote up
def get_serializer_context(self, *args, **kwargs):
        return {"request": self.request}




# class RegisterAPIView(APIView):
#     permission_classes      = [permissions.AllowAny]
#     def post(self, request, *args, **kwargs):
#         if request.user.is_authenticated():
#             return Response({'detail': 'You are already registered and are authenticated.'}, status=400)
#         data = request.data
#         username        = data.get('username') # username or email address
#         email           = data.get('username')
#         password        = data.get('password')
#         password2       = data.get('password2')
#         qs = User.objects.filter(
#                 Q(username__iexact=username)|
#                 Q(email__iexact=username)
#             )
#         if password != password2:
#             return Response({"password": "Password must match."}, status=401)
#         if qs.exists():
#             return Response({"detail": "This user already exists"}, status=401)
#         else:
#             user = User.objects.create(username=username, email=email)
#             user.set_password(password)
#             user.save()
#             # payload = jwt_payload_handler(user)
#             # token = jwt_encode_handler(payload)
#             # response = jwt_response_payload_handler(token, user, request=request)
#             # return Response(response, status=201)
#             return Response({'detail': "Thank you for registering. Please verify your email."}, status=201)
#         return Response({"detail": "Invalid Request"}, status=400) 
Example #7
Source File: test_viewsets.py    From drf-haystack with MIT License 5 votes vote down vote up
def test_viewset_get_queryset_with_AllowAny_permission(self):
        from rest_framework.permissions import AllowAny
        setattr(self.view, "permission_classes", (AllowAny, ))

        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK) 
Example #8
Source File: user.py    From train-ai-with-django-swagger-jwt with Apache License 2.0 5 votes vote down vote up
def get_permissions(self):
        if self.request.method == 'POST':
            return (permissions.AllowAny(),)
        elif self.request.method == 'GET':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'PUT':
            return (permissions.IsAuthenticated(),)
        elif self.request.method == 'DELETE':
            return (permissions.IsAuthenticated(),)

        return (permissions.IsAuthenticated(),)
    # end of get_permissions 
Example #9
Source File: test_unit.py    From drf-schema-adapter with MIT License 5 votes vote down vote up
def setUp(self):
        self.endpoint = Endpoint(model=Product)
        self.fields = tuple([field.name for field in Product._meta.get_fields()])

        self.permission_classes = (AllowAny, )
        self.filter_fields = ('name', 'category_id')
        self.search_fields = ('id', 'name')
        self.ordering_fields = ('name', )
        self.page_size = 2

        self.alternate_endpoint = Endpoint(model=Product, permission_classes=self.permission_classes,
                                           filter_fields=self.filter_fields,
                                           search_fields=self.search_fields,
                                           ordering_fields=self.ordering_fields,
                                           page_size=self.page_size) 
Example #10
Source File: api.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def get_permissions(self):
        if self.request.query_params.get('user-only', None):
            self.permission_classes = (AllowAny,)
        return super().get_permissions() 
Example #11
Source File: app_settings.py    From django-rest-auth with MIT License 5 votes vote down vote up
def register_permission_classes():
    permission_classes = [AllowAny, ]
    for klass in getattr(settings, 'REST_AUTH_REGISTER_PERMISSION_CLASSES', tuple()):
        permission_classes.append(import_callable(klass))
    return tuple(permission_classes) 
Example #12
Source File: views.py    From REST-API with MIT License 5 votes vote down vote up
def get_serializer_context(self, *args, **kwargs):
        return {"request": self.request}




# class RegisterAPIView(APIView):
#     permission_classes      = [permissions.AllowAny]
#     def post(self, request, *args, **kwargs):
#         if request.user.is_authenticated():
#             return Response({'detail': 'You are already registered and are authenticated.'}, status=400)
#         data = request.data
#         username        = data.get('username') # username or email address
#         email           = data.get('username')
#         password        = data.get('password')
#         password2       = data.get('password2')
#         qs = User.objects.filter(
#                 Q(username__iexact=username)|
#                 Q(email__iexact=username)
#             )
#         if password != password2:
#             return Response({"password": "Password must match."}, status=401)
#         if qs.exists():
#             return Response({"detail": "This user already exists"}, status=401)
#         else:
#             user = User.objects.create(username=username, email=email)
#             user.set_password(password)
#             user.save()
#             # payload = jwt_payload_handler(user)
#             # token = jwt_encode_handler(payload)
#             # response = jwt_response_payload_handler(token, user, request=request)
#             # return Response(response, status=201)
#             return Response({'detail': "Thank you for registering. Please verify your email."}, status=201)
#         return Response({"detail": "Invalid Request"}, status=400) 
Example #13
Source File: test_cache.py    From course-discovery with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_should_handle_getting_uncompressed_response_from_cache(self):
        """ Verify that the decorator correctly returns uncompressed responses """
        def key_func(**kwargs):  # pylint: disable=unused-argument
            return self.cache_response_key

        class TestView(views.APIView):
            permission_classes = [permissions.AllowAny]
            renderer_classes = [JSONRenderer]

            @compressed_cache_response(key_func=key_func)
            def get(self, request, *args, **kwargs):
                return Response('test response')

        view_instance = TestView()
        view_instance.headers = {}  # pylint: disable=attribute-defined-outside-init
        uncompressed_cached_response = Response('cached test response')
        view_instance.finalize_response(request=self.request, response=uncompressed_cached_response)
        uncompressed_cached_response.render()

        response_triple = (
            uncompressed_cached_response.rendered_content,
            uncompressed_cached_response.status_code,
            uncompressed_cached_response._headers.copy(),  # pylint: disable=protected-access
        )
        cache.set(self.cache_response_key, response_triple)

        response = view_instance.dispatch(request=self.request)
        self.assertEqual(response.content.decode('utf-8'), '"cached test response"') 
Example #14
Source File: middleware.py    From gro-api with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        if system_layout.current_value is not None:
            raise MiddlewareNotUsed()
        class FarmNotConfiguredView(APIView):
            permission_classes = (AllowAny, )
            def get(self, request):
                raise FarmNotConfiguredError()
            post = get
            put = get
            patch = get
            delete = get
        self.view = FarmNotConfiguredView.as_view() 
Example #15
Source File: users.py    From lego with MIT License 5 votes vote down vote up
def get_permissions(self):
        """
        The create action are used to register user, we do not require authentication on that
        endpoint.
        """
        if self.action == "create":
            return [AllowAny()]

        return super().get_permissions() 
Example #16
Source File: views.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == "validate":
            # Allow validating instance configuration without an account
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes] 
Example #17
Source File: views.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        if self.action == "create":
            # Allow any user to create an account, but limit other actions to logged-in users.
            permission_classes = [AllowAny]
        else:
            permission_classes = [IsAuthenticated]
        return [permission() for permission in permission_classes] 
Example #18
Source File: api_views.py    From django-aws-template with MIT License 5 votes vote down vote up
def get_permissions(self):

        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.IsAuthenticated(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),) 
Example #19
Source File: test_autofilter.py    From drf_tweaks with MIT License 5 votes vote down vote up
def test_excluding_fields(self):
        @autofilter(exclude_fields=("indexed_int", "indexed_char", ))
        class SampleApiV7(ListAPIView):
            permission_classes = (AllowAny,)
            serializer_class = SampleModelForAutofilterSerializerVer1
            queryset = SampleModelForAutofilter.objects.all()

        self.assertEqual(set(SampleApiV7.filter_fields.keys()), {"id", "fk", "indexed_text", "indexed_url",
                                                                 "indexed_email", "nullable_field", "unique_text"}) 
Example #20
Source File: build.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list' or self.action == 'retrieve':
            permission_classes = [permissions.AllowAny]
        else:
            permission_classes = [DenyAny]
        return [permission() for permission in permission_classes] 
Example #21
Source File: version.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list' or self.action == 'retrieve':
            permission_classes = [permissions.AllowAny]
        else:
            permission_classes = [DenyAny]
        return [permission() for permission in permission_classes] 
Example #22
Source File: package.py    From DCRM with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_permissions(self):
        if self.action == 'list' or self.action == 'retrieve':
            permission_classes = [permissions.AllowAny]
        else:
            permission_classes = [DenyAny]
        return [permission() for permission in permission_classes]