Пример #1
0
    def post(self, request, *args, **kwargs):
        if self.user_is_already_rsvped:
            raise MethodNotAllowed(
                "POST",
                detail={
                    "redirectTo": reverse("view_event", kwargs={"pk": self.object.pk})
                },
            )

        if bool(self.object.subscription_form_id):
            raise MethodNotAllowed(
                "POST",
                detail={
                    "redirectTo": reverse("rsvp_event", kwargs={"pk": self.object.pk})
                },
            )

        if not self.object.is_free:
            if "rsvp_submission" in request.session:
                del request.session["rsvp_submission"]
            request.session["rsvp_event"] = str(self.object.pk)
            request.session["is_guest"] = False
            raise MethodNotAllowed(
                "POST",
                detail={"redirectTo": reverse("pay_event")},
            )

        return super().post(request, *args, **kwargs)
Пример #2
0
    def create(self, request, *args, **kwargs):
        if request.method.lower() == 'post':
            if request.user.is_anonymous():
                request.data['groups'] = []
                serializer = UserRegistrationSerializer(data=request.data)

                if serializer.is_valid(raise_exception=True):
                    if len(User.objects.filter(
                            email=serializer.data['email'])):
                        raise ValidationError(
                            {"email": "This email has been used already."})
                    user = serializer.create(serializer.validated_data)
                    user.groups = []
                    user.set_password(serializer.data['password'])
                    user.is_active = True
                    user.save()
                    serializer = UserSerializer(user)

                    return Response(serializer.data)
                else:
                    raise NotAcceptable()
            else:
                raise PermissionDenied('You are already registered.')
        else:
            raise MethodNotAllowed(request.method)
Пример #3
0
    def activate(self, request, pk=None):
        if not settings.AUTH_WORKFLOW:
            raise MethodNotAllowed('put')

        profile = get_object_or_404(Profile, pk=pk)
        profile.activate(request)
        return Response(self.get_serializer(profile).data)
Пример #4
0
 def post(self, request, format='json', *args, **kwargs):
     #Only JSON accepted for edit/create/delete
     if not format == 'json':
         raise MethodNotAllowed('')
     else:
         return super(AlertCreateAPI, self).post(request, format, *args,
                                                 **kwargs)
    async def handle_action(self, action: str, request_id: str, **kwargs):
        """
        Handle a call for a given action.

        This method checks permissions and handles exceptions sending
        them back over the ws connection to the client.

        If there is no action listed on the consumer for this action name
        a `MethodNotAllowed` error is sent back over the ws connection.
        """
        try:
            await self.check_permissions(action, **kwargs)

            if action not in self.available_actions:
                raise MethodNotAllowed(method=action)

            method_name = self.available_actions[action]
            method = getattr(self, method_name)

            reply = partial(self.reply, action=action, request_id=request_id)

            # the @action decorator will wrap non-async action into async ones.

            response = await method(request_id=request_id, action=action, **kwargs)

            if isinstance(response, tuple):
                data, status = response
                await reply(data=data, status=status)

        except Exception as exc:
            await self.handle_exception(exc, action=action, request_id=request_id)
Пример #6
0
    def activate(self, request, pk=None):
        if not get_account_workflow():
            raise MethodNotAllowed()

        profile = get_object_or_404(Profile, pk=pk)
        profile.activate(request)
        return Response(self.get_serializer(profile).data)
Пример #7
0
    def update(self, request, *args, **kwargs):
        """
            Don't Allow PUT only PATCH should be there for updates
            Name should not be allowed to be updated
        """
        if (request.method == "PUT"):
            raise MethodNotAllowed(method='PUT',
                                   detail='Method "PUT" not allowed')

        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance,
                                         data=request.data,
                                         partial=partial)
        serializer.is_valid(raise_exception=True)

        if ("name" in request.data.keys()):
            name_in_db = instance.name
            print(name_in_db, request.data["name"])
            if (name_in_db != request.data["name"]):
                return Response({"detail": "Name Can't be updated again"},
                                status.HTTP_403_FORBIDDEN)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response(serializer.data)
Пример #8
0
def get_obj_method_permissions(self, **kwargs):
    method = self.request.method
    try:
        permission_classes = kwargs[method]
    except KeyError:
        raise MethodNotAllowed(method)
    return (permission() for permission in permission_classes)
Пример #9
0
 def get(self, request, *args, **kwargs):
     if request.user.is_authenticated:
         if getattr(settings, "OSCARAPI_EXPOSE_USER_DETAILS", False):
             ser = UserSerializer(request.user, many=False)
             return Response(ser.data)
         return Response(status=status.HTTP_204_NO_CONTENT)
     raise MethodNotAllowed("GET")
    def create(self, request, *args, **kwargs):
        if request.user.is_superuser or request.user.is_staff:
            log_action(request)
            return super(SectionImageViewSet,
                         self).create(request, *args, **kwargs)

        raise MethodNotAllowed('POST')
Пример #11
0
 def check_permissions(self, request):
     if request.method in ("PUT", "PATCH", "DELETE"):
         # TODO make sure Swagger or other doc generation doesn't skip methods mentioned in above condition
         post = get_object_or_404(models.Post, id=self.kwargs["id"])
         if post.user != request.user:
             raise MethodNotAllowed(request.method)
     return super().check_permissions(request)
Пример #12
0
    def has_create_permission(cls, request, serializer):
        """Authorize a new resource to be created.

        This is not an overwritten BasePermission method, but a custom method necessary for our access policy that depends on the incoming resource.

        This method must be called after deserialization and validation of the incoming request data to prevent injection attacks. 
        To my understanding, the only place to do so on a generic viewset is in the `perform_create()` method.
        Thus: Overwrite `perform_create()` on your viewset and call the present method there.
        """
        if request.method == "POST":
            # Is the authorized user an OWNER of the organization to which the resource
            # is to be added?
            owner = serializer.get_owner()
            logger.debug(
                "Check create permission for user #%s in organization #%s.",
                request.user.id,
                owner.id,
            )
            try:
                membership = request.user.memberships.get(
                    organization__id=owner.id)
            except Membership.DoesNotExist:
                raise PermissionDenied
            return membership.isOwner()  # TODO: Make role parameterizable.
        else:
            # Should never happen.
            raise MethodNotAllowed(request.method)
Пример #13
0
def process_file_list_view(request, **kwargs):
    """List and copy over process output files."""
    process = kwargs.get("process")
    if request.user.is_authenticated and request.user == process.project.user:
        if request.method == "GET":
            return Response(
                status=status.HTTP_200_OK,
                data=[{
                    "file":
                    x,
                    "preset":
                    OutputTemplate.match_any(x,
                                             process.script.output_templates),
                } for x in process.file_list],
            )
        elif request.method == "POST":
            if ("files" in request.data.keys()
                    and type(request.data["files"]) == list):
                sanitized_files = [
                    x for x in request.data["files"] if type(x) == str
                ]
                process.move_downloaded_output_files(files=sanitized_files)
                return Response(status=status.HTTP_200_OK)
            else:
                raise ValidationError(
                    detail={"files": "A list of strings is required."})
        else:
            raise MethodNotAllowed(method=request.method)
    else:
        raise PermissionDenied
Пример #14
0
 def get_serializer_class(self):
     if self.request.method == 'POST':
         return CreateCategorySerializer
     elif self.request.method == 'GET':
         return RetrieveCategorySerializer
     else:
         raise MethodNotAllowed()
Пример #15
0
    def relationship_create(self, request, pk, relationship):
        # get the relationship handler
        handler = self.get_relationship_handler(relationship)
        serializer_class = handler.serializer_class

        if not handler.many:
            # to-one relationships do not have a detail route
            raise MethodNotAllowed("POST")

        resource = self.get_resource(request, pk)
        data = request.data["data"]

        # data could be a single Resource Identifier or an array of Resource
        # Identifiers. Let's convert single items to a single-item list.
        if isinstance(data, dict):
            data = listify(data)
        data = handler.validate(data)

        related = serializer_class.from_identity(data, many=handler.many)

        handler.add_related(resource, related, request)

        return Response(
            status=status.HTTP_204_NO_CONTENT, context={"resource": resource}
        )
 def has_permission(self, request, view):
     """
     超级管理员角色,只能操作
     """
     user = request.user
     if isinstance(user, AnonymousUser):
         return False
     # 当前api操作是否是针对指定对象的操作
     try:
         # 当前接口如果最后一位是可变参数,则需要排除掉此部分
         int(request.path[-1])
         req_path = "/".join(request.path.split('/')[:-1])
     except ValueError:
         req_path = request.path
     if "common" in req_path:
         # 通用接口,不受到权限的控制
         return True
     # 查询当前角色所拥有的权限信息,以及权限对应的api的信息
     api_list = user.get_permission_api_list()
     # 接口权限过滤,判断当前用户是否拥有当前接口的操作权限
     for api in api_list:
         if req_path == api.path:
             if request.META['REQUEST_METHOD'] != api.method:
                 raise MethodNotAllowed(request.META['REQUEST_METHOD'])
             return True
     return False
Пример #17
0
    def check_permissions(self, request, view, obj=None):
        '''
        Perform basic permissions checking before delegating to the appropriate
        method based on the request method.
        '''

        # Don't allow anonymous users. 401, not 403, hence no raised exception.
        if not request.user or request.user.is_anonymous():
            return False

        # Always allow superusers
        if getattr(view, 'always_allow_superuser',
                   True) and request.user.is_superuser:
            return True

        # Check if view supports the request method before checking permission
        # based on request method.
        if request.method.upper() not in view.allowed_methods:
            raise MethodNotAllowed(request.method)

        # Check permissions for the given view and object, based on the request
        # method used.
        check_method = getattr(self,
                               'check_%s_permissions' % request.method.lower(),
                               None)
        result = check_method and check_method(request, view, obj)
        if not result:
            raise PermissionDenied()

        return result
    async def handle_action(self, action: str, request_id: str, **kwargs):
        """
        run the action.
        """
        try:
            await self.check_permissions(action, **kwargs)

            if action not in self.available_actions:
                raise MethodNotAllowed(method=action)

            method_name = self.available_actions[action]
            method = getattr(self, method_name)

            reply = partial(self.reply, action=action, request_id=request_id)

            # the @action decorator will wrap non-async action into async ones.

            response = await method(request_id=request_id,
                                    action=action,
                                    **kwargs)

            if isinstance(response, tuple):
                data, status = response
                await reply(data=data, status=status)

        except Exception as exc:
            await self.handle_exception(exc,
                                        action=action,
                                        request_id=request_id)
Пример #19
0
def dictionary_get_update(request, **kwargs):
    """Get or update the dictionary file(s)."""
    project = kwargs.get("project")
    if request.user.is_authenticated and request.user == project.user:
        if request.method == "GET":
            dictionary_files_with_content = get_dictionary_files_with_content(
                project
            )
            return Response(
                status=status.HTTP_200_OK,
                data={"files": dictionary_files_with_content},
            )
        elif request.method == "PATCH":
            if "files" in request.data and type(request.data["files"]) == list:
                update_dictionary_data(project, request.data["files"])
                dictionary_files_with_content = get_dictionary_files_with_content(
                    project
                )
                return Response(
                    status=status.HTTP_200_OK,
                    data={"files": dictionary_files_with_content},
                )
            else:
                raise ValidationError(
                    detail="A list of dictionaries is required."
                )
        else:
            raise MethodNotAllowed(method=request.method)
    else:
        raise PermissionDenied
Пример #20
0
    def getSBMLModelFile(self):

        if self.model.format == LogicalModel.ZGINML:
            ginsim_model = ginsim.load(
                join(settings.MEDIA_ROOT, self.model.file.path))

            path = tempfile.mkdtemp()
            tmp_sbml = tempfile.mkstemp(dir=path, suffix='.sbml')[1]

            biolqm.save(ginsim_model, tmp_sbml, "sbml")
            return tmp_sbml

        elif self.model.format == LogicalModel.MABOSS:
            ginsim_model = self.getBioLQMModel()

            path = tempfile.mkdtemp()
            tmp_sbml = tempfile.mkstemp(dir=path, suffix='.sbml')[1]

            biolqm.save(ginsim_model, tmp_sbml, "sbml")
            return tmp_sbml

        elif self.model.format == LogicalModel.SBML:
            return join(settings.MEDIA_ROOT, self.model.file.path)

        else:
            raise MethodNotAllowed()
Пример #21
0
 def http_method_not_allowed(self, **kwargs):
     method = kwargs.get('method')
     logger.warning(
         "Method Not Allowed (%s). Add the name to 'additional_method_names'",
         method,
         extra={'status_code': 405})
     raise MethodNotAllowed(method)
Пример #22
0
 def perform_destroy(self, instance):
     if not instance.can_delete():
         raise MethodNotAllowed(
             'DELETE',
             'DELETE not allowed for works with related works or documents, unlink documents and works first.'
         )
     return super(WorkViewSet, self).perform_destroy(instance)
Пример #23
0
 def perform_destroy(self, instance):
     if not instance.draft:
         raise MethodNotAllowed('DELETE', 'DELETE not allowed for published documents, mark as draft first.')
     instance.deleted = True
     action.send(self.request.user, verb='deleted', action_object=instance,
                 place_code=instance.work.place.place_code)
     instance.save()
Пример #24
0
def process(request):

    if Task.objects.count() == 0:
        fill_locations()

    if request.method == 'GET':
        data = {'tasks': [], 'stats': {}}
        for task in Task.objects.all():
            if task.queue != 'process':
                continue
            item = {}
            item['id'] = task.task_hash
            item['time'] = int(task.run_at.timestamp())
            item['label'] = task.task_name
            item['parameters'] = json.loads(task.task_params)
            data['tasks'].append(item)
        data['stats']['last_calculated_positon'] = int(
            Position.objects.filter(
                explicit=False,
                source='cron').order_by('-time')[0].time.timestamp())
        data['stats']['last_generated_event'] = int(
            Event.objects.order_by('-timestart')[0].timestart.timestamp())
        response = HttpResponse(json.dumps(data),
                                content_type='application/json')
        return response

    if request.method != 'POST':
        raise MethodNotAllowed(str(request.method))
 def has_permission(self, request, view):
     """
     Url is composed from:
         uidb64 - encoded pk of the user
         token - generated token, but that token does not allow authentication.
             Moreover, after changing attributes that are part of
             the token, it's no longer valid.
     """
     # uidb64 and token might be passed as kwargs or as request data
     uidb64, token = view.kwargs.get('uidb64'), view.kwargs.get('token')
     if (uidb64 and token) is None:
         uidb64 = request.data.get('uidb64')
         token = request.data.get('token')
     try:
         # If the exception is raised then user could have just been deleted
         # or the uidb64 is wrong.
         uid = urlsafe_base64_decode(uidb64).decode()
         user = User.objects.get(pk=uid)
     except AttributeError:
         raise MethodNotAllowed(method='Password reset',
                                detail={
                                    'error': True,
                                    'message': 'You can\'t do that'
                                })
     if user is not None and default_token_generator.check_token(
             user, token):
         return True
     raise NotAcceptable({
         'error':
         True,
         'message':
         'That link is broken or it has already been used.'
     })
Пример #26
0
def sign_view_action(request):
    if request.method != 'POST':
        raise MethodNotAllowed(request.method)
    form = forms.ToSForm(request.POST)
    if form.is_valid():
        entry = models.SignedTOS()
        entry.user = request.user
        entry.first_name = request.user.first_name
        entry.last_name = request.user.last_name
        entry.street = request.user.street
        entry.post_code = request.user.post_code
        entry.created_at = form.cleaned_data['timestamp']
        filename = models.signed_file_path(instance=entry,
                                           filename="signed_file.html")
        entry.signed_file = filename
        absname = os.path.join(settings.MEDIA_ROOT, filename)
        abspath = ntpath.dirname(absname)
        os.makedirs(abspath)
        with open(absname, "wb") as fh:
            compressed = zlib.compress(form.cleaned_data['text'].encode())
            #            fh.write(form.cleaned_data['text'])
            fh.write(compressed)

        entry.save()
        messages.success(request, 'Tos signed!')
    else:
        for error in form.errors:
            messages.error(request, error)
    return redirect('admin:index')
Пример #27
0
    def list(self, request, *args, **kwargs):
        verification_code = request.GET.get('vc', None)
        redirect_after_verification = (request.GET.get('r', False) == 'True')
        resend_verification = (request.GET.get('resend', False) == 'True')
        user_email = request.GET.get('email', None)

        if verification_code is not None:
            try:
                user = User.objects.get(verification_code=verification_code)
                user.verify_user()
                if redirect_after_verification:
                    return HttpResponseRedirect(APP_USER_VERIFIED_PATH)
                else:
                    response = {"detail": "User account verified."}
                    return Response(response)
            except (ObjectDoesNotExist):
                if redirect_after_verification:
                    return HttpResponseRedirect(APP_USER_VERIFICATION_FAILED)
                else:
                    raise NotFound('Verification code not valid.')

        if user_email is not None:
            if resend_verification:
                try:
                    user = User.objects.get(email=user_email)
                    user.send_verification_email()
                    print('sent email for %s' % user)
                except (ObjectDoesNotExist):
                    response = {
                        "detail":
                        "If an account that matches the email provided exists you will receive and email with a verification link."
                    }
                    return Response(response)

        raise MethodNotAllowed('GET')
Пример #28
0
    def update(self, request, *args, **kwargs):
        if request.user.id == UUID(kwargs.get(
                'pk')) or request.user.is_superuser or request.user.is_staff:
            self.serializer_class = UserSerializer
            return super(UserViewSet, self).update(request, *args, **kwargs)

        raise MethodNotAllowed('PUT')
Пример #29
0
    def get(self, request, format=None):
        if settings.DEBUG:
            if request.user.is_authenticated:
                ser = UserSerializer(request.user, many=False)
                return Response(ser.data)
            return Response(status=status.HTTP_204_NO_CONTENT)

        raise MethodNotAllowed('GET')
Пример #30
0
 def initial(self, request, *args, **kwargs):
     super().initial(request, *args, **kwargs)
     if not django_settings.WALDUR_RANCHER['READ_ONLY_MODE']:
         return
     if self.action in ('import_resource', 'pull') and request.user.is_staff:
         return
     if self.request.method not in SAFE_METHODS:
         raise MethodNotAllowed(method=request.method)