Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

[37868] Whitelist for attachment mime types and extensions on upload (#9431)

Oliver Günthere9d7c374ccc5
diff --git a/app/contracts/attachments/create_contract.rb b/app/contracts/attachments/create_contract.rb
new file mode 100644
index 00000000000..6c7c36078ce
--- /dev/null
+++ b/app/contracts/attachments/create_contract.rb
@@ -0,0 +1,98 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Attachments
+ class CreateContract < ::ModelContract
+ attribute :file
+ attribute :filename
+ attribute :filesize
+ attribute :digest
+ attribute :description
+ attribute :content_type
+ attribute :container
+ attribute :container_type
+ attribute :author
+
+ validates :filename, presence: true
+
+ validate :validate_attachments_addable
+ validate :validate_container_addable
+ validate :validate_author
+ validate :validate_content_type
+
+ private
+
+ def validate_attachments_addable
+ return if model.container
+
+ if Redmine::Acts::Attachable.attachables.none?(&:attachments_addable?)
+ errors.add(:base, :error_unauthorized)
+ end
+ end
+
+ def validate_author
+ unless model.author == user
+ errors.add(:author, :invalid)
+ end
+ end
+
+ def validate_container_addable
+ return unless model.container
+
+ errors.add(:base, :error_unauthorized) unless model.container.attachments_addable?(user)
+ end
+
+ ##
+ # Validates the content type, if a whitelist is set
+ def validate_content_type
+ # If the whitelist is empty, assume all files are allowed
+ # as before
+ unless matches_whitelist?(attachment_whitelist)
+ Rails.logger.info { "Uploaded file #{model.filename} with type #{model.content_type} does not match whitelist" }
+ errors.add :content_type, :not_whitelisted, value: model.content_type
+ end
+ end
+
+ ##
+ # Get the user-defined whitelist or a custom whitelist
+ # defined for this invocation
+ def attachment_whitelist
+ Array(options.fetch(:whitelist, Setting.attachment_whitelist))
+ end
+
+ ##
+ # Returns whether the attachment matches the whitelist
+ def matches_whitelist?(whitelist)
+ return true if whitelist.empty?
+
+ whitelist.include?(model.content_type) || whitelist.include?("*#{model.extension}")
+ end
+ end
+end
diff --git a/app/contracts/attachments/prepare_upload_contract.rb b/app/contracts/attachments/prepare_upload_contract.rb
new file mode 100644
index 00000000000..91f6a717dee
--- /dev/null
+++ b/app/contracts/attachments/prepare_upload_contract.rb
@@ -0,0 +1,41 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Attachments
+ class PrepareUploadContract < CreateContract
+ validate :validate_direct_uploads_active
+
+ private
+
+ def validate_direct_uploads_active
+ errors.add :base, :not_available unless OpenProject::Configuration.direct_uploads?
+ end
+ end
+end
diff --git a/app/contracts/base_contract.rb b/app/contracts/base_contract.rb
index be5bbe32ef2..ed2c12951fe 100644
--- a/app/contracts/base_contract.rb
+++ b/app/contracts/base_contract.rb
@@ -82,7 +82,7 @@ class BaseContract < Disposable::Twin
end
def attribute(attribute, options = {}, &block)
- property attribute
+ property attribute, options.slice(:readable)
add_writable(attribute, options[:writeable])
attribute_permission(attribute, options[:permission])
diff --git a/app/contracts/wiki_pages/update_contract.rb b/app/contracts/wiki_pages/update_contract.rb
new file mode 100644
index 00000000000..3aa737381de
--- /dev/null
+++ b/app/contracts/wiki_pages/update_contract.rb
@@ -0,0 +1,32 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module WikiPages
+ class UpdateContract < BaseContract
+ end
+end
diff --git a/lib/api/v3/attachments/attachment_metadata_representer.rb b/app/controllers/admin/settings/attachments_settings_controller.rb
similarity index 63%
rename from lib/api/v3/attachments/attachment_metadata_representer.rb
rename to app/controllers/admin/settings/attachments_settings_controller.rb
index 323bf60e69f..fcd768575d0 100644
--- a/lib/api/v3/attachments/attachment_metadata_representer.rb
+++ b/app/controllers/admin/settings/attachments_settings_controller.rb
@@ -28,28 +28,19 @@
# See docs/COPYRIGHT.rdoc for more details.
#++
-require 'roar/decorator'
-require 'roar/json/hal'
+module Admin::Settings
+ class AttachmentsSettingsController < ::Admin::SettingsController
+ menu_item :settings_attachments
-module API
- module V3
- module Attachments
- class AttachmentMetadataRepresenter < ::API::Decorators::Single
- def initialize(attachment)
- super(attachment, current_user: nil)
- end
+ def default_breadcrumb
+ t(:'attributes.attachments')
+ end
- property :file_name
- property :description,
- getter: ->(*) {
- ::API::Decorators::Formattable.new(description, plain: true)
- },
- setter: ->(fragment:, **) { self.description = fragment['raw'] },
- render_nil: true
+ private
- property :content_type, render_nil: false
- property :file_size, render_nil: false
- property :digest, render_nil: false
+ def settings_params
+ super.tap do |settings|
+ settings["attachment_whitelist"] = settings["attachment_whitelist"].split(/\r?\n/)
end
end
end
diff --git a/app/controllers/concerns/attachable_service_call.rb b/app/controllers/concerns/attachable_service_call.rb
new file mode 100644
index 00000000000..5803a95b191
--- /dev/null
+++ b/app/controllers/concerns/attachable_service_call.rb
@@ -0,0 +1,66 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module AttachableServiceCall
+ ##
+ # Call the presented CreateContract service
+ # with the given params, merging in any attachment params
+ #
+ # @param service_cls the service class instance
+ # @param args permitted args for the service call
+ def attachable_create_call(service_cls, args:)
+ service_cls
+ .new(user: current_user)
+ .call(args.merge(attachment_params))
+ end
+
+ ##
+ # Call the presented UpdateContract service
+ # with the given params, merging in any attachment params
+ #
+ # @param service_cls the service class instance
+ # @param args permitted args for the service call
+ def attachable_update_call(service_cls, model:, args:)
+ service_cls
+ .new(user: current_user, model: model)
+ .call(args.merge(attachment_params))
+ end
+
+ ##
+ # Attachable parameters mapped to a format the
+ # SetReplacements service concern
+ def attachment_params
+ attachment_params = permitted_params.attachments.to_h
+
+ if attachment_params.any?
+ { attachment_ids: attachment_params.values.map(&:values).flatten }
+ else
+ {}
+ end
+ end
+end
diff --git a/app/controllers/wiki_controller.rb b/app/controllers/wiki_controller.rb
index 03ffe95dec5..3ddfd161774 100644
--- a/app/controllers/wiki_controller.rb
+++ b/app/controllers/wiki_controller.rb
@@ -57,6 +57,7 @@ class WikiController < ApplicationController
before_action :handle_new_wiki_page, only: %i[show]
before_action :build_wiki_page_and_content, only: %i[new create]
+ include AttachableServiceCall
include AttachmentsHelper
include PaginationHelper
include Redmine::MenuManager::WikiMenuHelper
@@ -105,17 +106,18 @@ class WikiController < ApplicationController
end
def create
- @page.attributes = permitted_params.wiki_page
+ call = attachable_create_call ::WikiPages::CreateService,
+ args: permitted_params.wiki_page_with_content.to_h.merge(wiki: @wiki)
- @content.attributes = permitted_params.wiki_content
- @content.author = User.current
- @page.attach_files(permitted_params.attachments.to_h)
+ @page = call.result
+ @content = @page.content
- if @page.save
+ if call.success?
call_hook(:controller_wiki_edit_after_save, params: params, page: @page)
flash[:notice] = I18n.t(:notice_successful_create)
redirect_to_show
else
+ @errors = call.errors
render action: 'new'
end
end
@@ -165,22 +167,21 @@ class WikiController < ApplicationController
return
end
- @content = @page.content || @page.build_content
return if locked?
- @page.attach_files(permitted_params.attachments.to_h)
+ call = attachable_update_call ::WikiPages::UpdateService,
+ model: @page,
+ args: permitted_params.wiki_page_with_content.to_h
- @page.title = permitted_params.wiki_page[:title]
- @page.parent_id = permitted_params.wiki_page[:parent_id].presence
- @content.attributes = permitted_params.wiki_content
- @content.author = User.current
- @content.add_journal User.current, params['content']['comments']
+ @page = call.result
+ @content = @page.content
- if @page.save_with_content
+ if call.success?
call_hook(:controller_wiki_edit_after_save, params: params, page: @page)
flash[:notice] = I18n.t(:notice_successful_update)
redirect_to_show
else
+ @errors = call.errors
render action: 'edit'
end
rescue ActiveRecord::StaleObjectError
diff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rb
index 94cca1dbbdb..ff50fb10352 100644
--- a/app/helpers/settings_helper.rb
+++ b/app/helpers/settings_helper.rb
@@ -51,6 +51,11 @@ module SettingsHelper
controller: '/admin/settings/projects_settings',
label: :label_project_plural
},
+ {
+ name: 'attachments',
+ controller: '/admin/settings/attachments_settings',
+ label: :'attributes.attachments'
+ },
{
name: 'api',
controller: '/admin/settings/api_settings',
diff --git a/app/models/attachment.rb b/app/models/attachment.rb
index 15f32c7810e..3ad52806285 100644
--- a/app/models/attachment.rb
+++ b/app/models/attachment.rb
@@ -47,8 +47,8 @@ class Attachment < ApplicationRecord
acts_as_journalized
acts_as_event title: -> { file.name },
url: (Proc.new do |o|
- { controller: '/attachments', action: 'download', id: o.id, filename: o.filename }
- end)
+ { controller: '/attachments', action: 'download', id: o.id, filename: o.filename }
+ end)
mount_uploader :file, OpenProject::Configuration.file_uploader
@@ -148,7 +148,7 @@ class Attachment < ApplicationRecord
end
def filename
- attributes['file']
+ attributes['file'] || super
end
##
@@ -175,9 +175,7 @@ class Attachment < ApplicationRecord
end
def set_content_type(file)
- return if content_type.present?
-
- self.content_type = file.try(:content_type) || self.class.content_type_for(file.path)
+ self.content_type = self.class.content_type_for(file.path)
end
def set_digest(file)
@@ -255,37 +253,6 @@ class Attachment < ApplicationRecord
where(digest: "", downloads: -1)
end
- def self.create_pending_direct_upload(file_name:, author:, container: nil, content_type: nil, file_size: 0)
- a = create(
- container: container,
- author: author,
- content_type: content_type.presence || "application/octet-stream",
- filesize: file_size,
- digest: "",
- downloads: -1
- )
-
- # We need to do it like this because `file` is an uploader which expects a File (not a string)
- # to upload usually. But in this case the data has already been uploaded and we just point to it.
- a[:file] = pending_direct_upload_filename(file_name)
-
- a.save!
- a.reload # necessary so that the fog file uploader path is correct
-
- a
- end
-
- class << self
- private
-
- # The name has to be in the same format as what Carrierwave will produce later on. If they are different,
- # Carrierwave will alter the name (both local and remote) whenever the attachment is saved with the remote
- # file loaded.
- def pending_direct_upload_filename(file_name)
- CarrierWave::SanitizedFile.new(nil).send(:sanitize, file_name)
- end
- end
-
def pending_direct_upload?
digest == "" && downloads == -1
end
@@ -293,7 +260,7 @@ class Attachment < ApplicationRecord
private
def filesize_below_allowed_maximum
- if filesize > Setting.attachment_max_size.to_i.kilobytes
+ if filesize.to_i > Setting.attachment_max_size.to_i.kilobytes
errors.add(:file, :file_too_large, count: Setting.attachment_max_size.to_i.kilobytes)
end
end
diff --git a/app/models/mail_handler.rb b/app/models/mail_handler.rb
index d421d6cc1fc..085ab296b39 100644
--- a/app/models/mail_handler.rb
+++ b/app/models/mail_handler.rb
@@ -272,9 +272,15 @@ class MailHandler < ActionMailer::Base
binary: true
)
- ::Attachments::CreateService
- .new(container, author: user)
- .call(uploaded_file: file, description: nil)
+ call = ::Attachments::CreateService
+ .new(user: user)
+ .call(container: container, filename: attachment.filename, file: file)
+
+ call.on_failure do
+ log "Failed to add attachment #{attachment.filename} for [#{sender_email}]: #{call.message}"
+ end
+
+ call.result
end
# Adds To and Cc as watchers of the given object if the sender has the
diff --git a/app/models/permitted_params.rb b/app/models/permitted_params.rb
index caf3fcf9275..0adf15b41b9 100644
--- a/app/models/permitted_params.rb
+++ b/app/models/permitted_params.rb
@@ -252,6 +252,10 @@ class PermittedParams
params.require(:content).permit(*self.class.permitted_attributes[:wiki_content])
end
+ def wiki_page_with_content
+ wiki_page.merge(wiki_content)
+ end
+
def pref
params.fetch(:pref, {}).permit(:hide_mail, :time_zone, :theme,
:comments_sorting, :warn_on_leaving_unsaved,
diff --git a/app/services/attachments/build_service.rb b/app/services/attachments/build_service.rb
new file mode 100644
index 00000000000..9a725f571bf
--- /dev/null
+++ b/app/services/attachments/build_service.rb
@@ -0,0 +1,51 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Attachments
+ class BuildService < ::BaseServices::Create
+ private
+
+ def persist(service_result)
+ attachment = service_result.result
+ add_to_association(attachment)
+
+ unless attachment.valid?
+ service_result.errors = attachment.errors
+ service_result.success = false
+ end
+
+ service_result
+ end
+
+ def add_to_association(attachment)
+ return unless attachment.container
+
+ attachment.container.association(:attachments).add_to_target(attachment)
+ end
+ end
+end
diff --git a/app/services/attachments/create_service.rb b/app/services/attachments/create_service.rb
index 0671dc65a22..850f6c13e0e 100644
--- a/app/services/attachments/create_service.rb
+++ b/app/services/attachments/create_service.rb
@@ -26,78 +26,74 @@
# See docs/COPYRIGHT.rdoc for more details.
#++
-class Attachments::CreateService
+class Attachments::CreateService < ::BaseServices::Create
include Attachments::TouchContainer
- attr_reader :container, :author
-
- def initialize(container, author:)
- @container = container
- @author = author
- end
+ around_call :error_wrapped_call
##
- # Adds and saves the uploaded file as attachment of the given container.
- # In case the container supports it, a journal will be written.
+ # Create an attachment service bypassing the user-provided whitelist
+ # for internal purposes such as exporting data.
+ #
+ # @param user The user to call the service with
+ # @param whitelist A custom whitelist to validate with, or empty to disable validation
#
- # An ActiveRecord::RecordInvalid error is raised if any record can't be saved.
- def call(uploaded_file:, description:)
- create_attachment(uploaded_file, description)
- .tap(&method(:created_event))
+ # Warning: When passing an empty whitelist, this results in no validations on the content type taking place.
+ def self.bypass_whitelist(user:, whitelist: [])
+ new(user: user, contract_options: { whitelist: whitelist.map(&:to_s) })
end
- private
-
- def create_attachment(uploaded_file, description)
- if container.nil?
- save_attachment(uploaded_file, description)
- elsif container.class.journaled?
- create_journalized(uploaded_file, description)
+ def persist(call)
+ attachment = call.result
+ if attachment.container
+ in_container_mutex(attachment.container) { super }
else
- create_unjournalized(uploaded_file, description)
+ super
end
end
- def create_journalized(uploaded_file, description)
+ def in_container_mutex(container)
OpenProject::Mutex.with_advisory_lock_transaction(container) do
- save_attachment(uploaded_file, description).tap do
+ yield.tap do
# Get the latest attachments to ensure having them all for journalization.
# We just created an attachment and a different worker might have added attachments
# in the meantime, e.g when bulk uploading.
container.attachments.reload
-
- touch(container)
end
end
end
- def create_unjournalized(uploaded_file, description)
- save_attachment(uploaded_file, description).tap do
- touch(container)
- end
- end
+ def after_perform(call)
+ attachment = call.result
+ container = attachment.container
- def save_attachment(uploaded_file, description)
- attachment = Attachment.new(file: uploaded_file,
- container: container,
- description: description,
- author: author)
+ touch(container) unless container.nil?
- attachment.save!
- attachment
- end
-
- def build_attachment(uploaded_file, description)
- container.attachments.build(file: uploaded_file,
- description: description,
- content_type: uploaded_file.content_type,
- author: author)
- end
-
- def created_event(attachment)
OpenProject::Notifications.send(
OpenProject::Events::ATTACHMENT_CREATED,
attachment: attachment
)
+
+ call
+ end
+
+ def error_wrapped_call
+ yield
+ rescue StandardError => e
+ log_attachment_saving_error(e)
+
+ message =
+ if e&.class&.to_s == 'Errno::EACCES'
+ I18n.t('api_v3.errors.unable_to_create_attachment_permissions')
+ else
+ I18n.t('api_v3.errors.unable_to_create_attachment')
+ end
+ raise message
+ end
+
+ def log_attachment_saving_error(error)
+ message = "Failed to save attachment: #{error&.class} - #{error&.message || 'Unknown error'}"
+
+ OpenProject.logger.error message
end
end
diff --git a/app/services/attachments/prepare_upload_service.rb b/app/services/attachments/prepare_upload_service.rb
new file mode 100644
index 00000000000..abc1a55c5b6
--- /dev/null
+++ b/app/services/attachments/prepare_upload_service.rb
@@ -0,0 +1,48 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Attachments
+ class PrepareUploadService < ::BaseServices::Create
+ def persist(call)
+ attachment = call.result
+
+ if attachment.save
+ attachment.reload # necessary so that the fog file uploader path is correct
+ ServiceResult.new success: true, result: attachment
+ else
+ ServiceResult.new success: false, result: attachment
+ end
+ end
+
+ private
+
+ def attributes_service_class
+ SetPreparedAttributesService
+ end
+ end
+end
diff --git a/app/services/attachments/set_attributes_service.rb b/app/services/attachments/set_attributes_service.rb
new file mode 100644
index 00000000000..3f7e5c5b522
--- /dev/null
+++ b/app/services/attachments/set_attributes_service.rb
@@ -0,0 +1,43 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Attachments
+ class SetAttributesService < ::BaseServices::SetAttributes
+ def set_attributes(params)
+ # Don't set the content type manually,
+ # we always want to infer it
+ super params.except :content_type
+ end
+
+ def set_default_attributes(params)
+ model.author = user if model.author.nil?
+ end
+ end
+end
diff --git a/app/services/attachments/set_prepared_attributes_service.rb b/app/services/attachments/set_prepared_attributes_service.rb
new file mode 100644
index 00000000000..f46d99334cc
--- /dev/null
+++ b/app/services/attachments/set_prepared_attributes_service.rb
@@ -0,0 +1,66 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Attachments
+ class SetPreparedAttributesService < SetAttributesService
+ private
+
+ def set_attributes(params)
+ super
+
+ set_prepared_attributes params
+ end
+
+ def set_prepared_attributes(params)
+ # We need to do it like this because `file` is an uploader which expects a File (not a string)
+ # to upload usually. But in this case the data has already been uploaded and we just point to it.
+ model[:file] = pending_direct_upload_filename(params[:filename])
+
+ # Explicitly set the filesize from metadata
+ # as the provided file is not actually uploaded
+ model.filesize = params[:filesize]
+
+ model.extend(OpenProject::ChangedBySystem)
+ model.change_by_system do
+ model.downloads = -1
+ # Set a content type as the file is not present
+ # The real content type will be set by FinishDirectUploadJob
+ model.content_type = params[:content_type] || OpenProject::ContentTypeDetector::SENSIBLE_DEFAULT
+ end
+ end
+
+ # The name has to be in the same format as what Carrierwave will produce later on. If they are different,
+ # Carrierwave will alter the name (both local and remote) whenever the attachment is saved with the remote
+ # file loaded.
+ def pending_direct_upload_filename(filename)
+ CarrierWave::SanitizedFile.new(nil).send(:sanitize, filename)
+ end
+ end
+end
diff --git a/app/services/base_services/base_contracted.rb b/app/services/base_services/base_contracted.rb
index a2d688a2ced..25dbc8bf12a 100644
--- a/app/services/base_services/base_contracted.rb
+++ b/app/services/base_services/base_contracted.rb
@@ -92,6 +92,7 @@ module BaseServices
# nothing for now but subclasses can override
call
end
+
alias_method :after_save, :after_perform
def persist(call)
diff --git a/app/services/wiki_pages/create_service.rb b/app/services/wiki_pages/create_service.rb
index 6c138267d6e..8fd4e802d5b 100644
--- a/app/services/wiki_pages/create_service.rb
+++ b/app/services/wiki_pages/create_service.rb
@@ -29,4 +29,5 @@
#++
class WikiPages::CreateService < ::BaseServices::Create
+ include Attachments::ReplaceAttachments
end
diff --git a/app/services/wiki_pages/set_attributes_service.rb b/app/services/wiki_pages/set_attributes_service.rb
index c3b89e7c115..64fd698d346 100644
--- a/app/services/wiki_pages/set_attributes_service.rb
+++ b/app/services/wiki_pages/set_attributes_service.rb
@@ -36,6 +36,8 @@
#
# Attributes for both the page as well as for the content are accepted.
class WikiPages::SetAttributesService < ::BaseServices::SetAttributes
+ include Attachments::SetReplacements
+
private
def set_attributes(params)
@@ -53,7 +55,7 @@ class WikiPages::SetAttributesService < ::BaseServices::SetAttributes
end
def set_default_attributes(_params)
- model.build_content
+ model.build_content page: model
model.content.extend(OpenProject::ChangedBySystem)
model.content.change_by_system do
@@ -66,6 +68,10 @@ class WikiPages::SetAttributesService < ::BaseServices::SetAttributes
end
def split_page_and_content_params(params)
- params.partition { |p, _| WikiContent.column_names.include?(p) }.map(&:to_h)
+ params.partition { |p, _| content_attribute?(p) }.map(&:to_h)
+ end
+
+ def content_attribute?(name)
+ WikiContent.column_names.include?(name) || name.to_s == 'comments'
end
end
diff --git a/app/services/wiki_pages/update_service.rb b/app/services/wiki_pages/update_service.rb
new file mode 100644
index 00000000000..c76009f09ad
--- /dev/null
+++ b/app/services/wiki_pages/update_service.rb
@@ -0,0 +1,50 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+class WikiPages::UpdateService < ::BaseServices::Update
+ include Attachments::ReplaceAttachments
+
+ private
+
+ def persist(service_result)
+ service_result = super(service_result)
+
+ page = service_result.result
+ content = page.content
+
+ unless page.save && content.save
+ service_result.errors = page.errors
+ service_result.errors.merge! content.errors
+ service_result.success = false
+ end
+
+ service_result
+ end
+end
diff --git a/app/views/admin/settings/attachments_settings/show.html.erb b/app/views/admin/settings/attachments_settings/show.html.erb
new file mode 100644
index 00000000000..f31ac9d4994
--- /dev/null
+++ b/app/views/admin/settings/attachments_settings/show.html.erb
@@ -0,0 +1,48 @@
+<%#-- copyright
+OpenProject is an open source project management software.
+Copyright (C) 2012-2021 the OpenProject GmbH
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License version 3.
+
+OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+Copyright (C) 2006-2013 Jean-Philippe Lang
+Copyright (C) 2010-2013 the ChiliProject Team
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+See docs/COPYRIGHT.rdoc for more details.
+
+++#%>
+<%= toolbar title: t(:'attributes.attachments') %>
+
+<%= styled_form_tag(admin_settings_update_attachments_path, method: :patch) do %>
+ <section class="form--section">
+ <div class="form--field">
+ <%= setting_text_field :attachment_max_size, size: 6, unit: t(:"number.human.storage_units.units.kb"), container_class: '-slim' %>
+ </div>
+ <div class="form--field">
+ <%= setting_text_area :attachment_whitelist, rows: 5, container_class: '-wide' %>
+ <div class="form--field-instructions">
+ <%= t('settings.attachments.whitelist_text_html',
+ ext_example: '*.jpg',
+ mime_example: 'image/jpeg',
+ ) %>
+ </div>
+ </div>
+ </section>
+
+ <%= styled_button_tag t(:button_save), class: '-highlight -with-icon icon-checkmark' %>
+<% end %>
diff --git a/app/views/admin/settings/general_settings/show.html.erb b/app/views/admin/settings/general_settings/show.html.erb
index 22fbf8d682c..2ab2f7c1e51 100644
--- a/app/views/admin/settings/general_settings/show.html.erb
+++ b/app/views/admin/settings/general_settings/show.html.erb
@@ -31,9 +31,6 @@ See docs/COPYRIGHT.rdoc for more details.
<%= styled_form_tag(admin_settings_update_general_path, method: :patch) do %>
<section class="form--section">
<div class="form--field"><%= setting_text_field :app_title, size: 30, container_class: '-middle' %></div>
- <div class="form--field">
- <%= setting_text_field :attachment_max_size, size: 6, unit: t(:"number.human.storage_units.units.kb"), container_class: '-slim' %>
- </div>
<div class="form--field">
<%= setting_text_field :per_page_options, size: 20, container_class: '-slim' %>
<span class="form--field-instructions">
diff --git a/app/views/wiki/_page_form.html.erb b/app/views/wiki/_page_form.html.erb
index 41b39cd47b6..d5f8c8c369d 100644
--- a/app/views/wiki/_page_form.html.erb
+++ b/app/views/wiki/_page_form.html.erb
@@ -1,4 +1,4 @@
-<%= error_messages_for 'page' %>
+<%= error_messages_for_contract @page, @errors %>
<% resource = ::API::V3::WikiPages::WikiPageRepresenter.new(@page, current_user: current_user, embed_links: true) %>
diff --git a/app/workers/attachments/finish_direct_upload_job.rb b/app/workers/attachments/finish_direct_upload_job.rb
index f1893f00e5a..0b319208d16 100644
--- a/app/workers/attachments/finish_direct_upload_job.rb
+++ b/app/workers/attachments/finish_direct_upload_job.rb
@@ -55,9 +55,9 @@ class Attachments::FinishDirectUploadJob < ApplicationJob
def set_attributes_from_file(attachment, local_file)
attachment.downloads = 0
- attachment.set_file_size local_file unless attachment.filesize && attachment.filesize > 0
- attachment.set_content_type local_file unless attachment.content_type.present?
- attachment.set_digest local_file unless attachment.digest.present?
+ attachment.set_file_size local_file
+ attachment.set_content_type local_file
+ attachment.set_digest local_file
end
def save_attachment(attachment)
diff --git a/app/workers/backup_job.rb b/app/workers/backup_job.rb
index b5e76b448ba..9d951833398 100644
--- a/app/workers/backup_job.rb
+++ b/app/workers/backup_job.rb
@@ -120,17 +120,24 @@ class BackupJob < ::ApplicationJob
def store_backup(file_name, backup:, user:)
File.open(file_name) do |file|
- attachment = Attachments::CreateService
- .new(backup, author: user)
- .call(uploaded_file: file, description: 'OpenProject backup')
-
- download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(attachment.id)
+ call = Attachments::CreateService
+ .bypass_whitelist(user: user)
+ .call(container: backup, filename: file_name, file: file, description: 'OpenProject backup')
+
+ call.on_success do
+ download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(call.result.id)
+
+ upsert_status(
+ status: :success,
+ message: I18n.t('export.succeeded'),
+ payload: download_payload(download_url)
+ )
+ end
- upsert_status(
- status: :success,
- message: I18n.t('export.succeeded'),
- payload: download_payload(download_url)
- )
+ call.on_failure do
+ upsert_status status: :failure,
+ message: I18n.t('export.failed', message: call.message)
+ end
end
end
diff --git a/app/workers/extract_fulltext_job.rb b/app/workers/extract_fulltext_job.rb
index 7fbbb7f0932..975cac15bf9 100644
--- a/app/workers/extract_fulltext_job.rb
+++ b/app/workers/extract_fulltext_job.rb
@@ -81,7 +81,7 @@ class ExtractFulltextJob < ApplicationJob
end
def find_attachment(id)
- Attachment.find_by_id id
+ Attachment.find_by(id: id)
end
def remote_file?
diff --git a/app/workers/work_packages/exports/export_job.rb b/app/workers/work_packages/exports/export_job.rb
index f98f10ef079..ea09c48680d 100644
--- a/app/workers/work_packages/exports/export_job.rb
+++ b/app/workers/work_packages/exports/export_job.rb
@@ -88,16 +88,23 @@ module WorkPackages
end
end
- def store_attachment(storage, file)
- attachment = Attachments::CreateService
- .new(storage, author: User.current)
- .call(uploaded_file: file, description: '')
+ def store_attachment(container, file)
+ call = Attachments::CreateService
+ .bypass_whitelist(user: User.current)
+ .call(container: container, file: file, filename: File.basename(file), description: '')
- download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(attachment.id)
+ call.on_success do
+ download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(call.result.id)
- upsert_status status: :success,
- message: I18n.t('export.succeeded'),
- payload: download_payload(download_url)
+ upsert_status status: :success,
+ message: I18n.t('export.succeeded'),
+ payload: download_payload(download_url)
+ end
+
+ call.on_failure do
+ upsert_status status: :failure,
+ message: I18n.t('export.failed', message: call.message)
+ end
end
end
end
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 12013d038f4..3fe202a7d98 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -613,6 +613,7 @@ en:
invalid_url: 'is not a valid URL.'
invalid_url_scheme: 'is not a supported protocol (allowed: %{allowed_schemes}).'
less_than_or_equal_to: "must be less than or equal to %{count}."
+ not_available: "is not available due to a system configuration."
not_deletable: "cannot be deleted."
not_current_user: "is not the current user."
not_a_date: "is not a valid date."
@@ -632,6 +633,10 @@ en:
unremovable: "cannot be removed."
wrong_length: "is the wrong length (should be %{count} characters)."
models:
+ attachment:
+ attributes:
+ content_type:
+ not_whitelisted: "is set to '%{value}', which is not whitelisted for uploading."
capability:
context:
global: 'Global'
@@ -1271,6 +1276,7 @@ en:
export:
your_work_packages_export: "Your work packages export"
succeeded: "The export has completed successfully."
+ failed: "The export has failed: %{message}"
format:
atom: "Atom"
csv: "CSV"
@@ -2351,6 +2357,7 @@ en:
setting_apiv3_docs_enabled_instructions_html: >
If the docs page is enabled you can get an interactive view of the APIv3 documentation under
<a href="%{link}" target="_blank">%{link}</a>.
+ setting_attachment_whitelist: "Attachment upload whitelist"
setting_email_delivery_method: "Email delivery method"
setting_sendmail_location: "Location of the sendmail executable"
setting_smtp_enable_starttls_auto: "Automatically use STARTTLS if available"
@@ -2467,6 +2474,14 @@ en:
passwords: "Passwords"
session: "Session"
brute_force_prevention: "Automated user blocking"
+ attachments:
+ whitelist_text_html: >
+ Define a list of valid file extensions and/or mime types for uploaded files.
+ <br/>
+ Enter file extensions (e.g., <code>%{ext_example}</code>) or mime types (e.g., <code>%{mime_example}</code>).
+ <br/>
+ Leave empty to allow any file type to be uploaded.
+ Multiple values allowed (one line for each value).
notifications:
retention_text: >
Set the number of days notification events for users (the source for in-app notifications)
diff --git a/config/settings.yml b/config/settings.yml
index 462ba83b956..d4394789621 100644
--- a/config/settings.yml
+++ b/config/settings.yml
@@ -388,3 +388,6 @@ notification_retention_period_days:
notification_email_delay_minutes:
default: 15
format: int
+attachment_whitelist:
+ serialized: true
+ default: []
diff --git a/lib/api/utilities/endpoints/bodied.rb b/lib/api/utilities/endpoints/bodied.rb
index c5e2ca2697c..6e207559ea3 100644
--- a/lib/api/utilities/endpoints/bodied.rb
+++ b/lib/api/utilities/endpoints/bodied.rb
@@ -46,11 +46,19 @@ module API
end
end
+ def default_params_source
+ ->(request) do
+ request.request_body
+ end
+ end
+
def initialize(model:,
api_name: model.name.demodulize,
instance_generator: default_instance_generator(model),
params_modifier: default_params_modifier,
+ params_source: default_params_source,
process_state: default_process_state,
+ before_hook: nil,
parse_representer: nil,
render_representer: nil,
process_service: nil,
@@ -60,18 +68,21 @@ module API
self.api_name = api_name
self.instance_generator = instance_generator
self.params_modifier = params_modifier
+ self.params_source = params_source
self.process_state = process_state
self.parse_representer = parse_representer || deduce_parse_representer
self.render_representer = render_representer || deduce_render_representer
self.process_contract = process_contract || deduce_process_contract
self.process_service = process_service || deduce_process_service
self.parse_service = parse_service || deduce_parse_service
+ self.before_hook = before_hook
end
def mount
update = self
-> do
+ update.before_hook&.(request: self)
params = update.parse(self)
call = update.process(self, params)
@@ -86,7 +97,7 @@ module API
.new(request.current_user,
model: model,
representer: parse_representer)
- .call(request.request_body)
+ .call(params_source.call(request))
.result
end
@@ -121,11 +132,13 @@ module API
:instance_generator,
:parse_representer,
:render_representer,
+ :params_source,
:params_modifier,
:process_contract,
:process_service,
:parse_service,
- :process_state
+ :process_state,
+ :before_hook
private
diff --git a/lib/api/v3/attachments/attachment_parsing_representer.rb b/lib/api/v3/attachments/attachment_parsing_representer.rb
new file mode 100644
index 00000000000..563d496ce0d
--- /dev/null
+++ b/lib/api/v3/attachments/attachment_parsing_representer.rb
@@ -0,0 +1,71 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'roar/decorator'
+require 'roar/json/hal'
+
+module API
+ module V3
+ module Attachments
+ class AttachmentParsingRepresenter < ::API::Decorators::Single
+ nested :metadata do
+ property :filename,
+ as: :fileName
+
+ property :description,
+ getter: ->(*) {
+ ::API::Decorators::Formattable.new(description, plain: true)
+ },
+ setter: ->(fragment:, **) { self.description = fragment['raw'] },
+ render_nil: true
+
+ property :content_type,
+ as: :contentType,
+ render_nil: false
+
+ property :filesize,
+ as: :fileSize,
+ render_nil: false
+
+ property :digest,
+ render_nil: false
+ end
+
+ property :file,
+ setter: ->(fragment:, represented:, doc:, **) {
+ filename = represented.filename || doc.dig('metadata', 'fileName')
+ self.file = OpenProject::Files.build_uploaded_file fragment[:tempfile],
+ fragment[:type],
+ file_name: filename
+ }
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/attachments/attachment_upload_representer.rb b/lib/api/v3/attachments/attachment_upload_representer.rb
index 3cbe0742d7e..01bdf1e0655 100644
--- a/lib/api/v3/attachments/attachment_upload_representer.rb
+++ b/lib/api/v3/attachments/attachment_upload_representer.rb
@@ -69,7 +69,7 @@ module API
attr_reader :form_url, :form_fields, :attachment
- def initialize(attachment, current_user:)
+ def initialize(attachment, current_user:, embed_links: false)
super
fog_hash = DirectFogUploader.direct_fog_hash attachment: attachment
diff --git a/lib/api/v3/attachments/attachments_api.rb b/lib/api/v3/attachments/attachments_api.rb
index e4cb927667b..f2a1bc8eb8f 100644
--- a/lib/api/v3/attachments/attachments_api.rb
+++ b/lib/api/v3/attachments/attachments_api.rb
@@ -39,25 +39,12 @@ module API
def container
nil
end
-
- def check_attachments_addable
- raise API::Errors::Unauthorized if Redmine::Acts::Attachable.attachables.none?(&:attachments_addable?)
- end
end
- post do
- check_attachments_addable
-
- ::API::V3::Attachments::AttachmentRepresenter.new(parse_and_create, current_user: current_user)
- end
+ post &API::V3::Attachments::AttachmentsByContainerAPI.create
namespace :prepare do
- post do
- require_direct_uploads
- check_attachments_addable
-
- ::API::V3::Attachments::AttachmentUploadRepresenter.new(parse_and_prepare, current_user: current_user)
- end
+ post &API::V3::Attachments::AttachmentsByContainerAPI.prepare
end
route_param :id, type: Integer, desc: 'Attachment ID' do
diff --git a/lib/api/v3/attachments/attachments_by_container_api.rb b/lib/api/v3/attachments/attachments_by_container_api.rb
index 745096e05ff..bb506529d96 100644
--- a/lib/api/v3/attachments/attachments_by_container_api.rb
+++ b/lib/api/v3/attachments/attachments_by_container_api.rb
@@ -47,114 +47,20 @@ module API
request.env['REQUEST_METHOD'] == 'POST'
end
- def parse_metadata(json)
- return nil unless json
-
- metadata = OpenStruct.new
- ::API::V3::Attachments::AttachmentMetadataRepresenter.new(metadata).from_json(json)
-
- unless metadata.file_name
- raise ::API::Errors::Validation.new(
- :file_name,
- "fileName #{I18n.t('activerecord.errors.messages.blank')}"
- )
- end
-
- metadata
+ ##
+ # Additionally to what would be checked by the contract,
+ # we need to restrict permissions in some use cases of the mounts of this endpoint.
+ def restrict_permissions(permissions)
+ authorize_any(permissions, projects: container.project) unless permissions.empty?
end
+ end
- def parse_and_prepare
- metadata = parse_metadata params[:metadata]
-
- unless metadata
- raise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.multipart_body_error'))
- end
-
- unless metadata.file_size
- raise ::API::Errors::Validation.new(
- :file_size,
- "fileSize #{I18n.t('activerecord.errors.messages.blank')}"
- )
- end
-
- with_handled_create_errors do
- create_attachment metadata
- end
- end
-
- def create_attachment(metadata)
- Attachment.create_pending_direct_upload(
- file_name: metadata.file_name,
- container: container,
- author: current_user,
- content_type: metadata.content_type,
- file_size: metadata.file_size
- )
- end
-
- def parse_and_create
- metadata = parse_metadata params[:metadata]
- file = params[:file]
-
- unless metadata && file
- raise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.multipart_body_error'))
- end
-
- build_and_attach(metadata, file)
- end
-
- def build_and_attach(metadata, file)
- uploaded_file = OpenProject::Files.build_uploaded_file file[:tempfile],
- file[:type],
- file_name: metadata.file_name.to_s
-
- service = ::Attachments::CreateService.new(container, author: current_user)
-
- with_handled_create_errors do
- service.call uploaded_file: uploaded_file,
- description: metadata.description
- end
- end
-
- def check_permissions(permissions)
- if permissions.empty?
- raise API::Errors::Unauthorized unless container.attachments_addable?(current_user)
- else
- authorize_any(permissions, projects: container.project)
- end
- end
-
- def require_direct_uploads
- unless OpenProject::Configuration.direct_uploads?
- raise API::Errors::NotFound, message: "Only available if direct uploads are enabled."
- end
- end
-
- def with_handled_create_errors
- yield
- rescue ActiveRecord::RecordInvalid => e
- raise ::API::Errors::ErrorBase.create_and_merge_errors(e.record.errors)
- rescue StandardError => e
- log_attachment_saving_error(e)
- message =
- if e&.class&.to_s == 'Errno::EACCES'
- I18n.t('api_v3.errors.unable_to_create_attachment_permissions')
- else
- I18n.t('api_v3.errors.unable_to_create_attachment')
- end
- raise ::API::Errors::InternalError.new(message)
- end
-
- def log_attachment_saving_error(error)
- container_message = if container
- "on #{container.class} with ID #{container.id}"
- else
- "without container"
- end
- message = "Failed to save attachment #{container_message}: #{error&.class} - #{error&.message || 'Unknown error'}"
-
- Rails.logger.error message
+ def self.parse_multipart(request)
+ request.params.tap do |params|
+ params[:metadata] = JSON.parse(params[:metadata]) if params.key?(:metadata)
end
+ rescue JSON::ParserError
+ raise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.invalid_json'))
end
def self.read
@@ -167,21 +73,30 @@ module API
end
def self.create(permissions = [])
- -> do
- check_permissions permissions
-
- ::API::V3::Attachments::AttachmentRepresenter.new(parse_and_create,
- current_user: current_user)
- end
+ ::API::V3::Utilities::Endpoints::Create
+ .new(model: ::Attachment,
+ parse_representer: AttachmentParsingRepresenter,
+ params_source: method(:parse_multipart),
+ before_hook: ->(request:) { request.restrict_permissions(permissions) },
+ params_modifier: ->(params) do
+ params.merge(container: container)
+ end)
+ .mount
end
def self.prepare(permissions = [])
- -> do
- require_direct_uploads
- check_permissions permissions
-
- ::API::V3::Attachments::AttachmentUploadRepresenter.new(parse_and_prepare, current_user: current_user)
- end
+ ::API::V3::Utilities::Endpoints::Create
+ .new(model: ::Attachment,
+ parse_representer: AttachmentParsingRepresenter,
+ render_representer: AttachmentUploadRepresenter,
+ process_service: ::Attachments::PrepareUploadService,
+ process_contract: ::Attachments::PrepareUploadContract,
+ params_source: method(:parse_multipart),
+ before_hook: ->(request:) { request.restrict_permissions(permissions) },
+ params_modifier: ->(params) do
+ params.merge(container: container)
+ end)
+ .mount
end
end
end
diff --git a/lib/open_project/content_type_detector.rb b/lib/open_project/content_type_detector.rb
index b4f164bff00..c8146a0ce73 100644
--- a/lib/open_project/content_type_detector.rb
+++ b/lib/open_project/content_type_detector.rb
@@ -91,15 +91,15 @@ module OpenProject
# Returns a String describing the file's content type
def detect
- type = if blank_name?
- SENSIBLE_DEFAULT
- elsif empty_file?
- EMPTY_TYPE
- elsif calculated_type_matches.any?
- calculated_type_matches.first
- else
- type_from_file_command || SENSIBLE_DEFAULT
- end.to_s
+ if blank_name?
+ SENSIBLE_DEFAULT
+ elsif empty_file?
+ EMPTY_TYPE
+ elsif calculated_type_matches.any?
+ calculated_type_matches.first
+ else
+ type_from_file_command || SENSIBLE_DEFAULT
+ end.to_s
end
private
diff --git a/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb b/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb
index a251638085e..d1243713c11 100644
--- a/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb
+++ b/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb
@@ -54,8 +54,6 @@ module Redmine
:attachments_claimed
send :include, Redmine::Acts::Attachable::InstanceMethods
-
- OpenProject::Deprecation.deprecate_method self, :attach_files
end
private
@@ -174,26 +172,6 @@ module Redmine
(persisted? && allowed_to_on_attachment?(user, self.class.attachable_options[:add_on_persisted_permission]))
end
- # Bulk attaches a set of files to an object
- # @deprecated
- # Either use the already existing Attachments::CreateService or
- # write/extend Services for the attached to object.
- # The service should rely on the attachments_replacements variable.
- # See:
- # * app/services/attachments/set_replacements.rb
- # * app/services/attachments/replace_attachments.rb
- def attach_files(attachments)
- return unless attachments&.is_a?(Hash)
-
- attachments.each_value do |attachment|
- if attachment['file']
- build_attachments_from_hash(attachment)
- elsif attachment['id']
- memoize_attachment_for_claiming(attachment)
- end
- end
- end
-
private
def allowed_to_on_attachment?(user, permissions)
@@ -222,21 +200,6 @@ module Redmine
(Redmine::Acts::Attachable.attachables & self.class.ancestors).first
end
- def build_attachments_from_hash(attachment_hash)
- if (file = attachment_hash['file']) && file && file.size.positive?
- attachments.build(file: file,
- container: self,
- description: attachment_hash['description'].to_s.strip,
- author: User.current)
- end
- end
-
- def memoize_attachment_for_claiming(attachment_hash)
- self.attachments_claimed ||= []
- attachment = Attachment.find(attachment_hash['id'])
- self.attachments_claimed << attachment unless id && attachment.container_id == id
- end
-
def validate_attachments_claimable
return unless claimed_attachments?
diff --git a/modules/avatars/lib/open_project/avatars/patches/user_patch.rb b/modules/avatars/lib/open_project/avatars/patches/user_patch.rb
index f675d5874cb..4b5d96b30e8 100644
--- a/modules/avatars/lib/open_project/avatars/patches/user_patch.rb
+++ b/modules/avatars/lib/open_project/avatars/patches/user_patch.rb
@@ -60,8 +60,12 @@ module OpenProject::Avatars
local_avatar_attachment&.destroy
reset_avatar_attachment_cache!
- attach_files('first' => { 'file' => file, 'description' => 'avatar' })
- save
+ @local_avatar_attachment = Attachments::CreateService
+ .new(user: User.system, contract_class: EmptyContract)
+ .call(file: file, container: self, filename: file.original_filename, description: 'avatar')
+ .result
+
+ touch
end
def reset_avatar_attachment_cache!
diff --git a/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rb b/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rb
index 6f568b08231..7edea108901 100644
--- a/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rb
+++ b/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rb
@@ -84,6 +84,7 @@ module Bim::Bcf
attribute :uuid
attribute :issue
+ attribute :snapshot
attribute :json_viewpoint do
validate_json_viewpoint_present
validate_json_viewpoint_hash
diff --git a/modules/bim/app/contracts/bim/ifc_models/base_contract.rb b/modules/bim/app/contracts/bim/ifc_models/base_contract.rb
index d98bf621ef7..2dfbf4dabdc 100644
--- a/modules/bim/app/contracts/bim/ifc_models/base_contract.rb
+++ b/modules/bim/app/contracts/bim/ifc_models/base_contract.rb
@@ -42,7 +42,6 @@ module Bim
end
validate :user_allowed_to_manage
- validate :user_is_uploader
validate :ifc_attachment_existent
validate :ifc_attachment_is_ifc
validate :uploader_is_ifc_attachment_author
@@ -53,12 +52,6 @@ module Bim
end
end
- def user_is_uploader
- if model.uploader_id_changed? && model.uploader != user
- errors.add :uploader_id, :invalid
- end
- end
-
def ifc_attachment_existent
errors.add :base, :ifc_attachment_missing unless model.ifc_attachment
end
diff --git a/modules/bim/app/controllers/bim/bcf/issues_controller.rb b/modules/bim/app/controllers/bim/bcf/issues_controller.rb
index d8bedcce891..3d3269dd641 100644
--- a/modules/bim/app/controllers/bim/bcf/issues_controller.rb
+++ b/modules/bim/app/controllers/bim/bcf/issues_controller.rb
@@ -213,9 +213,16 @@ module Bim
end
def create_attachment
- Attachments::CreateService
- .new(nil, author: current_user)
- .call(uploaded_file: params[:bcf_file], description: params[:bcf_file].original_filename)
+ filename = params[:bcf_file].original_filename
+ call = Attachments::CreateService
+ .bypass_whitelist(user: current_user, whitelist: %w[application/zip])
+ .call(file: params[:bcf_file],
+ filename: filename,
+ description: filename)
+
+ call.on_failure { raise e.message }
+
+ call.result
end
def check_file_param
diff --git a/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rb b/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rb
index 511d9f4cacb..337228412f9 100644
--- a/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rb
+++ b/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rb
@@ -176,14 +176,20 @@ module Bim
private
def prepare_form(ifc_model)
- if OpenProject::Configuration.direct_uploads?
- @pending_upload = Attachment.create_pending_direct_upload(file_name: "model.ifc", author: current_user)
- @form = DirectFogUploader.direct_fog_hash(
- attachment: @pending_upload,
- success_action_redirect: direct_upload_finished_bcf_project_ifc_models_url
- )
- session[:pending_ifc_model_ifc_model_id] = ifc_model.id unless ifc_model.new_record?
- end
+ return unless OpenProject::Configuration.direct_uploads?
+
+ call = ::Attachments::PrepareUploadService
+ .new(user: current_user)
+ .call(filename: "model.ifc", filesize: 0)
+
+ call.on_failure { flash[:error] = call.message }
+
+ @pending_upload = call.result
+ @form = DirectFogUploader.direct_fog_hash(
+ attachment: @pending_upload,
+ success_action_redirect: direct_upload_finished_bcf_project_ifc_models_url
+ )
+ session[:pending_ifc_model_ifc_model_id] = ifc_model.id unless ifc_model.new_record?
end
def frontend_redirect(model_ids)
diff --git a/modules/bim/app/models/bim/bcf/viewpoint.rb b/modules/bim/app/models/bim/bcf/viewpoint.rb
index bd8e770064a..c9dfdd74d9e 100644
--- a/modules/bim/app/models/bim/bcf/viewpoint.rb
+++ b/modules/bim/app/models/bim/bcf/viewpoint.rb
@@ -37,7 +37,14 @@ module Bim::Bcf
def snapshot=(file)
snapshot&.destroy
- attach_files('first' => { 'file' => file, 'description' => 'snapshot' })
+ build_snapshot file
+ end
+
+ def build_snapshot(file, user: User.current)
+ ::Attachments::BuildService
+ .new(user: user)
+ .call(file: file, container: self, filename: file.original_filename, description: 'snapshot')
+ .result
end
end
end
diff --git a/modules/bim/app/models/bim/ifc_models/ifc_model.rb b/modules/bim/app/models/bim/ifc_models/ifc_model.rb
index 1ae55c12cac..940acb76fe1 100644
--- a/modules/bim/app/models/bim/ifc_models/ifc_model.rb
+++ b/modules/bim/app/models/bim/ifc_models/ifc_model.rb
@@ -1,7 +1,9 @@
module Bim
module IfcModels
class IfcModel < ActiveRecord::Base
- acts_as_attachable delete_permission: :manage_ifc_models, view_permission: :view_ifc_models
+ acts_as_attachable delete_permission: :manage_ifc_models,
+ add_permission: :manage_ifc_models,
+ view_permission: :view_ifc_models
belongs_to :project
belongs_to :uploader, class_name: 'User', foreign_key: 'uploader_id'
@@ -23,7 +25,11 @@ module Bim
end
delete_attachment name
- attach_files('first' => { 'file' => file, 'description' => name })
+ call = ::Attachments::CreateService
+ .bypass_whitelist(user: User.current)
+ .call(file: file, container: self, filename: file.original_filename, description: name)
+
+ call.on_failure { Rails.logger.error "Failed to add #{name} attachment: #{call.message}" }
end
end
diff --git a/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rb b/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rb
index fd861246f6d..c9cce4c2ac9 100644
--- a/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rb
+++ b/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rb
@@ -44,8 +44,9 @@ module Bim::Bcf
def set_snapshot
return unless snapshot_data_complete? && snapshot_content_type
+ name = "snapshot.#{snapshot_extension}"
file = OpenProject::Files
- .create_uploaded_file(name: "snapshot.#{snapshot_extension}",
+ .create_uploaded_file(name: name,
content_type: snapshot_content_type,
content: snapshot_binary_contents,
binary: true)
@@ -54,7 +55,8 @@ module Bim::Bcf
# to update existing viewpoints as the snapshot method will
# delete any existing snapshot right away while the expectation
# on a SetAttributesService is to not perform persisted changes.
- model.snapshot = file
+ model.snapshot&.mark_for_destruction
+ model.build_snapshot file, user: user
end
def snapshot_data_complete?
diff --git a/modules/bim/app/services/bim/ifc_models/set_attributes_service.rb b/modules/bim/app/services/bim/ifc_models/set_attributes_service.rb
index 80661c043bb..b703ceee161 100644
--- a/modules/bim/app/services/bim/ifc_models/set_attributes_service.rb
+++ b/modules/bim/app/services/bim/ifc_models/set_attributes_service.rb
@@ -39,7 +39,7 @@ module Bim
super
model.change_by_system do
- model.uploader = model.ifc_attachment&.author if model.ifc_attachment&.new_record? || model.ifc_attachment&.pending_direct_upload?
+ model.uploader = model.ifc_attachment&.author
end
end
@@ -75,7 +75,9 @@ module Bim
model.attachments << ifc_attachment
else
- model.attach_files('first' => { 'file' => ifc_attachment, 'description' => 'ifc' })
+ ::Attachments::BuildService
+ .new(user: user)
+ .call(file: ifc_attachment, container: model, filename: ifc_attachment.original_filename, description: 'ifc')
end
end
end
diff --git a/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb b/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb
index de0e0c659e5..2c3b43f10bd 100644
--- a/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb
+++ b/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb
@@ -103,9 +103,7 @@ describe ::OpenProject::Bim::BcfXml::IssueWriter do
before do
allow(User).to receive(:current).and_return current_user
-
- bcf_issue.comments.first.journal.update_attribute('journable_id', work_package.id)
- FactoryBot.create(:work_package_journal, notes: "Some note created in OP.", journable_id: work_package.id)
+ bcf_issue.comments.first.journal.update_columns(journable_id: work_package.id, version: 2)
end
shared_examples_for "writes Topic" do
@@ -174,6 +172,9 @@ describe ::OpenProject::Bim::BcfXml::IssueWriter do
end
it 'creates BCF comments for comments that were created within OP.' do
+ work_package.journal_notes = 'Some note created in OP.'
+ work_package.save!
+
expect(subject.at('/Markup/Comment[2]/Comment').content).to eql("Some note created in OP.")
expect(Bim::Bcf::Comment.count).to eql(2)
end
@@ -182,7 +183,7 @@ describe ::OpenProject::Bim::BcfXml::IssueWriter do
uuid = bcf_issue.viewpoints.first.uuid
viewpoint_node = subject.at("/Markup/Viewpoints[@Guid='#{uuid}']")
expect(viewpoint_node.at('Viewpoint').content).to eql("#{uuid}.xml")
- expect(viewpoint_node.at('Snapshot').content).to eql("#{uuid}.jpg")
+ expect(viewpoint_node.at('Snapshot').content).to eql("#{uuid}.png")
end
end
diff --git a/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rb b/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rb
index 82936c81848..d16b8d0adf1 100644
--- a/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rb
+++ b/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rb
@@ -31,22 +31,8 @@
require 'spec_helper'
shared_examples_for 'ifc model contract' do
- let(:current_user) do
- FactoryBot.build_stubbed(:user) do |user|
- allow(user)
- .to receive(:allowed_to?) do |permission, permission_project|
- permissions.include?(permission) && model_project == permission_project
- end
- end
- end
- let(:other_user) do
- FactoryBot.build_stubbed(:user) do |user|
- allow(user)
- .to receive(:allowed_to?) do |permission, permission_project|
- permissions.include?(permission) && model_project == permission_project
- end
- end
- end
+ let(:current_user) { FactoryBot.build_stubbed(:user) }
+ let(:other_user) { FactoryBot.build_stubbed(:user) }
let(:model_project) { FactoryBot.build_stubbed(:project) }
let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment, author: model_user) }
let(:model_user) { current_user }
@@ -56,6 +42,16 @@ shared_examples_for 'ifc model contract' do
allow(ifc_model)
.to receive(:ifc_attachment)
.and_return(ifc_attachment)
+
+ allow(other_user)
+ .to receive(:allowed_to?) do |permission, permission_project|
+ permissions.include?(permission) && model_project == permission_project
+ end
+
+ allow(current_user)
+ .to receive(:allowed_to?) do |permission, permission_project|
+ permissions.include?(permission) && model_project == permission_project
+ end
end
def expect_valid(valid, symbols = {})
@@ -109,10 +105,10 @@ shared_examples_for 'ifc model contract' do
context 'if the new ifc file is no valid ifc file' do
let(:ifc_file) { FileHelpers.mock_uploaded_file name: "model.ifc", content_type: 'application/binary', binary: true }
let(:ifc_attachment) do
- User.execute_as current_user do
- ifc_model.attach_files('first' => { 'file' => ifc_file, 'description' => 'ifc' })
- ifc_model.attachments.last
- end
+ ::Attachments::BuildService
+ .new(user: current_user)
+ .call(file: ifc_file, filename: 'model.ifc')
+ .result
end
it 'is invalid' do
@@ -125,10 +121,10 @@ shared_examples_for 'ifc model contract' do
FileHelpers.mock_uploaded_file name: "model.ifc", content_type: 'application/binary', binary: true, content: "ISO-10303-21;"
end
let(:ifc_attachment) do
- User.execute_as current_user do
- ifc_model.attach_files('first' => { 'file' => ifc_file, 'description' => 'ifc' })
- ifc_model.attachments.last
- end
+ ::Attachments::BuildService
+ .new(user: current_user)
+ .call(file: ifc_file, filename: 'model.ifc')
+ .result
end
it_behaves_like 'is valid'
diff --git a/modules/bim/spec/contracts/ifc_models/update_contract_spec.rb b/modules/bim/spec/contracts/ifc_models/update_contract_spec.rb
index afa42d0ceda..84d71c019b5 100644
--- a/modules/bim/spec/contracts/ifc_models/update_contract_spec.rb
+++ b/modules/bim/spec/contracts/ifc_models/update_contract_spec.rb
@@ -42,13 +42,18 @@ describe Bim::IfcModels::UpdateContract do
project: model_project).tap do |model|
model.extend(OpenProject::ChangedBySystem)
- model.change_by_system do
+ if changed_by_system
+ changed_by_system do
+ model.uploader = uploader_user
+ end
+ else
model.uploader = uploader_user
end
end
end
let(:permissions) { %i(manage_ifc_models) }
let(:uploader_user) { model_user }
+ let(:changed_by_system) { false }
context 'if the uploader changes' do
let(:model_user) { FactoryBot.build_stubbed(:user) }
@@ -56,14 +61,20 @@ describe Bim::IfcModels::UpdateContract do
let(:current_user) { other_user }
let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment, author: other_user) }
- it_behaves_like 'is valid'
+ it 'is invalid as not writable' do
+ expect_valid(false, uploader_id: %i(error_readonly))
+ end
+ end
- context 'if the uploader is different from the current_user' do
- let(:current_user) { model_user }
+ context 'if the uploader changes' do
+ let(:model_user) { FactoryBot.build_stubbed(:user) }
+ let(:uploader_user) { other_user }
+ let(:current_user) { other_user }
+ let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment, author: other_user) }
+ let(:changed_by_system) { true }
- it 'is invalid' do
- expect_valid(false, uploader_id: %i(invalid))
- end
+ it 'is invalid as does not match' do
+ expect_valid(false, uploader_id: %i(invalid))
end
end
diff --git a/modules/bim/spec/controllers/issues_controller_spec.rb b/modules/bim/spec/controllers/issues_controller_spec.rb
index 08eb3e451af..6a24ad68048 100644
--- a/modules/bim/spec/controllers/issues_controller_spec.rb
+++ b/modules/bim/spec/controllers/issues_controller_spec.rb
@@ -103,7 +103,7 @@ describe ::Bim::Bcf::IssuesController, type: :controller do
let(:file) do
Rack::Test::UploadedFile.new(
File.join(Rails.root, "modules/bim/spec/fixtures/files/#{filename}"),
- 'application/octet-stream'
+ 'application/zip'
)
end
@@ -119,7 +119,7 @@ describe ::Bim::Bcf::IssuesController, type: :controller do
let(:file) { FileHelpers.mock_uploaded_file }
it 'should redirect back to where we started from' do
- expect { action }.to change { Attachment.count }.by(1)
+ expect { action }.to change { Attachment.count }.by(0)
expect(response).to redirect_to '/projects/bim_project/issues/upload'
end
end
diff --git a/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rb b/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rb
index 84d091df055..8f88d96dec0 100644
--- a/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rb
+++ b/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rb
@@ -29,13 +29,15 @@
FactoryBot.define do
factory :bcf_viewpoint_attachment, class: 'Attachment' do
description { "snapshot" }
- filename { "snapshot.jpg" }
+ filename { "image.png" }
content_type { "image/jpeg" }
author { User.current }
file do
- OpenProject::Files.create_uploaded_file name: filename,
- content_type: content_type,
- binary: true
+ Rack::Test::UploadedFile.new(
+ Rails.root.join("spec/fixtures/files/image.png"),
+ 'image/png',
+ true
+ )
end
end
end
diff --git a/modules/bim/spec/factories/ifc_model_factory.rb b/modules/bim/spec/factories/ifc_model_factory.rb
index 3162fd232cb..afa99ca606f 100644
--- a/modules/bim/spec/factories/ifc_model_factory.rb
+++ b/modules/bim/spec/factories/ifc_model_factory.rb
@@ -32,11 +32,19 @@ FactoryBot.define do
project factory: :project
uploader factory: :user
is_default { true }
- ifc_attachment do
- Rack::Test::UploadedFile.new(
- File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.ifc"),
- 'application/binary'
- )
+ transient do
+ ifc_attachment do
+ Rack::Test::UploadedFile.new(
+ File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.ifc"),
+ 'application/binary'
+ )
+ end
+
+ callback(:after_create) do |model, evaluator|
+ User.system.run_given do
+ model.ifc_attachment = evaluator.ifc_attachment
+ end
+ end
end
factory :ifc_model_minimal_converted do
@@ -44,12 +52,19 @@ FactoryBot.define do
project factory: :project
uploader factory: :user
is_default { true }
+ transient do
+ xkt_attachment do
+ Rack::Test::UploadedFile.new(
+ File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.xkt"),
+ 'application/binary'
+ )
+ end
+ end
- xkt_attachment do
- Rack::Test::UploadedFile.new(
- File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.xkt"),
- 'application/binary'
- )
+ callback(:after_create) do |model, evaluator|
+ User.system.run_given do
+ model.xkt_attachment = evaluator.xkt_attachment
+ end
end
end
end
diff --git a/modules/bim/spec/features/bim_navigation_spec.rb b/modules/bim/spec/features/bim_navigation_spec.rb
index e444666caff..0f2a3eb0064 100644
--- a/modules/bim/spec/features/bim_navigation_spec.rb
+++ b/modules/bim/spec/features/bim_navigation_spec.rb
@@ -44,7 +44,7 @@ describe 'BIM navigation spec',
member_through_role: role
end
- let!(:model) do
+ let(:model) do
FactoryBot.create(:ifc_model_minimal_converted,
project: project,
uploader: user)
@@ -56,16 +56,19 @@ describe 'BIM navigation spec',
let(:model_tree) { ::Components::XeokitModelTree.new }
let(:destroy_modal) { Components::WorkPackages::DestroyModal.new }
+ before do
+ login_as user
+ model
+ end
+
shared_examples 'can switch from split to viewer to list-only' do
before do
- login_as(user)
model_page.visit!
model_page.finished_loading
end
context 'deep link on the page' do
before do
- login_as(user)
model_page.visit!
model_page.finished_loading
diff --git a/modules/bim/spec/features/model_management_spec.rb b/modules/bim/spec/features/model_management_spec.rb
index 79049dce541..e45344f7570 100644
--- a/modules/bim/spec/features/model_management_spec.rb
+++ b/modules/bim/spec/features/model_management_spec.rb
@@ -44,14 +44,14 @@ describe 'model management',
member_through_role: role
end
- let(:model) do
+ let!(:model) do
FactoryBot.create(:ifc_model_minimal_converted,
project: project,
uploader: user,
is_default: true)
end
- let(:model2) do
+ let!(:model2) do
FactoryBot.create(:ifc_model_minimal_converted,
project: project,
uploader: user)
diff --git a/modules/bim/spec/features/model_viewer_spec.rb b/modules/bim/spec/features/model_viewer_spec.rb
index 44ea7c9868d..66eb1932a89 100644
--- a/modules/bim/spec/features/model_viewer_spec.rb
+++ b/modules/bim/spec/features/model_viewer_spec.rb
@@ -43,7 +43,7 @@ describe 'model viewer',
member_through_role: role
end
- let(:model) do
+ let!(:model) do
FactoryBot.create(:ifc_model_minimal_converted,
project: project,
uploader: user)
@@ -92,6 +92,8 @@ describe 'model viewer',
end
context 'in a project with no model' do
+ let!(:model) { nil }
+
it 'shows a warning that no IFC models exist yet' do
login_as user
visit defaults_bcf_project_ifc_models_path(project)
diff --git a/modules/bim/spec/models/ifc_model_spec.rb b/modules/bim/spec/models/ifc_model_spec.rb
index 4dc28cbc1d5..6542dc65d66 100644
--- a/modules/bim/spec/models/ifc_model_spec.rb
+++ b/modules/bim/spec/models/ifc_model_spec.rb
@@ -16,11 +16,17 @@ describe ::Bim::IfcModels::IfcModel, type: :model do
end
describe 'ifc_attachment=' do
- subject { FactoryBot.create :ifc_model_minimal_converted, project: FactoryBot.create(:project) }
+ let(:project) { FactoryBot.create(:project, enabled_module_names: %i[bim]) }
let(:ifc_attachment) { subject.ifc_attachment }
let(:new_attachment) do
FileHelpers.mock_uploaded_file name: "model.ifc", content_type: 'application/binary', binary: true
end
+ subject { FactoryBot.create :ifc_model_minimal_converted, project: project }
+ current_user do
+ FactoryBot.create :user,
+ member_in_project: project,
+ member_with_permissions: %i[manage_ifc_models]
+ end
it 'replaces the previous attachment' do
expect(ifc_attachment).to be_present
@@ -31,7 +37,7 @@ describe ::Bim::IfcModels::IfcModel, type: :model do
expect { ifc_attachment.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect(subject.ifc_attachment).not_to eq ifc_attachment
- expect(subject.ifc_attachment).not_to be_present
+ expect(subject.ifc_attachment).to be_present
expect(subject.xkt_attachment).not_to be_present
expect(subject).not_to be_converted
end
diff --git a/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rb b/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rb
index 87aa1c53fad..b672b7dd5e0 100644
--- a/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rb
+++ b/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rb
@@ -202,7 +202,7 @@ describe 'BCF 2.1 viewpoints resource', type: :request, content_type: :json, wit
it 'responds with the attachment with the appropriate content type and cache headers' do
expect(subject.status).to eq 200
- expect(subject.headers['Content-Type']).to eq 'image/jpeg'
+ expect(subject.headers['Content-Type']).to eq 'image/png'
max_age = OpenProject::Configuration.fog_download_url_expires_in - 10
diff --git a/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rb b/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rb
index 7bfc3783d4b..2a813b0b39a 100644
--- a/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rb
+++ b/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rb
@@ -60,6 +60,13 @@ describe Bim::Bcf::Viewpoints::SetAttributesService, type: :model do
Bim::Bcf::Viewpoint.new
end
+ before do
+ allow(viewpoint)
+ .to receive(:attachments_addable?)
+ .with(user, any_args)
+ .and_return true
+ end
+
describe 'call' do
# We only expect the service to be called for new records. As viewpoints
# are immutable.
@@ -113,7 +120,7 @@ describe Bim::Bcf::Viewpoints::SetAttributesService, type: :model do
expect(viewpoint.attachments.first.file.read)
.to eql 'Hello World!'
- expect(viewpoint.attachments.first.file.filename)
+ expect(viewpoint.attachments.first.filename)
.to eql 'snapshot.png'
end
diff --git a/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rb b/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rb
index 533d859149c..72427087cdf 100644
--- a/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rb
+++ b/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rb
@@ -31,7 +31,10 @@
require 'spec_helper'
describe Bim::IfcModels::SetAttributesService, type: :model do
- let(:user) { FactoryBot.build_stubbed(:user) }
+ shared_let(:project) { FactoryBot.create(:project, enabled_module_names: %i[bim]) }
+ shared_let(:other_project) { FactoryBot.create(:project, enabled_module_names: %i[bim]) }
+ shared_let(:user) { FactoryBot.create(:user, member_in_project: project, member_with_permissions: %i[manage_ifc_models]) }
+
let(:other_user) { FactoryBot.build_stubbed(:user) }
let(:contract_class) do
contract = double('contract_class')
@@ -58,10 +61,8 @@ describe Bim::IfcModels::SetAttributesService, type: :model do
end
let(:call_attributes) { {} }
let(:ifc_file) { FileHelpers.mock_uploaded_file(name: "model_2.ifc", content_type: 'application/binary', binary: true) }
- let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment) }
- let(:project) { FactoryBot.build_stubbed(:project) }
let(:model) do
- FactoryBot.build_stubbed(:ifc_model, attachments: [ifc_attachment], uploader: other_user)
+ FactoryBot.create(:ifc_model, project: project, uploader: other_user)
end
before do
@@ -72,7 +73,7 @@ describe Bim::IfcModels::SetAttributesService, type: :model do
describe 'call' do
let(:call_attributes) do
{
- project_id: project.id
+ project_id: other_project.id
}
end
@@ -96,7 +97,7 @@ describe Bim::IfcModels::SetAttributesService, type: :model do
subject
expect(model.attributes.slice(*model.changed).symbolize_keys)
- .to eql call_attributes
+ .to eql call_attributes.merge(uploader_id: user.id)
end
it 'does not persist the model' do
@@ -108,7 +109,7 @@ describe Bim::IfcModels::SetAttributesService, type: :model do
context 'for a new record' do
let(:model) do
- Bim::IfcModels::IfcModel.new
+ Bim::IfcModels::IfcModel.new project: project
end
context 'with an ifc_attachment' do
@@ -167,6 +168,8 @@ describe Bim::IfcModels::SetAttributesService, type: :model do
end
it 'marks existing attachments for destruction' do
+ ifc_attachment = model.ifc_attachment
+
subject
expect(ifc_attachment)
diff --git a/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb b/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb
index de62b36fb22..bd0dc398716 100644
--- a/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb
+++ b/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb
@@ -59,22 +59,16 @@ describe WorkPackages::Exports::ExportJob do
let(:mime_type) { :bcf }
it 'issues an OpenProject::Bim::BcfXml::Exporter export' do
- file = double(File)
- allow(file)
- .to receive(:is_a?)
- .with(File)
- .and_return true
-
result = WorkPackage::Exporter::Result::Success.new(format: 'blubs',
- title: 'some_title',
- content: file,
+ title: "some_title.#{mime_type}",
+ content: 'some content',
mime_type: "application/octet-stream")
service = double('attachments create service')
expect(Attachments::CreateService)
- .to receive(:new)
- .with(export, author: user)
+ .to receive(:bypass_whitelist)
+ .with(user: user)
.and_return(service)
expect(WorkPackages::Exports::CleanupOutdatedJob)
@@ -82,7 +76,7 @@ describe WorkPackages::Exports::ExportJob do
expect(service)
.to(receive(:call))
- .and_return attachment
+ .and_return(ServiceResult.new(result: attachment, success: true))
allow(OpenProject::Bim::BcfXml::Exporter)
.to receive(:list)
diff --git a/modules/budgets/app/contracts/budgets/base_contract.rb b/modules/budgets/app/contracts/budgets/base_contract.rb
new file mode 100644
index 00000000000..ece6c30e1fe
--- /dev/null
+++ b/modules/budgets/app/contracts/budgets/base_contract.rb
@@ -0,0 +1,65 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Budgets
+ class BaseContract < ::ModelContract
+ include Attachments::ValidateReplacements
+
+ def self.model
+ Budget
+ end
+
+ attribute :subject
+ attribute :description
+ attribute :fixed_date
+ attribute :project
+ attribute :new_material_budget_item_attributes,
+ readable: false
+
+ attribute :new_labor_budget_item_attributes,
+ readable: false
+
+ attribute :existing_material_budget_item_attributes,
+ readable: false
+
+ attribute :existing_labor_budget_item_attributes,
+ readable: false
+
+ validate :validate_manage_allowed
+
+ private
+
+ def validate_manage_allowed
+ unless user.allowed_to?(:edit_budgets, model.project)
+ errors.add :base, :error_unauthorized
+ end
+ end
+ end
+end
diff --git a/modules/budgets/app/contracts/budgets/create_contract.rb b/modules/budgets/app/contracts/budgets/create_contract.rb
new file mode 100644
index 00000000000..8708e9c74ca
--- /dev/null
+++ b/modules/budgets/app/contracts/budgets/create_contract.rb
@@ -0,0 +1,34 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Budgets
+ class CreateContract < BaseContract
+ end
+end
diff --git a/modules/budgets/app/contracts/budgets/update_contract.rb b/modules/budgets/app/contracts/budgets/update_contract.rb
new file mode 100644
index 00000000000..44a3337b219
--- /dev/null
+++ b/modules/budgets/app/contracts/budgets/update_contract.rb
@@ -0,0 +1,34 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Budgets
+ class UpdateContract < BaseContract
+ end
+end
diff --git a/modules/budgets/app/controllers/budgets_controller.rb b/modules/budgets/app/controllers/budgets_controller.rb
index bb26ce92206..370428f6f98 100644
--- a/modules/budgets/app/controllers/budgets_controller.rb
+++ b/modules/budgets/app/controllers/budgets_controller.rb
@@ -27,6 +27,8 @@
#++
class BudgetsController < ApplicationController
+ include AttachableServiceCall
+
before_action :find_budget, only: %i[show edit update copy]
before_action :find_budgets, only: :destroy
before_action :find_project, only: %i[new create update_material_budget_item update_labor_budget_item]
@@ -85,11 +87,12 @@ class BudgetsController < ApplicationController
def copy
source = Budget.find(params[:id].to_i)
- @budget = if source
- Budget.new_copy(source)
- else
- Budget.new
- end
+ @budget =
+ if source
+ Budget.new_copy(source)
+ else
+ Budget.new
+ end
@budget.fixed_date ||= Date.today
@@ -97,23 +100,15 @@ class BudgetsController < ApplicationController
end
def create
- @budget = Budget.new
- @budget.project_id = @project.id
-
- # fixed_date must be set before material_budget_items and labor_budget_items
- @budget.fixed_date = if params[:budget] && params[:budget][:fixed_date]
- params[:budget].delete(:fixed_date)
- else
- Date.today
- end
-
- @budget.attributes = permitted_params.budget
- @budget.attach_files(permitted_params.attachments.to_h)
+ call = attachable_create_call ::Budgets::CreateService,
+ args: permitted_params.budget.merge(project: @project)
+ @budget = call.result
- if @budget.save
+ if call.success?
flash[:notice] = t(:notice_successful_create)
redirect_to(params[:continue] ? { action: 'new' } : { action: 'show', id: @budget })
else
+ @errors = call.errors
render action: 'new', layout: !request.xhr?
end
end
@@ -123,20 +118,16 @@ class BudgetsController < ApplicationController
end
def update
- @budget.attributes = permitted_params.budget if params[:budget]
- if params[:budget][:existing_material_budget_item_attributes].nil?
- @budget.existing_material_budget_item_attributes = ({})
- end
- if params[:budget][:existing_labor_budget_item_attributes].nil?
- @budget.existing_labor_budget_item_attributes = ({})
- end
-
- @budget.attach_files(permitted_params.attachments.to_h)
+ call = attachable_update_call ::Budgets::UpdateService,
+ model: @budget,
+ args: permitted_params.budget
- if @budget.save
+ if call.success?
flash[:notice] = t(:notice_successful_update)
redirect_to(params[:back_to] || { action: 'show', id: @budget })
else
+ @budget = call.result
+ @errors = call.errors
render action: 'edit'
end
rescue ActiveRecord::StaleObjectError
diff --git a/modules/budgets/app/models/budget.rb b/modules/budgets/app/models/budget.rb
index 47b731947ab..998c43f10fd 100644
--- a/modules/budgets/app/models/budget.rb
+++ b/modules/budgets/app/models/budget.rb
@@ -97,11 +97,6 @@ class Budget < ApplicationRecord
end
end
- def initialize(attributes = nil)
- super
- self.author = User.current if new_record?
- end
-
def budget
material_budget + labor_budget
end
diff --git a/modules/budgets/app/services/budgets/create_service.rb b/modules/budgets/app/services/budgets/create_service.rb
new file mode 100644
index 00000000000..2125f3fc672
--- /dev/null
+++ b/modules/budgets/app/services/budgets/create_service.rb
@@ -0,0 +1,33 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Budgets
+ class CreateService < ::BaseServices::Create
+ include Attachments::ReplaceAttachments
+ end
+end
diff --git a/modules/budgets/app/services/budgets/set_attributes_service.rb b/modules/budgets/app/services/budgets/set_attributes_service.rb
new file mode 100644
index 00000000000..71481e2dd65
--- /dev/null
+++ b/modules/budgets/app/services/budgets/set_attributes_service.rb
@@ -0,0 +1,65 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Budgets
+ class SetAttributesService < ::BaseServices::SetAttributes
+ include Attachments::SetReplacements
+
+ private
+
+ def set_attributes(params)
+ set_fixed_date(params)
+ unset_items(params)
+
+ super
+ end
+
+ def set_default_attributes(_params)
+ model.change_by_system do
+ model.author = user
+ end
+ end
+
+ # fixed_date must be set before material_budget_items and labor_budget_items
+ def set_fixed_date(params)
+ model.fixed_date = params.delete(:fixed_date) || Date.today
+ end
+
+ def unset_items(params)
+ if params[:existing_material_budget_item_attributes].nil?
+ model.existing_material_budget_item_attributes = ({})
+ end
+
+ if params[:existing_labor_budget_item_attributes].nil?
+ model.existing_labor_budget_item_attributes = ({})
+ end
+ end
+ end
+end
diff --git a/modules/budgets/app/services/budgets/update_service.rb b/modules/budgets/app/services/budgets/update_service.rb
new file mode 100644
index 00000000000..dfa73c33a9d
--- /dev/null
+++ b/modules/budgets/app/services/budgets/update_service.rb
@@ -0,0 +1,35 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Budgets
+ class UpdateService < ::BaseServices::Update
+ include Attachments::ReplaceAttachments
+ end
+end
diff --git a/modules/budgets/app/views/budgets/_edit.html.erb b/modules/budgets/app/views/budgets/_edit.html.erb
index 4a392b15171..9e195f8027a 100644
--- a/modules/budgets/app/views/budgets/_edit.html.erb
+++ b/modules/budgets/app/views/budgets/_edit.html.erb
@@ -33,7 +33,6 @@ See docs/COPYRIGHT.rdoc for more details.
:html => {:multipart => true,
:id => 'budget_form',
:class => 'form'} do |f| %>
- <%= error_messages_for 'budget' %>
<%= render :partial => 'form', :locals => {:f => f} %>
<div class="generic-table--action-buttons">
<%= styled_button_tag t(:button_submit), class: '-with-icon icon-checkmark -highlight', id: 'budget-table--submit-button'%>
diff --git a/modules/budgets/app/views/budgets/_form.html.erb b/modules/budgets/app/views/budgets/_form.html.erb
index e3162429f05..85339408acd 100644
--- a/modules/budgets/app/views/budgets/_form.html.erb
+++ b/modules/budgets/app/views/budgets/_form.html.erb
@@ -28,6 +28,7 @@ See docs/COPYRIGHT.rdoc for more details.
++#%>
<% resource = budget_attachment_representer(f.object) %>
+<%= error_messages_for_contract @budget, @errors %>
<div class="form--field -required">
<%= f.text_field :subject, required: true, autofocus: true, container_class: '-wide' %>
diff --git a/modules/budgets/app/views/budgets/new.html.erb b/modules/budgets/app/views/budgets/new.html.erb
index 5e8729f9f5e..3f872e89f79 100644
--- a/modules/budgets/app/views/budgets/new.html.erb
+++ b/modules/budgets/app/views/budgets/new.html.erb
@@ -34,7 +34,6 @@ See docs/COPYRIGHT.rdoc for more details.
:url => projects_budgets_path(@project),
:as => :budget,
:html => {:multipart => true, :id => 'budget_form'} do |f| %>
- <%= error_messages_for 'budget' %>
<%= render :partial => 'form', :locals => {:f => f} %>
<%= styled_button_tag t(:button_create), class: '-with-icon icon-checkmark' %>
<%= styled_button_tag t(:button_create_and_continue), :name => 'continue',
diff --git a/modules/budgets/spec/models/budget_spec.rb b/modules/budgets/spec/models/budget_spec.rb
index 4aed89166ca..a3bb498b0a0 100644
--- a/modules/budgets/spec/models/budget_spec.rb
+++ b/modules/budgets/spec/models/budget_spec.rb
@@ -34,16 +34,6 @@ describe Budget, type: :model do
let(:project) { FactoryBot.create(:project_with_types) }
let(:user) { FactoryBot.create(:user) }
- describe 'initialization' do
- let(:budget) { Budget.new }
-
- before do
- allow(User).to receive(:current).and_return(user)
- end
-
- it { expect(budget.author).to eq(user) }
- end
-
describe 'destroy' do
let(:work_package) { FactoryBot.create(:work_package, project: project) }
diff --git a/modules/budgets/spec/services/budgets/create_service_spec.rb b/modules/budgets/spec/services/budgets/create_service_spec.rb
new file mode 100644
index 00000000000..4f4ba1949ea
--- /dev/null
+++ b/modules/budgets/spec/services/budgets/create_service_spec.rb
@@ -0,0 +1,36 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'services/base_services/behaves_like_create_service'
+
+describe Budgets::CreateService, type: :model do
+ it_behaves_like 'BaseServices create service'
+end
diff --git a/modules/budgets/spec/services/budgets/update_service_spec.rb b/modules/budgets/spec/services/budgets/update_service_spec.rb
new file mode 100644
index 00000000000..42051f91157
--- /dev/null
+++ b/modules/budgets/spec/services/budgets/update_service_spec.rb
@@ -0,0 +1,36 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'services/base_services/behaves_like_update_service'
+
+describe Budgets::UpdateService, type: :model do
+ it_behaves_like 'BaseServices update service'
+end
diff --git a/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rb b/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rb
index dd5f1e91eda..f5b6a580a14 100644
--- a/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rb
+++ b/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rb
@@ -27,118 +27,19 @@
#++
require 'spec_helper'
-require 'rack/test'
+require 'requests/api/v3/attachments/attachment_resource_shared_examples'
-describe 'API v3 Attachments by budget resource', type: :request do
- include Rack::Test::Methods
- include API::V3::Utilities::PathHelper
- include FileHelpers
+describe "budget attachments" do
+ it_behaves_like "an APIv3 attachment resource" do
+ let(:attachment_type) { :budget }
- let(:current_user) do
- FactoryBot.create(:user,
- member_in_project: project,
- member_with_permissions: permissions)
- end
- let(:project) { FactoryBot.create(:project) }
- let(:permissions) { [:view_budgets] }
- let(:budget) { FactoryBot.create(:budget, project: project) }
-
- subject(:response) { last_response }
-
- before do
- allow(User).to receive(:current).and_return current_user
- end
-
- describe '#get' do
- let(:get_path) { api_v3_paths.attachments_by_budget budget.id }
+ let(:create_permission) { :edit_budgets }
+ let(:read_permission) { :view_budgets }
+ let(:update_permission) { :edit_budgets }
- before do
- FactoryBot.create_list(:attachment, 2, container: budget)
- get get_path
- end
-
- it 'should respond with 200' do
- expect(subject.status).to eq(200)
- end
-
- it_behaves_like 'API V3 collection response', 2, 2, 'Attachment'
- end
-
- describe '#post' do
- let(:permissions) { %i[view_budgets edit_budgets] }
-
- let(:request_path) { api_v3_paths.attachments_by_budget budget.id }
- let(:request_parts) { { metadata: metadata.to_json, file: file } }
- let(:metadata) { { fileName: 'cat.png' } }
- let(:file) { mock_uploaded_file(name: 'original-filename.txt') }
- let(:max_file_size) { 1 } # given in kiB
-
- before do
- allow(Setting).to receive(:attachment_max_size).and_return max_file_size.to_s
- post request_path, request_parts
- end
-
- it 'should respond with HTTP Created' do
- expect(subject.status).to eq(201)
- end
-
- it 'should return the new attachment' do
- expect(subject.body).to be_json_eql('Attachment'.to_json).at_path('_type')
- end
-
- it 'ignores the original file name' do
- expect(subject.body).to be_json_eql('cat.png'.to_json).at_path('fileName')
- end
-
- context 'metadata section is missing' do
- let(:request_parts) { { file: file } }
-
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
- end
-
- context 'file section is missing' do
- # rack-test won't send a multipart request without a file being present
- # however as long as we depend on correctly named sections this test should do just fine
- let(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }
-
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
- end
-
- context 'metadata section is no valid JSON' do
- let(:request_parts) { { metadata: '"fileName": "cat.png"', file: file } }
-
- it_behaves_like 'parse error'
- end
-
- context 'metadata is missing the fileName' do
- let(:metadata) { Hash.new }
-
- it_behaves_like 'constraint violation' do
- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }
- end
- end
-
- context 'file is too large' do
- let(:file) { mock_uploaded_file(content: 'a' * 2.kilobytes) }
- let(:expanded_localization) do
- I18n.t('activerecord.errors.messages.file_too_large', count: max_file_size.kilobytes)
- end
-
- it_behaves_like 'constraint violation' do
- let(:message) { "File #{expanded_localization}" }
- end
- end
-
- context 'only allowed to add messages, but no edit permission' do
- let(:permissions) { %i[view_messages add_messages] }
-
- it_behaves_like 'unauthorized access'
- end
-
- context 'only allowed to view messages' do
- let(:permissions) { [:view_messages] }
-
- it_behaves_like 'unauthorized access'
+ let(:budget) do
+ FactoryBot.create :budget, project: project
end
end
end
+
diff --git a/modules/documents/app/contracts/documents/base_contract.rb b/modules/documents/app/contracts/documents/base_contract.rb
new file mode 100644
index 00000000000..0670ef94a0f
--- /dev/null
+++ b/modules/documents/app/contracts/documents/base_contract.rb
@@ -0,0 +1,54 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Documents
+ class BaseContract < ::ModelContract
+ include Attachments::ValidateReplacements
+
+ def self.model
+ Document
+ end
+
+ attribute :project
+ attribute :category
+ attribute :title
+ attribute :description
+
+ validate :validate_manage_allowed
+
+ private
+
+ def validate_manage_allowed
+ unless user.allowed_to?(:manage_documents, model.project)
+ errors.add :base, :error_unauthorized
+ end
+ end
+ end
+end
diff --git a/modules/documents/app/contracts/documents/create_contract.rb b/modules/documents/app/contracts/documents/create_contract.rb
new file mode 100644
index 00000000000..29af7bcec61
--- /dev/null
+++ b/modules/documents/app/contracts/documents/create_contract.rb
@@ -0,0 +1,34 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Documents
+ class CreateContract < BaseContract
+ end
+end
diff --git a/modules/documents/app/contracts/documents/update_contract.rb b/modules/documents/app/contracts/documents/update_contract.rb
new file mode 100644
index 00000000000..1c83f98988e
--- /dev/null
+++ b/modules/documents/app/contracts/documents/update_contract.rb
@@ -0,0 +1,34 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Documents
+ class UpdateContract < BaseContract
+ end
+end
diff --git a/modules/documents/app/controllers/documents_controller.rb b/modules/documents/app/controllers/documents_controller.rb
index f805cc106e7..1c3f4a22491 100644
--- a/modules/documents/app/controllers/documents_controller.rb
+++ b/modules/documents/app/controllers/documents_controller.rb
@@ -29,6 +29,7 @@
#++
class DocumentsController < ApplicationController
+ include AttachableServiceCall
default_search_scope :documents
model_object Document
before_action :find_project_by_project_id, only: %i[index new create]
@@ -64,14 +65,15 @@ class DocumentsController < ApplicationController
end
def create
- @document = @project.documents.build
- @document.attributes = document_params
- @document.attach_files(permitted_params.attachments.to_h)
+ call = attachable_create_call ::Documents::CreateService,
+ args: document_params.merge(project: @project)
- if @document.save
+ if call.success?
flash[:notice] = I18n.t(:notice_successful_create)
redirect_to project_documents_path(@project)
else
+ @document = call.result
+ @errors = call.errors
render action: 'new'
end
end
@@ -81,13 +83,16 @@ class DocumentsController < ApplicationController
end
def update
- @document.attributes = document_params
- @document.attach_files(permitted_params.attachments.to_h)
+ call = attachable_update_call ::Documents::UpdateService,
+ model: @document,
+ args: document_params
- if @document.save
+ if call.success?
flash[:notice] = I18n.t(:notice_successful_update)
redirect_to action: 'show', id: @document
else
+ @document = call.result
+ @errors = call.errors
render action: 'edit'
end
end
@@ -98,18 +103,19 @@ class DocumentsController < ApplicationController
end
def add_attachment
- @document.attach_files(permitted_params.attachments.to_h)
- attachments = @document.attachments.select(&:new_record?)
+ current_attachments = @document.attachments.pluck(:id)
+ call = attachable_update_call ::Documents::UpdateService,
+ model: @document,
+ args: document_params
- @document.save
- saved_attachments = attachments.select(&:persisted?)
+ if call.success? && Setting.notified_events.include?('document_added')
+ added = call.result
+ .attachments
+ .reject { |a| current_attachments.include?(a.id) }
- if saved_attachments.present? && Setting.notified_events.include?('document_added')
- users = saved_attachments.first.container.recipients
- users.each do |user|
- UserMailer.attachments_added(user, saved_attachments).deliver_later
- end
+ notify_attachments added
end
+
redirect_to action: 'show', id: @document
end
@@ -118,4 +124,14 @@ class DocumentsController < ApplicationController
def document_params
params.fetch(:document, {}).permit('category_id', 'title', 'description')
end
+
+ def notify_attachments(added)
+ return if added.empty?
+
+ users = added.first.container.recipients
+ users.each do |user|
+ UserMailer.attachments_added(user, added).deliver_later
+ end
+ end
+
end
diff --git a/modules/documents/app/services/documents/create_service.rb b/modules/documents/app/services/documents/create_service.rb
new file mode 100644
index 00000000000..62ba3665e68
--- /dev/null
+++ b/modules/documents/app/services/documents/create_service.rb
@@ -0,0 +1,35 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Documents
+ class CreateService < ::BaseServices::Create
+ include Attachments::ReplaceAttachments
+ end
+end
diff --git a/modules/documents/app/services/documents/set_attributes_service.rb b/modules/documents/app/services/documents/set_attributes_service.rb
new file mode 100644
index 00000000000..c9d4a807f3b
--- /dev/null
+++ b/modules/documents/app/services/documents/set_attributes_service.rb
@@ -0,0 +1,35 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Documents
+ class SetAttributesService < ::BaseServices::SetAttributes
+ include Attachments::SetReplacements
+ end
+end
diff --git a/modules/documents/app/services/documents/update_service.rb b/modules/documents/app/services/documents/update_service.rb
new file mode 100644
index 00000000000..5e7013f28e2
--- /dev/null
+++ b/modules/documents/app/services/documents/update_service.rb
@@ -0,0 +1,35 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module Documents
+ class UpdateService < ::BaseServices::Update
+ include Attachments::ReplaceAttachments
+ end
+end
diff --git a/modules/documents/app/views/documents/_form.html.erb b/modules/documents/app/views/documents/_form.html.erb
index 26cb35da227..3957fc46b5a 100644
--- a/modules/documents/app/views/documents/_form.html.erb
+++ b/modules/documents/app/views/documents/_form.html.erb
@@ -27,7 +27,7 @@ See docs/COPYRIGHT.rdoc for more details.
++#%>
-<%= error_messages_for 'document' %>
+<%= error_messages_for_contract @document, @errors %>
<div class="form--field -required">
<%= f.select :category_id,
diff --git a/modules/documents/spec/controllers/documents_controller_spec.rb b/modules/documents/spec/controllers/documents_controller_spec.rb
index 9227b5d9166..98deb4c8c06 100644
--- a/modules/documents/spec/controllers/documents_controller_spec.rb
+++ b/modules/documents/spec/controllers/documents_controller_spec.rb
@@ -128,6 +128,7 @@ describe DocumentsController do
end
describe "with attachments" do
+ let(:uncontainered) { FactoryBot.create :attachment, container: nil, author: admin }
before do
notify_project = project
FactoryBot.create(:member, project: notify_project, user: user, roles: [role])
@@ -138,7 +139,7 @@ describe DocumentsController do
document: FactoryBot.attributes_for(:document, title: "New Document",
project_id: notify_project.id,
category_id: default_category.id),
- attachments: { '1' => { description: "sample file", file: file_attachment } }
+ attachments: { '1' => { id: uncontainered.id } }
}
end
@@ -147,8 +148,7 @@ describe DocumentsController do
expect(document.attachments.count).to eql 1
attachment = document.attachments.first
- expect(attachment.description).to eql "sample file"
- expect(attachment.filename).to eql "testfile.txt"
+ expect(uncontainered.reload).to eql attachment
end
it "should redirect to the documents-page" do
@@ -174,12 +174,14 @@ describe DocumentsController do
end
describe '#add_attachment' do
+ let(:uncontainered) { FactoryBot.create :attachment, container: nil, author: admin }
+
before do
document
post :add_attachment,
params: {
id: document.id,
- attachments: { '1' => { description: "sample file", file: file_attachment } }
+ attachments: { '1' => { id: uncontainered.id } }
}
end
@@ -187,6 +189,7 @@ describe DocumentsController do
expect(response).to be_redirect
document.reload
expect(document.attachments.length).to eq(1)
+ expect(uncontainered.reload).to eq document.attachments.first
end
end
diff --git a/modules/documents/spec/models/document_spec.rb b/modules/documents/spec/models/document_spec.rb
index b76ae232342..12813cb52e9 100644
--- a/modules/documents/spec/models/document_spec.rb
+++ b/modules/documents/spec/models/document_spec.rb
@@ -86,8 +86,8 @@ describe Document do
expect do
Attachments::CreateService
- .new(valid_document, author: admin)
- .call(uploaded_file: FactoryBot.attributes_for(:attachment)[:file], description: '')
+ .new(user: admin)
+ .call(container: valid_document, file: FactoryBot.attributes_for(:attachment)[:file], filename: 'foo')
expect(valid_document.attachments.size).to eql 1
end.to(change do
diff --git a/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rb b/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rb
index 4c12f43f303..552aef077b4 100644
--- a/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rb
+++ b/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rb
@@ -27,113 +27,19 @@
#++
require 'spec_helper'
-require 'rack/test'
+require 'requests/api/v3/attachments/attachment_resource_shared_examples'
-describe 'API v3 Attachments by document resource', type: :request do
- include Rack::Test::Methods
- include API::V3::Utilities::PathHelper
- include FileHelpers
+describe "document attachments" do
+ it_behaves_like "an APIv3 attachment resource" do
+ let(:attachment_type) { :document }
- let(:current_user) do
- FactoryBot.create(:user,
- member_in_project: project,
- member_through_role: role)
- end
- let(:project) { FactoryBot.create(:project) }
- let(:role) { FactoryBot.create(:role, permissions: permissions) }
- let(:permissions) { [:view_documents] }
- let(:document) { FactoryBot.create(:document, project: project) }
-
- subject(:response) { last_response }
-
- before do
- allow(User).to receive(:current).and_return current_user
- end
-
- describe '#get' do
- let(:get_path) { api_v3_paths.attachments_by_document document.id }
-
- before do
- FactoryBot.create_list(:attachment, 2, container: document)
- get get_path
- end
-
- it 'should respond with 200' do
- expect(subject.status).to eq(200)
- end
-
- it_behaves_like 'API V3 collection response', 2, 2, 'Attachment'
- end
-
- describe '#post' do
- let(:permissions) { %i[view_documents manage_documents] }
-
- let(:request_path) { api_v3_paths.attachments_by_document document.id }
- let(:request_parts) { { metadata: metadata.to_json, file: file } }
- let(:metadata) { { fileName: 'cat.png' } }
- let(:file) { mock_uploaded_file(name: 'original-filename.txt') }
- let(:max_file_size) { 1 } # given in kiB
-
- before do
- allow(Setting).to receive(:attachment_max_size).and_return max_file_size.to_s
- post request_path, request_parts
- end
-
- it 'should respond with HTTP Created' do
- expect(subject.status).to eq(201)
- end
-
- it 'should return the new attachment' do
- expect(subject.body).to be_json_eql('Attachment'.to_json).at_path('_type')
- end
+ let(:create_permission) { :manage_documents }
+ let(:read_permission) { :view_documents }
+ let(:update_permission) { :manage_documents }
- it 'ignores the original file name' do
- expect(subject.body).to be_json_eql('cat.png'.to_json).at_path('fileName')
- end
-
- context 'metadata section is missing' do
- let(:request_parts) { { file: file } }
-
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
- end
-
- context 'file section is missing' do
- # rack-test won't send a multipart request without a file being present
- # however as long as we depend on correctly named sections this test should do just fine
- let(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }
-
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
- end
-
- context 'metadata section is no valid JSON' do
- let(:request_parts) { { metadata: '"fileName": "cat.png"', file: file } }
-
- it_behaves_like 'parse error'
- end
-
- context 'metadata is missing the fileName' do
- let(:metadata) { Hash.new }
-
- it_behaves_like 'constraint violation' do
- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }
- end
- end
-
- context 'file is too large' do
- let(:file) { mock_uploaded_file(content: 'a' * 2.kilobytes) }
- let(:expanded_localization) do
- I18n.t('activerecord.errors.messages.file_too_large', count: max_file_size.kilobytes)
- end
-
- it_behaves_like 'constraint violation' do
- let(:message) { "File #{expanded_localization}" }
- end
- end
-
- context 'only allowed to view documents' do
- let(:permissions) { [:view_documents] }
-
- it_behaves_like 'unauthorized access'
+ let(:document) do
+ FactoryBot.create :document, project: project
end
end
end
+
diff --git a/modules/job_status/spec/services/documents/create_service_spec.rb b/modules/job_status/spec/services/documents/create_service_spec.rb
new file mode 100644
index 00000000000..7bf9c46ff4a
--- /dev/null
+++ b/modules/job_status/spec/services/documents/create_service_spec.rb
@@ -0,0 +1,6 @@
+require 'spec_helper'
+require 'services/base_services/behaves_like_create_service'
+
+describe Documents::CreateService, type: :model do
+ it_behaves_like 'BaseServices create service'
+end
\ No newline at end of file
diff --git a/modules/job_status/spec/services/documents/update_service_spec.rb b/modules/job_status/spec/services/documents/update_service_spec.rb
new file mode 100644
index 00000000000..511f0b398d3
--- /dev/null
+++ b/modules/job_status/spec/services/documents/update_service_spec.rb
@@ -0,0 +1,36 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'services/base_services/behaves_like_update_service'
+
+describe Documents::UpdateService, type: :model do
+ it_behaves_like 'BaseServices update service'
+end
diff --git a/modules/meeting/app/contracts/meeting_contents/base_contract.rb b/modules/meeting/app/contracts/meeting_contents/base_contract.rb
new file mode 100644
index 00000000000..ed749bf2624
--- /dev/null
+++ b/modules/meeting/app/contracts/meeting_contents/base_contract.rb
@@ -0,0 +1,55 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module MeetingContents
+ class BaseContract < ::ModelContract
+ include Attachments::ValidateReplacements
+
+ def self.model
+ MeetingContent
+ end
+
+ attribute :meeting
+ attribute :text
+ attribute :lock_version
+ attribute :locked
+ attribute :type
+
+ validate :type_in_allowed
+
+ private
+
+ def type_in_allowed
+ unless [MeetingAgenda.name, MeetingMinutes.name].include?(model.type)
+ errors.add(:type, :inclusion)
+ end
+ end
+ end
+end
diff --git a/modules/meeting/app/contracts/meeting_contents/update_contract.rb b/modules/meeting/app/contracts/meeting_contents/update_contract.rb
new file mode 100644
index 00000000000..605d58ff160
--- /dev/null
+++ b/modules/meeting/app/contracts/meeting_contents/update_contract.rb
@@ -0,0 +1,43 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module MeetingContents
+ class UpdateContract < BaseContract
+ validate :validate_editable
+
+ private
+
+ def validate_editable
+ unless model.editable?
+ errors.add :base, :error_readonly
+ end
+ end
+ end
+end
diff --git a/modules/meeting/app/controllers/meeting_contents_controller.rb b/modules/meeting/app/controllers/meeting_contents_controller.rb
index dd89619493a..9ff36aca032 100644
--- a/modules/meeting/app/controllers/meeting_contents_controller.rb
+++ b/modules/meeting/app/controllers/meeting_contents_controller.rb
@@ -27,6 +27,7 @@
#++
class MeetingContentsController < ApplicationController
+ include AttachableServiceCall
include PaginationHelper
menu_item :meetings
@@ -60,26 +61,26 @@ class MeetingContentsController < ApplicationController
end
def update
- (render_403; return) unless @content.editable? # TODO: not tested!
- @content.attributes = content_params.merge(author: User.current)
- @content.attach_files(permitted_params.attachments.to_h)
-
- if [email protected]_version_changed?
- if @content.save
- flash[:notice] = I18n.t(:notice_successful_update)
- redirect_back_or_default controller: '/meetings', action: 'show', id: @meeting
- end
+ call = attachable_update_call ::MeetingContents::UpdateService,
+ model: @content,
+ args: content_params
+
+ if call.success?
+ flash[:notice] = I18n.t(:notice_successful_update)
+ redirect_back_or_default controller: '/meetings', action: 'show', id: @meeting
else
- render_conflict
+ flash.now[:error] = call.message
+ params[:tab] ||= 'minutes' if @meeting.agenda.present? && @meeting.agenda.locked?
+ render 'meetings/show'
end
end
def history
# don't load text
@content_versions = @content.journals.select('id, user_id, notes, created_at, version')
- .order(Arel.sql('version DESC'))
- .page(page_param)
- .per_page(per_page_param)
+ .order(Arel.sql('version DESC'))
+ .page(page_param)
+ .per_page(per_page_param)
render 'meeting_contents/history', layout: !request.xhr?
end
@@ -129,19 +130,13 @@ class MeetingContentsController < ApplicationController
def find_meeting
@meeting = Meeting.includes(:project, :author, :participants, :agenda, :minutes)
- .find(params[:meeting_id])
+ .find(params[:meeting_id])
@project = @meeting.project
@author = User.current
rescue ActiveRecord::RecordNotFound
render_404
end
- def render_conflict
- flash.now[:error] = I18n.t(:notice_locking_conflict)
- params[:tab] ||= 'minutes' if @meeting.agenda.present? && @meeting.agenda.locked?
- render 'meetings/show'
- end
-
def content_params
params.require(@content_type).permit(:text, :lock_version, :comment)
end
diff --git a/modules/meeting/app/services/meeting_contents/set_attributes_service.rb b/modules/meeting/app/services/meeting_contents/set_attributes_service.rb
new file mode 100644
index 00000000000..321ea665fda
--- /dev/null
+++ b/modules/meeting/app/services/meeting_contents/set_attributes_service.rb
@@ -0,0 +1,42 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module MeetingContents
+ class SetAttributesService < ::BaseServices::SetAttributes
+ include Attachments::SetReplacements
+
+
+ def set_default_attributes(_params)
+ model.change_by_system do
+ model.author = user if model.author.nil?
+ end
+ end
+ end
+end
diff --git a/modules/meeting/app/services/meeting_contents/update_service.rb b/modules/meeting/app/services/meeting_contents/update_service.rb
new file mode 100644
index 00000000000..8eb13957337
--- /dev/null
+++ b/modules/meeting/app/services/meeting_contents/update_service.rb
@@ -0,0 +1,47 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+module MeetingContents
+ class UpdateService < ::BaseServices::Update
+ include Attachments::ReplaceAttachments
+
+ def persist(call)
+ content = call.result
+
+ if content.lock_version_changed?
+ call.errors.add(:base, I18n.t(:notice_locking_conflict))
+ call.success = false
+ return call
+ end
+
+ super
+ end
+ end
+end
diff --git a/modules/meeting/spec/contracts/meeting_contents/update_contract_spec.rb b/modules/meeting/spec/contracts/meeting_contents/update_contract_spec.rb
new file mode 100644
index 00000000000..3ebddead893
--- /dev/null
+++ b/modules/meeting/spec/contracts/meeting_contents/update_contract_spec.rb
@@ -0,0 +1,55 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'contracts/shared/model_contract_shared_context'
+
+describe MeetingContents::UpdateContract do
+ include_context 'ModelContract shared context'
+ let(:agenda) { FactoryBot.build_stubbed(:meeting_agenda) }
+ let(:current_user) { FactoryBot.build_stubbed(:user) }
+ let(:contract) { described_class.new(agenda, current_user) }
+
+ context 'when not editable' do
+ before do
+ allow(agenda).to receive(:editable?).and_return false
+ end
+
+ it_behaves_like 'contract is invalid', base: :error_readonly
+ end
+
+ context 'when editable' do
+ before do
+ allow(agenda).to receive(:editable?).and_return true
+ end
+
+ it_behaves_like 'contract is valid'
+ end
+end
diff --git a/modules/meeting/spec/services/meeting_contents/update_service_spec.rb b/modules/meeting/spec/services/meeting_contents/update_service_spec.rb
new file mode 100644
index 00000000000..11dc41cc59d
--- /dev/null
+++ b/modules/meeting/spec/services/meeting_contents/update_service_spec.rb
@@ -0,0 +1,38 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'services/base_services/behaves_like_update_service'
+
+describe MeetingContents::UpdateService, type: :model do
+ it_behaves_like 'BaseServices update service' do
+ let(:factory) { :meeting_agenda }
+ end
+end
diff --git a/spec/contracts/attachments/create_contract_spec.rb b/spec/contracts/attachments/create_contract_spec.rb
new file mode 100644
index 00000000000..efcce412ac3
--- /dev/null
+++ b/spec/contracts/attachments/create_contract_spec.rb
@@ -0,0 +1,143 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2021 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+#++
+
+require 'spec_helper'
+require 'contracts/shared/model_contract_shared_context'
+
+describe Attachments::CreateContract do
+ include_context 'ModelContract shared context'
+
+ let(:current_user) { FactoryBot.build_stubbed :user }
+ let(:model) do
+ FactoryBot.build :attachment,
+ container: container,
+ content_type: content_type,
+ file: file,
+ filename: filename,
+ author: current_user
+ end
+ let(:contract) { described_class.new model, user, options: contract_options }
+ let(:contract_options) { {} }
+
+ let(:user) { current_user }
+ let(:container) { nil }
+ let(:file) do
+ Rack::Test::UploadedFile.new(
+ Rails.root.join("spec/fixtures/files/image.png"),
+ 'image/png',
+ true
+ )
+ end
+ let(:content_type) { 'image/png' }
+ let(:filename) { 'image.png' }
+
+ let(:can_attach_global) { true }
+
+ before do
+ allow(Redmine::Acts::Attachable.attachables)
+ .to receive(:none?).and_return(!can_attach_global)
+ end
+
+ context 'with user who has no permissions' do
+ let(:can_attach_global) { false }
+
+ it_behaves_like 'contract is invalid', base: :error_unauthorized
+ end
+
+ context 'with a user that is not the author' do
+ let(:user) { FactoryBot.build_stubbed :user }
+
+ it_behaves_like 'contract is invalid', author: :invalid
+ end
+
+ context 'with user who has permissions to add' do
+ it_behaves_like 'contract is valid'
+ end
+
+ context 'with a container' do
+ let(:container) { FactoryBot.build_stubbed :work_package }
+
+ before do
+ allow(container)
+ .to receive(:attachments_addable?)
+ .with(user)
+ .and_return(can_attach)
+ end
+
+ context 'with user who has no permissions' do
+ let(:can_attach) { false }
+
+ it_behaves_like 'contract is invalid', base: :error_unauthorized
+ end
+
+ context 'with user who has permissions to add' do
+ let(:can_attach) { true }
+
+ it_behaves_like 'contract is valid'
+ end
+
+ end
+
+ context 'with an empty whitelist',
+ with_settings: { attachment_whitelist: %w[] } do
+ it_behaves_like 'contract is valid'
+ end
+
+ context 'with a matching mime whitelist',
+ with_settings: { attachment_whitelist: %w[image/png] } do
+ it_behaves_like 'contract is valid'
+ end
+
+ context 'with a matching extension whitelist',
+ with_settings: { attachment_whitelist: %w[*.png] } do
+ it_behaves_like 'contract is valid'
+ end
+
+ context 'with a non-matching whitelist',
+ with_settings: { attachment_whitelist: %w[*.jpg image/jpeg] } do
+ it_behaves_like 'contract is invalid', content_type: :not_whitelisted
+
+ context 'when disabling the whitelist check' do
+ let(:contract_options) do
+ { whitelist: [] }
+ end
+
+ it_behaves_like 'contract is valid'
+ end
+
+ context 'when overriding the whitelist' do
+ let(:contract_options) do
+ { whitelist: %w[*.png] }
+ end
+
+ it_behaves_like 'contract is valid'
+ end
+ end
+end
diff --git a/spec/factories/attachment_factory.rb b/spec/factories/attachment_factory.rb
index e09b57ab4a6..55c37949cb8 100644
--- a/spec/factories/attachment_factory.rb
+++ b/spec/factories/attachment_factory.rb
@@ -45,6 +45,10 @@ FactoryBot.define do
binary: true
end
+ callback(:after_build, :after_stub) do |attachment, evaluator|
+ attachment.filename = evaluator.filename if evaluator.filename
+ end
+
factory :wiki_attachment do
container factory: :wiki_page_with_content
end
diff --git a/spec/features/auth/login_spec.rb b/spec/features/auth/login_spec.rb
index f3affef1d09..c1d3c8d1702 100644
--- a/spec/features/auth/login_spec.rb
+++ b/spec/features/auth/login_spec.rb
@@ -28,7 +28,7 @@
require 'spec_helper'
-describe 'Login', type: :feature do
+describe 'Login', type: :feature, clear_cache: true do
before do
@capybara_ignore_elements = Capybara.ignore_hidden_elements
Capybara.ignore_hidden_elements = true
diff --git a/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rb b/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rb
index 1ea8f18f73d..094cdfb84fb 100644
--- a/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rb
+++ b/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rb
@@ -28,15 +28,16 @@
require 'spec_helper'
-describe ::API::V3::Attachments::AttachmentMetadataRepresenter do
+describe ::API::V3::Attachments::AttachmentParsingRepresenter do
+ let(:current_user) { FactoryBot.build_stubbed :user }
include API::V3::Utilities::PathHelper
let(:metadata) do
data = Hashie::Mash.new
- data.file_name = original_file_name
+ data.filename = original_file_name
data.description = original_description
data.content_type = original_content_type
- data.file_size = original_file_size
+ data.filesize = original_file_size
data.digest = original_digest
data
end
@@ -47,34 +48,18 @@ describe ::API::V3::Attachments::AttachmentMetadataRepresenter do
let(:original_file_size) { 42 }
let(:original_digest) { "0xFF" }
- let(:representer) { ::API::V3::Attachments::AttachmentMetadataRepresenter.new(metadata) }
-
- describe 'generation' do
- subject { representer.to_json }
-
- it 'is a type-less representer' do
- is_expected.not_to have_json_path('_type')
- end
-
- it { is_expected.to be_json_eql(original_file_name.to_json).at_path('fileName') }
- it { is_expected.to be_json_eql(original_content_type.to_json).at_path('contentType') }
- it { is_expected.to be_json_eql(original_file_size.to_json).at_path('fileSize') }
- it { is_expected.to be_json_eql(original_digest.to_json).at_path('digest') }
-
- it_behaves_like 'API V3 formattable', 'description' do
- let(:format) { 'plain' }
- let(:raw) { original_description }
- end
- end
+ let(:representer) { described_class.new(metadata, current_user: current_user) }
describe 'parsing' do
let(:parsed_hash) do
{
- 'fileName' => 'the parsed name',
- 'description' => { 'raw' => 'the parsed description' },
- 'contentType' => 'text/html',
- 'fileSize' => 43,
- 'digest' => '0x00'
+ 'metadata' => {
+ 'fileName' => 'the parsed name',
+ 'description' => { 'raw' => 'the parsed description' },
+ 'contentType' => 'text/html',
+ 'fileSize' => 43,
+ 'digest' => '0x00'
+ }
}
end
@@ -84,10 +69,10 @@ describe ::API::V3::Attachments::AttachmentMetadataRepresenter do
representer.from_hash parsed_hash
end
- it { expect(subject.file_name).to eql('the parsed name') }
+ it { expect(subject.filename).to eql('the parsed name') }
it { expect(subject.description).to eql('the parsed description') }
it { expect(subject.content_type).to eql('text/html') }
- it { expect(subject.file_size).to eql(43) }
+ it { expect(subject.filesize).to eql(43) }
it { expect(subject.digest).to eql('0x00') }
end
end
diff --git a/spec/models/attachment_spec.rb b/spec/models/attachment_spec.rb
index 3a8b70d157c..0235a1c6c24 100644
--- a/spec/models/attachment_spec.rb
+++ b/spec/models/attachment_spec.rb
@@ -183,64 +183,6 @@ describe Attachment, type: :model do
end
end
- describe '.create_pending_direct_upload' do
- let(:file_size) { 6 }
- let(:file_name) { 'document.png' }
- let(:content_type) { "application/octet-stream" }
-
- subject do
- described_class.create_pending_direct_upload(file_name: file_name,
- author: author,
- container: container,
- content_type: content_type,
- file_size: file_size)
- end
-
- it 'returns the attachment' do
- expect(subject)
- .to be_a(Attachment)
- end
-
- it 'sets the content_type' do
- expect(subject.content_type)
- .to eql content_type
- end
-
- it 'sets the file_size' do
- expect(subject.filesize)
- .to eql file_size
- end
-
- it 'sets the file for carrierwave' do
- expect(subject.file.file.path)
- .to end_with "attachment/file/#{subject.id}/#{file_name}"
- end
-
- it 'sets the author' do
- expect(subject.author)
- .to eql author
- end
-
- it 'sets the digest to empty string' do
- expect(subject.digest)
- .to eql ""
- end
-
- it 'sets the download count to -1' do
- expect(subject.downloads)
- .to eql -1
- end
-
- context 'with a special character in the filename' do
- let(:file_name) { "document=number 5.png" }
-
- it 'sets the file for carrierwave' do
- expect(subject.file.file.path)
- .to end_with "attachment/file/#{subject.id}/document_number_5.png"
- end
- end
- end
-
##
# The tests assumes the default, file-based storage is configured and tests against that.
# I.e. it does not test fog attachments being deleted from the cloud storage (such as S3).
diff --git a/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb b/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb
index b0f9b3068de..2788b911f84 100644
--- a/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb
+++ b/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb
@@ -45,6 +45,7 @@ shared_examples 'it supports direct uploads' do
let(:request_parts) { { metadata: metadata.to_json, file: file } }
let(:metadata) { { fileName: 'cat.png', fileSize: file.size, contentType: 'image/png' } }
let(:file) { mock_uploaded_file(name: 'original-filename.txt') }
+ let(:json_response) { JSON.parse last_response.body }
def request!
post request_path, request_parts
@@ -57,8 +58,12 @@ shared_examples 'it supports direct uploads' do
request!
end
- it 'should respond with HTTP Not Found' do
- expect(subject.status).to eq(404)
+ it 'should respond with validation error' do
+ expect(subject.status).to eq(422)
+ end
+
+ it_behaves_like 'constraint violation' do
+ let(:message) { "is not available due to a system configuration" }
end
end
@@ -69,10 +74,15 @@ shared_examples 'it supports direct uploads' do
context 'with no filesize metadata' do
let(:metadata) { { fileName: 'cat.png' } }
+ let(:json) { JSON.parse subject.body }
it 'should respond with 422 due to missing file size metadata' do
expect(subject.status).to eq(422)
- expect(subject.body).to include 'fileSize'
+ expect(subject.body).to include 'Size'
+ end
+
+ it_behaves_like 'constraint violation' do
+ let(:message) { "Size #{I18n.t('activerecord.errors.messages.blank')}" }
end
end
@@ -255,7 +265,9 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
context 'metadata section is missing' do
let(:request_parts) { { file: file } }
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
+ it_behaves_like 'constraint violation' do
+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }
+ end
end
context 'file section is missing' do
@@ -263,7 +275,9 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
# however as long as we depend on correctly named sections this test should do just fine
let(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
+ it_behaves_like 'constraint violation' do
+ let(:message) { "Content type #{I18n.t('activerecord.errors.messages.blank')}" }
+ end
end
context 'metadata section is no valid JSON' do
@@ -276,12 +290,13 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
let(:metadata) { Hash.new }
it_behaves_like 'constraint violation' do
- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }
+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }
end
end
context 'file is too large' do
let(:file) { mock_uploaded_file(content: 'a' * 2.kilobytes) }
+
let(:expanded_localization) do
I18n.t('activerecord.errors.messages.file_too_large', count: max_file_size.kilobytes)
end
@@ -538,7 +553,11 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
context 'metadata section is missing' do
let(:request_parts) { { file: file } }
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
+ it_behaves_like 'constraint violation' do
+ # File here is the localized name for fileName property
+ # which is derived from the missing metadata
+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }
+ end
end
context 'file section is missing' do
@@ -546,7 +565,9 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
# however as long as we depend on correctly named sections this test should do just fine
let(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }
- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')
+ it_behaves_like 'constraint violation' do
+ let(:message) { "Content type #{I18n.t('activerecord.errors.messages.blank')}" }
+ end
end
context 'metadata section is no valid JSON' do
@@ -559,7 +580,7 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j
let(:metadata) { Hash.new }
it_behaves_like 'constraint violation' do
- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }
+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }
end
end
diff --git a/spec/services/attachments/create_service_integration_spec.rb b/spec/services/attachments/create_service_integration_spec.rb
index d683efde03e..ec8c03291f5 100644
--- a/spec/services/attachments/create_service_integration_spec.rb
+++ b/spec/services/attachments/create_service_integration_spec.rb
@@ -30,19 +30,25 @@
require 'spec_helper'
describe Attachments::CreateService, 'integration', with_settings: { journal_aggregation_time_minutes: 0 } do
- let(:user) { FactoryBot.create(:user) }
let(:description) { 'a fancy description' }
- subject { described_class.new(container, author: user) }
+ subject { described_class.new(user: user) }
describe '#call' do
def call_tested_method
- subject.call uploaded_file: FileHelpers.mock_uploaded_file(name: 'foobar.txt'),
+ subject.call container: container,
+ file: FileHelpers.mock_uploaded_file(name: 'foobar.txt'),
+ filename: 'foobar.txt',
description: description
end
context 'when journalized' do
- let(:container) { FactoryBot.create(:work_package) }
+ shared_let(:container) { FactoryBot.create(:work_package) }
+ shared_let(:user) do
+ FactoryBot.create :user,
+ member_in_project: container.project,
+ member_with_permissions: %i[view_work_packages edit_work_packages]
+ end
shared_examples 'successful creation' do
it 'saves the attachment' do
@@ -90,26 +96,22 @@ describe Attachments::CreateService, 'integration', with_settings: { journal_agg
end
context 'with an invalid attachment', with_settings: { attachment_max_size: 0 } do
- it 'raises the exception' do
+ it 'does not raise exceptions' do
expect { call_tested_method }
- .to raise_exception ActiveRecord::RecordInvalid
- end
-
- it 'does not create the attachment' do
- begin
- call_tested_method
- rescue ActiveRecord::RecordInvalid
- # expected
- end
+ .not_to raise_exception ActiveRecord::RecordInvalid
- expect(Attachment.count)
- .to eq 0
+ expect(call_tested_method.errors[:file]).to include "is too large (maximum size is 0 Bytes)."
end
end
end
context 'when not journalized' do
- let(:container) { FactoryBot.create(:message) }
+ shared_let(:container) { FactoryBot.create(:message) }
+ shared_let(:user) do
+ FactoryBot.create :user,
+ member_in_project: container.forum.project,
+ member_with_permissions: %i[add_messages edit_messages]
+ end
shared_examples 'successful creation' do
it 'saves the attachment' do
@@ -158,6 +160,7 @@ describe Attachments::CreateService, 'integration', with_settings: { journal_agg
context "when uncontainered" do
let(:container) { nil }
+ let(:user) { FactoryBot.create :admin }
before do
call_tested_method
@@ -169,5 +172,17 @@ describe Attachments::CreateService, 'integration', with_settings: { journal_agg
expect(attachment.description).to eq description
end
end
+
+ context "when user with no permissions" do
+ let(:container) { nil }
+ let(:user) { FactoryBot.build_stubbed :user }
+
+ it 'does not save an attachment' do
+ expect do
+ expect(call_tested_method).to be_failure
+ expect(call_tested_method.errors[:base]).to include 'may not be accessed.'
+ end.not_to change { Attachment.count }
+ end
+ end
end
end
diff --git a/spec/services/attachments/prepare_upload_service_integration_spec.rb b/spec/services/attachments/prepare_upload_service_integration_spec.rb
new file mode 100644
index 00000000000..8db117518fc
--- /dev/null
+++ b/spec/services/attachments/prepare_upload_service_integration_spec.rb
@@ -0,0 +1,98 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2020 the OpenProject GmbH
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License version 3.
+#
+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
+# Copyright (C) 2006-2013 Jean-Philippe Lang
+# Copyright (C) 2010-2013 the ChiliProject Team
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License
+# as published by the Free Software Foundation; either version 2
+# of the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# See docs/COPYRIGHT.rdoc for more details.
+
+require 'spec_helper'
+
+describe Attachments::PrepareUploadService,
+ 'integration' do
+ shared_let(:container) { FactoryBot.create(:work_package) }
+ shared_let(:user) do
+ FactoryBot.create :user,
+ member_in_project: container.project,
+ member_with_permissions: %i[view_work_packages edit_work_packages]
+ end
+ let(:instance) { described_class.new(user: user) }
+
+ let(:file_size) { 6 }
+ let(:file_name) { 'document.png' }
+ let(:content_type) { "application/octet-stream" }
+
+ let(:call) do
+ instance.call filename: file_name,
+ container: container,
+ content_type: content_type,
+ filesize: file_size
+ end
+
+ let(:attachment) { call.result }
+
+ it 'returns the attachment' do
+ expect(attachment)
+ .to be_a(Attachment)
+ end
+
+ it 'sets the content_type' do
+ expect(attachment.content_type)
+ .to eql content_type
+ end
+
+ it 'sets the file_size' do
+ expect(attachment.filesize)
+ .to eql file_size
+ end
+
+ it 'sets the file for carrierwave' do
+ expect(attachment.file.file.path)
+ .to end_with "attachment/file/#{attachment.id}/#{file_name}"
+ end
+
+ it 'sets the author' do
+ expect(attachment.author)
+ .to eql user
+ end
+
+ it 'sets the digest to empty string' do
+ expect(attachment.digest)
+ .to eql ""
+ end
+
+ it 'sets the download count to -1' do
+ expect(attachment.downloads)
+ .to eql -1
+ end
+
+ context 'with a special character in the filename' do
+ let(:file_name) { "document=number 5.png" }
+
+ it 'sets the file for carrierwave' do
+ expect(attachment.file.file.path)
+ .to end_with "attachment/file/#{attachment.id}/document_number_5.png"
+ end
+ end
+end
diff --git a/spec/support/shared/with_direct_uploads.rb b/spec/support/shared/with_direct_uploads.rb
index 280e3a99d20..ceee1aa2d4c 100644
--- a/spec/support/shared/with_direct_uploads.rb
+++ b/spec/support/shared/with_direct_uploads.rb
@@ -78,14 +78,13 @@ class WithDirectUploads
end
def mock_attachment
- allow(Attachment).to receive(:create) do |*args|
+ allow_any_instance_of(::Attachments::PrepareUploadService)
+ .to receive(:instance) do
# We don't use create here because this would cause an infinite loop as FogAttachment's #create
# uses the base class's #create which is what we are mocking here. All this is necessary to begin
# with because the Attachment class is initialized with the LocalFileUploader before this test
# is ever run and we need remote attachments using the FogFileUploader in this scenario.
- record = FogAttachment.new *args
- record.save
- record
+ FogAttachment.new
end
# This is so the uploaded callback works. Since we can't actually substitute the Attachment class
diff --git a/spec/workers/attachments/finish_direct_upload_job_integration_spec.rb b/spec/workers/attachments/finish_direct_upload_job_integration_spec.rb
index dc83bfc03ca..ea16e4d3099 100644
--- a/spec/workers/attachments/finish_direct_upload_job_integration_spec.rb
+++ b/spec/workers/attachments/finish_direct_upload_job_integration_spec.rb
@@ -48,8 +48,9 @@ describe Attachments::FinishDirectUploadJob, 'integration', type: :job do
expect(attachment.downloads)
.to eql(0)
+ # expect to replace the content type with the actual value
expect(attachment.content_type)
- .to eql('application/binary')
+ .to eql('text/plain')
expect(attachment.digest)
.to eql("9473fdd0d880a43c21b7778d34872157")
end
diff --git a/spec/workers/backup_job_spec.rb b/spec/workers/backup_job_spec.rb
index 03e1c867136..3af5c101394 100644
--- a/spec/workers/backup_job_spec.rb
+++ b/spec/workers/backup_job_spec.rb
@@ -59,7 +59,7 @@ describe BackupJob, type: :model do
let(:arguments) { [{ backup: backup, user: user, **opts }] }
- let(:user) { FactoryBot.create :user }
+ let(:user) { FactoryBot.create :admin }
before do
previous_backup; backup; status # create
diff --git a/spec/workers/extract_fulltext_job_spec.rb b/spec/workers/extract_fulltext_job_spec.rb
index 802b72b53af..1267ebaac83 100644
--- a/spec/workers/extract_fulltext_job_spec.rb
+++ b/spec/workers/extract_fulltext_job_spec.rb
@@ -31,86 +31,89 @@
require 'spec_helper'
describe ExtractFulltextJob, type: :job do
- # These jobs only get created when TSVector is supported by the DB.
- if OpenProject::Database.allows_tsv?
- let(:text) { 'lorem ipsum' }
- let(:attachment) do
- FactoryBot.create(:attachment).tap do |attachment|
- expect(ExtractFulltextJob)
- .to have_been_enqueued
- .with(attachment.id)
-
- perform_enqueued_jobs
-
- attachment.reload
- end
+ let(:text) { 'lorem ipsum' }
+ let(:attachment) do
+ FactoryBot.create(:attachment).tap do |attachment|
+ expect(ExtractFulltextJob)
+ .to have_been_enqueued
+ .with(attachment.id)
end
+ end
+
+ let(:subject) do
+ perform_enqueued_jobs
+
+ attachment.reload
+ end
+
+ before do
+ allow(Attachment).to receive(:find_by).with(id: attachment.id).and_return(attachment)
+ end
- context "with successful text extraction" do
+ context "with successful text extraction" do
+ before do
+ allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_return(text)
+ end
+
+ context 'attachment is readable' do
before do
- allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_return(text)
+ allow(attachment).to receive(:readable?).and_return(true)
+ subject
end
- context 'attachment is readable' do
- before do
- allow(attachment).to receive(:readable?).and_return(true)
- attachment.reload
- end
-
- it 'updates the attachment\'s DB record with fulltext, fulltext_tsv, and file_tsv' do
- expect(attachment.fulltext).to eq text
- expect(attachment.fulltext_tsv.size).to be > 0
- expect(attachment.file_tsv.size).to be > 0
- end
+ it 'updates the attachment\'s DB record with fulltext, fulltext_tsv, and file_tsv' do
+ expect(attachment.fulltext).to eq text
+ expect(attachment.fulltext_tsv.size).to be > 0
+ expect(attachment.file_tsv.size).to be > 0
+ end
- # shared_examples 'no fulltext but file name saved as TSV' do
- # end
+ # shared_examples 'no fulltext but file name saved as TSV' do
+ # end
- context 'No content was extracted' do
- let(:text) { nil }
+ context 'No content was extracted' do
+ let(:text) { nil }
- # include_examples 'no fulltext but file name saved as TSV'
- it 'updates the attachment\'s DB record with file_tsv' do
- expect(attachment.fulltext).to be_blank
- expect(attachment.fulltext_tsv).to be_blank
- expect(attachment.file_tsv.size).to be > 0
- end
+ # include_examples 'no fulltext but file name saved as TSV'
+ it 'updates the attachment\'s DB record with file_tsv' do
+ expect(attachment.fulltext).to be_blank
+ expect(attachment.fulltext_tsv).to be_blank
+ expect(attachment.file_tsv.size).to be > 0
end
end
end
+ end
- shared_examples 'only file name indexed' do
- it 'updates the attachment\'s DB record with file_tsv' do
- expect(attachment.fulltext).to be_blank
- expect(attachment.fulltext_tsv).to be_blank
- expect(attachment.file_tsv.size).to be > 0
- end
+ shared_examples 'only file name indexed' do
+ it 'updates the attachment\'s DB record with file_tsv' do
+ expect(attachment.fulltext).to be_blank
+ expect(attachment.fulltext_tsv).to be_blank
+ expect(attachment.file_tsv.size).to be > 0
end
+ end
- context 'file not readable' do
- before do
- allow(attachment).to receive(:readable?).and_return(false)
- attachment.reload
- end
-
- include_examples 'only file name indexed'
+ context 'file not readable' do
+ before do
+ allow(attachment).to receive(:readable?).and_return(false)
+ subject
end
- context 'with exception in extraction' do
- let(:exception_message) { 'boom-internal-error' }
- let(:logger) { Rails.logger }
+ include_examples 'only file name indexed'
+ end
- before do
- allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_raise(exception_message)
+ context 'with exception in extraction' do
+ let(:exception_message) { 'boom-internal-error' }
+ let(:logger) { Rails.logger }
- # This line is actually part of the test. `expect` call needs to go so far up here, as we want to verify that a message gets logged.
- expect(logger).to receive(:error).with(/boom-internal-error/)
+ before do
+ allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_raise(exception_message)
- allow(attachment).to receive(:readable?).and_return(true)
- attachment.reload
- end
+ # This line is actually part of the test. `expect` call needs to go so far up here, as we want to verify that a message gets logged.
+ expect(logger).to receive(:error).with(/boom-internal-error/)
- include_examples 'only file name indexed'
+ allow(attachment).to receive(:readable?).and_return(true)
+ subject
end
+
+ include_examples 'only file name indexed'
end
end
diff --git a/spec/workers/work_packages/exports/export_job_spec.rb b/spec/workers/work_packages/exports/export_job_spec.rb
index e9ae9a9a51f..48ed7ffd6cd 100644
--- a/spec/workers/work_packages/exports/export_job_spec.rb
+++ b/spec/workers/work_packages/exports/export_job_spec.rb
@@ -68,22 +68,22 @@ describe WorkPackages::Exports::ExportJob do
service = double('attachments create service')
expect(Attachments::CreateService)
- .to receive(:new)
- .with(export, author: user)
+ .to receive(:bypass_whitelist)
+ .with(user: user)
.and_return(service)
expect(WorkPackages::Exports::CleanupOutdatedJob)
.to receive(:perform_after_grace)
expect(service)
- .to receive(:call) do |uploaded_file:, description:|
- expect(File.basename(uploaded_file))
+ .to receive(:call) do |file:, **args|
+ expect(File.basename(file))
.to start_with 'some_title'
- expect(File.basename(uploaded_file))
+ expect(File.basename(file))
.to end_with ".#{mime_type}"
- attachment
+ ServiceResult.new(result: attachment, success: true)
end
allow("WorkPackage::Exporter::#{mime_type.upcase}".constantize)