Python rest_framework.exceptions.NotAuthenticated() Examples

The following are 10 code examples of rest_framework.exceptions.NotAuthenticated(). 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.exceptions , or try the search function .
Example #1
Source File: token.py    From kpi with GNU Affero General Public License v3.0 6 votes vote down vote up
def _which_user(self, request):
        """
        Determine the user from `request`, allowing superusers to specify
        another user by passing the `username` query parameter
        """
        if request.user.is_anonymous:
            raise exceptions.NotAuthenticated()

        if 'username' in request.query_params:
            # Allow superusers to get others' tokens
            if request.user.is_superuser:
                user = get_object_or_404(
                    User,
                    username=request.query_params['username']
                )
            else:
                raise exceptions.PermissionDenied()
        else:
            user = request.user
        return user 
Example #2
Source File: views.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def handle_exception(self, exc):
        """
        Handle any exception that occurs, by returning an appropriate response,
        or re-raising the error.
        """
        if isinstance(exc, (exceptions.NotAuthenticated,
                            exceptions.AuthenticationFailed)):
            # WWW-Authenticate header for 401 responses, else coerce to 403
            auth_header = self.get_authenticate_header(self.request)

            if auth_header:
                exc.auth_header = auth_header
            else:
                exc.status_code = status.HTTP_403_FORBIDDEN

        exception_handler = self.get_exception_handler()

        context = self.get_exception_handler_context()
        response = exception_handler(exc, context)

        if response is None:
            self.raise_uncaught_exception(exc)

        response.exception = True
        return response 
Example #3
Source File: viewsets.py    From django-rest-registration with MIT License 5 votes vote down vote up
def perform_create(self, serializer):
        user = self.request.user
        if not user.is_authenticated:
            raise NotAuthenticated()
        serializer.save(reporter=user) 
Example #4
Source File: viewsets.py    From django-rest-registration with MIT License 5 votes vote down vote up
def _vote(self, request, pk, options):
        user = request.user
        if not user.is_authenticated:
            raise NotAuthenticated()
        vote, _ = LinkVote.objects.get_or_create(
            link_id=pk,
            voter=user,
            defaults=options,
        )
        for name, value in options.items():
            setattr(vote, name, value)
        vote.save()
        serializer = LinkSerializer(instance=vote.link)
        return Response(serializer.data) 
Example #5
Source File: decorators.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def raise_exception_treat(func):
    @functools.wraps(func)
    def inner(self, request, *args, **kwargs):
        try:
            return func(self, request, *args, **kwargs)
        except ValidationError, error:
            log.error(error)
            raise rest_exceptions.ValidationExceptionJson(error)
        except (exceptions_api.APIException, exceptions_api.AuthenticationFailed,
                exceptions_api.MethodNotAllowed, exceptions_api.NotAcceptable,
                exceptions_api.NotAuthenticated, exceptions_api.ParseError,
                exceptions_api.PermissionDenied, exceptions_api.Throttled,
                exceptions_api.UnsupportedMediaType, rest_exceptions.ValidationAPIException), error:
            log.error(error)
            raise error 
Example #6
Source File: exceptionhandler.py    From BrewCenterAPI with GNU General Public License v3.0 5 votes vote down vote up
def custom_exception_handler(exc, context):
    # if its a view with a list and request attr
    if 'view' in context and hasattr(context['view'], 'list') and hasattr(context['view'], 'request'):
        view = context['view']
        request = view.request

        if request.method == 'GET' and settings.ENABLE_UNAUTHENTICATED_RESULTS and isinstance(exc, NotAuthenticated):
            return view.list(context['request'])

    return exception_handler(exc, context) 
Example #7
Source File: import_task.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        if self.request.user.is_anonymous:
            raise exceptions.NotAuthenticated()
        itask_data = {
            'library': request.POST.get('library') not in ['false', False],
            # NOTE: 'filename' here comes from 'name' (!) in the POST data
            'filename': request.POST.get('name', None),
            'destination': request.POST.get('destination', None),
        }
        if 'base64Encoded' in request.POST:
            encoded_str = request.POST['base64Encoded']
            encoded_substr = encoded_str[encoded_str.index('base64') + 7:]
            itask_data['base64Encoded'] = encoded_substr
        elif 'file' in request.data:
            encoded_xls = to_str(base64.b64encode(request.data['file'].read()))
            itask_data['base64Encoded'] = encoded_xls
            if 'filename' not in itask_data:
                itask_data['filename'] = request.data['file'].name
        elif 'url' in request.POST:
            itask_data['single_xls_url'] = request.POST['url']
        import_task = ImportTask.objects.create(user=request.user,
                                                data=itask_data)
        # Have Celery run the import in the background
        import_in_background.delay(import_task_uid=import_task.uid)
        return Response({
            'uid': import_task.uid,
            'url': reverse(
                'importtask-detail',
                kwargs={'uid': import_task.uid},
                request=request),
            'status': ImportTask.PROCESSING
        }, status.HTTP_201_CREATED) 
Example #8
Source File: asset.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def hash(self, request):
        """
        Creates an hash of `version_id` of all accessible assets by the user.
        Useful to detect changes between each request.

        :param request:
        :return: JSON
        """
        user = self.request.user
        if user.is_anonymous:
            raise exceptions.NotAuthenticated()
        else:
            accessible_assets = get_objects_for_user(
                user, "view_asset", Asset).filter(asset_type=ASSET_TYPE_SURVEY) \
                .order_by("uid")

            assets_version_ids = [asset.version_id for asset in accessible_assets if asset.version_id is not None]
            # Sort alphabetically
            assets_version_ids.sort()

            if len(assets_version_ids) > 0:
                hash = md5(hashable_str("".join(assets_version_ids))).hexdigest()
            else:
                hash = ""

            return Response({
                "hash": hash
            }) 
Example #9
Source File: views.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def permission_denied(self, request, message=None):
        """
        If request is not permitted, determine what kind of exception to raise.
        """
        if request.authenticators and not request.successful_authenticator:
            raise exceptions.NotAuthenticated()
        raise exceptions.PermissionDenied(detail=message) 
Example #10
Source File: export_task.py    From kpi with GNU Affero General Public License v3.0 4 votes vote down vote up
def create(self, request, *args, **kwargs):
        if self.request.user.is_anonymous:
            raise exceptions.NotAuthenticated()

        # Read valid options from POST data
        valid_options = (
            'type',
            'source',
            'group_sep',
            'lang',
            'hierarchy_in_labels',
            'fields_from_all_versions',
        )
        task_data = {}
        for opt in valid_options:
            opt_val = request.POST.get(opt, None)
            if opt_val is not None:
                task_data[opt] = opt_val
        # Complain if no source was specified
        if not task_data.get('source', False):
            raise exceptions.ValidationError(
                {'source': 'This field is required.'})
        # Get the source object
        source_type, source = _resolve_url_to_asset_or_collection(
            task_data['source'])
        # Complain if it's not an Asset
        if source_type != 'asset':
            raise exceptions.ValidationError(
                {'source': 'This field must specify an asset.'})
        # Complain if it's not deployed
        if not source.has_deployment:
            raise exceptions.ValidationError(
                {'source': 'The specified asset must be deployed.'})
        # Create a new export task
        export_task = ExportTask.objects.create(user=request.user,
                                                data=task_data)
        # Have Celery run the export in the background
        export_in_background.delay(export_task_uid=export_task.uid)
        return Response({
            'uid': export_task.uid,
            'url': reverse(
                'exporttask-detail',
                kwargs={'uid': export_task.uid},
                request=request),
            'status': ExportTask.PROCESSING
        }, status.HTTP_201_CREATED)