Пример #1
0
    def post(self, request):
        form = RefreshTokenForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        try:
            claims = JWTFactory.decode(form.cleaned_data['refresh'])
        except JoseError as e:
            raise ProblemDetailException(request,
                                         _('Invalid token.'),
                                         status=HTTPStatus.UNAUTHORIZED,
                                         previous=e)

        redis = Redis(host=settings.REDIS_HOST,
                      port=settings.REDIS_PORT,
                      db=settings.REDIS_DATABASE)

        if not redis.exists(f"refresh_token:{claims['jti']}"):
            raise UnauthorizedException(request)

        access_token = JWTFactory(claims['sub']).access()

        return SingleResponse(request, {'access_token': access_token},
                              status=HTTPStatus.OK)
Пример #2
0
    def post(self, request):
        form = CreateAuthorForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        if not has_object_permission('check_catalog_write', request.user,
                                     form.cleaned_data['catalog_id']):
            raise ProblemDetailException(request,
                                         _("Insufficient permissions"),
                                         status=HTTPStatus.FORBIDDEN)

        if Author.objects.filter(
                catalog=form.cleaned_data['catalog_id'],
                name=form.cleaned_data['name'],
                surname=form.cleaned_data['surname']).exists():
            raise ProblemDetailException(
                request,
                _("Author already exists in the catalog"),
                status=HTTPStatus.CONFLICT)

        author = Author()
        form.populate(author)
        author.save()

        return SingleResponse(request,
                              author,
                              serializer=AuthorSerializer.Detailed,
                              status=HTTPStatus.CREATED)
Пример #3
0
    def post(self, request):
        form = CreateUserForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        if not request.user.has_perm('core.add_user'):
            raise ProblemDetailException(request,
                                         _("Insufficient permissions"),
                                         status=HTTPStatus.FORBIDDEN)

        if User.objects.filter(email=form.cleaned_data['email']).exists():
            raise ProblemDetailException(
                request,
                _("User with same email already exists"),
                status=HTTPStatus.CONFLICT)

        user = User()
        form.populate(user)
        user.set_password(form.cleaned_data['password'])
        user.save()

        return SingleResponse(request,
                              user,
                              serializer=UserSerializer.Base,
                              status=HTTPStatus.CREATED)
Пример #4
0
    def put(self, request, feed_id: UUID):
        feed = self._get_feed(request, feed_id)

        form = FeedForm.create_from_request(request)
        form['parents'].queryset = form['parents'].queryset.exclude(pk=feed.pk)

        if not form.is_valid():
            raise ValidationException(request, form)

        if Feed.objects.filter(catalog=form.cleaned_data['catalog_id'],
                               url_name=form.cleaned_data['url_name']).exclude(
                                   pk=feed.id).exists():
            raise ProblemDetailException(
                request,
                _("Feed with same url_name already exists in same catalog"),
                status=HTTPStatus.CONFLICT)

        form.populate(feed)
        feed.save()

        if feed.kind == Feed.FeedKind.ACQUISITION and 'entries' in form.cleaned_data.keys(
        ):
            feed.entries.clear()
            feed.entries.add(*form.cleaned_data['entries'])

        if feed.kind == Feed.FeedKind.NAVIGATION and 'parents' in form.cleaned_data.keys(
        ):
            feed.parents.clear()
            feed.parents.add(*form.cleaned_data['parents'])

        return SingleResponse(request, feed, serializer=FeedSerializer.Base)
Пример #5
0
    def post(self, request):
        form = AccessTokenForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        backend = ModelBackend()
        user = backend.authenticate(request,
                                    username=form.cleaned_data['username'],
                                    password=form.cleaned_data['password'])

        if not user:
            raise UnauthorizedException(request)

        access_token = JWTFactory(user.pk).access()
        jti, refresh_token = JWTFactory(user.pk).refresh()

        redis = Redis(host=settings.REDIS_HOST,
                      port=settings.REDIS_PORT,
                      db=settings.REDIS_DATABASE)

        redis.set(f"refresh_token:{jti}", jti)
        redis.expire(f"refresh_token:{jti}",
                     settings.SECURED_VIEW_JWT_REFRESH_TOKEN_EXPIRATION)

        return SingleResponse(request, {
            'access_token': access_token,
            'refresh_token': refresh_token
        },
                              status=HTTPStatus.OK)
Пример #6
0
    def post(self, request):
        form = CatalogForm.create_from_request(request)

        if not request.user.has_perm('core.add_catalog'):
            raise ProblemDetailException(request,
                                         _("Insufficient permissions"),
                                         status=HTTPStatus.FORBIDDEN)

        if not form.is_valid():
            raise ValidationException(request, form)

        if Catalog.objects.filter(
                url_name=form.cleaned_data['url_name']).exists():
            raise ProblemDetailException(
                request,
                title=_('Catalog url_name already taken'),
                status=HTTPStatus.CONFLICT)

        service = CatalogService()
        catalog = service.populate(catalog=Catalog(creator=request.user),
                                   form=form)

        if not catalog.users.contains(request.user):
            UserCatalog.objects.create(catalog=catalog,
                                       user=request.user,
                                       mode=UserCatalog.Mode.MANAGE)

        return SingleResponse(request,
                              catalog,
                              serializer=CatalogSerializer.Detailed,
                              status=HTTPStatus.CREATED)
Пример #7
0
    def post(self, request):
        form = FeedForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        if not has_object_permission('check_catalog_manage', request.user,
                                     form.cleaned_data['catalog_id']):
            raise ProblemDetailException(request,
                                         _("Insufficient permissions"),
                                         status=HTTPStatus.FORBIDDEN)

        if Feed.objects.filter(
                catalog=form.cleaned_data['catalog_id'],
                url_name=form.cleaned_data['url_name']).exists():
            raise ProblemDetailException(
                request,
                _("Feed with same url_name already exists in same catalog"),
                status=HTTPStatus.CONFLICT)

        feed = Feed(creator=request.user)
        form.populate(feed)
        feed.save()

        if 'entries' in form.cleaned_data.keys():
            feed.entries.add(*form.cleaned_data['entries'])

        if 'parents' in form.cleaned_data.keys():
            feed.parents.add(*form.cleaned_data['parents'])

        return SingleResponse(request,
                              feed,
                              serializer=FeedSerializer.Base,
                              status=HTTPStatus.CREATED)
Пример #8
0
    def put(self, request, user_id: UUID):
        form = UserForm.create_from_request(request)

        user = self._get_user(
            request, user_id,
            lambda: request.user.has_perm('core.change_user'))

        if not form.is_valid():
            raise ValidationException(request, form)

        form.populate(user)
        if 'password' in form.cleaned_data.keys():
            user.set_password(form.cleaned_data['password'])
        user.save()

        return SingleResponse(request, user, serializer=UserSerializer.Base)
Пример #9
0
    def put(self, request, catalog_id: uuid.UUID, entry_id: uuid.UUID):
        entry = self._get_entry(request, catalog_id, entry_id)

        form = EntryForm.create_from_request(request)
        form.fields['category_ids'].queryset = form.fields['category_ids'].queryset.filter(catalog_id=catalog_id)
        form.fields['author_id'].queryset = form.fields['author_id'].queryset.filter(catalog_id=catalog_id)

        if not form.is_valid():
            raise ValidationException(request, form)

        service = EntryService(
            Catalog.objects.get(pk=catalog_id), request.user
        )
        service.populate(entry, form)

        return SingleResponse(request, entry, serializer=EntrySerializer.Detailed)
Пример #10
0
    def post(self, request):
        form = ApiKeyForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        if 'user_id' in form.cleaned_data.keys(
        ) and not request.user.is_superuser:
            raise ProblemDetailException(request,
                                         _("Insufficient permissions"),
                                         status=HTTPStatus.FORBIDDEN)

        api_key = ApiKey(user=request.user)
        form.populate(api_key)
        api_key.save()

        return SingleResponse(request,
                              api_key,
                              serializer=ApiKeySerializer.Base,
                              status=HTTPStatus.CREATED)
Пример #11
0
    def put(self, request, catalog_id: UUID):
        form = CatalogForm.create_from_request(request)

        if not form.is_valid():
            raise ValidationException(request, form)

        catalog = self._get_catalog(request, catalog_id)

        if Catalog.objects.exclude(pk=catalog.pk).filter(
                url_name=form.cleaned_data['url_name']).exists():
            raise ProblemDetailException(
                request,
                title=_('Catalog url_name already taken'),
                status=HTTPStatus.CONFLICT)

        service = CatalogService()
        catalog = service.populate(catalog=catalog, form=form)

        return SingleResponse(request,
                              catalog,
                              serializer=CatalogSerializer.Detailed)
Пример #12
0
    def post(self, request, catalog_id: uuid.UUID):
        try:
            catalog = Catalog.objects.get(pk=catalog_id)
        except Catalog.DoesNotExist as e:
            raise ProblemDetailException(request, _("Catalog not found"), status=HTTPStatus.NOT_FOUND, previous=e)

        if not has_object_permission('check_catalog_write', request.user, catalog):
            raise ProblemDetailException(request, _("Insufficient permissions"), status=HTTPStatus.FORBIDDEN)

        form = EntryForm.create_from_request(request)
        form.fields['category_ids'].queryset = form.fields['category_ids'].queryset.filter(catalog=catalog)
        form.fields['author_id'].queryset = form.fields['author_id'].queryset.filter(catalog=catalog)

        if not form.is_valid():
            raise ValidationException(request, form)

        entry = Entry(creator=request.user, catalog=catalog)
        service = EntryService(catalog, request.user)
        service.populate(entry, form)

        return SingleResponse(request, entry, serializer=EntrySerializer.Detailed, status=HTTPStatus.CREATED)
Пример #13
0
    def post(self, request, catalog_id: uuid.UUID, entry_id: uuid.UUID):
        entry = self._get_entry(request, catalog_id, entry_id)

        try:
            metadata = json.loads(request.POST.get('metadata', '{}'))
        except json.JSONDecodeError as e:
            raise ProblemDetailException(
                request,
                title=_('Unable to parse metadata for request file'),
                status=HTTPStatus.BAD_REQUEST,
                previous=e
            )

        form = AcquisitionMetaForm(metadata, request)

        if not form.is_valid():
            raise ValidationException(request, form)

        acquisition = Acquisition(
            entry=entry,
            relation=form.cleaned_data.get('relation', Acquisition.AcquisitionType.ACQUISITION),
            mime=request.FILES['content'].content_type
        )

        if 'content' in request.FILES.keys():
            acquisition.content.save(
                f"{uuid.uuid4()}{mimetypes.guess_extension(acquisition.mime)}",
                request.FILES['content']
            )

        for price in form.cleaned_data.get('prices', []):
            Price.objects.create(
                acquisition=acquisition,
                currency=price['currency_code'],
                value=price['value']
            )

        return SingleResponse(
            request, acquisition, serializer=AcquisitionSerializer.Detailed, status=HTTPStatus.CREATED
        )
Пример #14
0
    def put(self, request, author_id: UUID):
        form = CreateAuthorForm.create_from_request(request)
        author = self._get_author(request, author_id)

        if not form.is_valid():
            raise ValidationException(request, form)

        if Author.objects.exclude(pk=author_id).filter(
                catalog=form.cleaned_data['catalog_id'],
                name=form.cleaned_data['name'],
                surname=form.cleaned_data['surname'],
        ).exists():
            raise ProblemDetailException(
                request,
                _("Author already exists in the catalog"),
                status=HTTPStatus.CONFLICT)

        form.populate(author)
        author.save()

        return SingleResponse(request,
                              author,
                              serializer=AuthorSerializer.Detailed)