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
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Implementation/48289 add automatic project folder management settings for storages (#12721)
Kabiru Mwenja74cfc0aac929
diff --git a/Gemfile b/Gemfileindex 9a2f017db9b..75da253a799 100644--- a/Gemfile+++ b/Gemfile@@ -202,6 +202,9 @@ gem 'mini_magick', '~> 4.12.0', require: falsegem 'validate_url'+# ActiveRecord extension which adds typecasting to store accessors+gem "store_attribute", "~> 1.0"+# Appsignal integrationgem "appsignal", "~> 3.0", require: falsediff --git a/Gemfile.lock b/Gemfile.lockindex 4a49a8a022d..42d23e0a585 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -917,6 +917,8 @@ GEMsprockets (>= 3.0.0)ssrf_filter (1.1.1)stackprof (0.2.25)+ store_attribute (1.1.0)+ activerecord (>= 6.0)stringex (2.8.6)stringio (3.0.7)structured_warnings (0.4.0)@@ -1155,6 +1157,7 @@ DEPENDENCIESsprockets (~> 3.7.2)sprockets-rails (~> 3.4.2)stackprof+ store_attribute (~> 1.0)stringex (~> 2.8.5)structured_warnings (~> 0.4.0)svg-graph (~> 2.2.0)diff --git a/docs/api/apiv3/components/schemas/storage_read_model.yml b/docs/api/apiv3/components/schemas/storage_read_model.ymlindex 72ec31d0ebc..4ebcfaf19a1 100644--- a/docs/api/apiv3/components/schemas/storage_read_model.yml+++ b/docs/api/apiv3/components/schemas/storage_read_model.yml@@ -17,6 +17,12 @@ properties:name:type: stringdescription: Storage name+ hasApplicationPassword:+ type: boolean+ description: |-+ Whether the storage has the application password to use for the Nextcloud storage.++ Ignored if the provider type is not NextcloudcreatedAt:type: stringformat: date-time@@ -77,24 +83,24 @@ properties:- $ref: './link.yml'- description: |-The urn of the storage connection state. Can be one of:-+- urn:openproject-org:api:v3:storages:authorization:Connected- urn:openproject-org:api:v3:storages:authorization:FailedAuthorization- urn:openproject-org:api:v3:storages:authorization:Error-+**Resource**: N/Aauthorize:allOf:- $ref: './link.yml'- description: |-The link to the starting point of the authorization cycle for a configured storage provider.-+# Conditions-+`authorizationState` is:-+- urn:openproject-org:api:v3:storages:authorization:FailedAuthorization-+**Resource**: N/AoauthApplication:allOf:@@ -122,6 +128,7 @@ example:id: 1337_type: Storagename: It's no moon+ hasApplicationPassword: truecreatedAt: '2021-12-20T13:37:00.211Z'updatedAt: '2021-12-20T13:37:00.211Z'_links:diff --git a/docs/api/apiv3/components/schemas/storage_write_model.yml b/docs/api/apiv3/components/schemas/storage_write_model.ymlindex 0d16c3141ff..441e422e82c 100644--- a/docs/api/apiv3/components/schemas/storage_write_model.yml+++ b/docs/api/apiv3/components/schemas/storage_write_model.yml@@ -5,6 +5,15 @@ properties:name:type: stringdescription: Storage name, if not provided, falls back to a default.+ applicationPassword:+ type:+ - string+ - 'null'+ description: |-+ The application password to use for the Nextcloud storage. Ignored if the provider type is not Nextcloud.++ If a string is provided, the password is set and automatic management is enabled for the storage.+ If null is provided, the password is unset and automatic management is disabled for the storage._links:type: objectrequired:@@ -23,13 +32,14 @@ properties:- $ref: './link.yml'- description: |-The urn of the storage type. Currently only nextcloud storages are supported.-+- urn:openproject-org:api:v3:storages:Nextcloud**Resource**: N/Aexample:name: Coruscant+ applicationPassword: 'qJ_VLNReW@sd-Edz2hyC'_links:origin:href: https://nextcloud.deathstar.rocksdiff --git a/frontend/src/app/spot/components/switch/switch.component.html b/frontend/src/app/spot/components/switch/switch.component.htmlindex 637a1c81a4f..053a87537b1 100644--- a/frontend/src/app/spot/components/switch/switch.component.html+++ b/frontend/src/app/spot/components/switch/switch.component.html@@ -5,6 +5,7 @@[disabled]="disabled"[tabindex]="tabindex"[ngModel]="checked"+ [value]="checked"(ngModelChange)="onToggle($event)"#input/>diff --git a/frontend/src/stimulus/controllers/dynamic/storages/automatically-managed-project-folders-form.controller.ts b/frontend/src/stimulus/controllers/dynamic/storages/automatically-managed-project-folders-form.controller.tsnew file mode 100644index 00000000000..56f0c0b5cf1--- /dev/null+++ b/frontend/src/stimulus/controllers/dynamic/storages/automatically-managed-project-folders-form.controller.ts@@ -0,0 +1,67 @@+/*+ * -- copyright+ * OpenProject is an open source project management software.+ * Copyright (C) 2023 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 COPYRIGHT and LICENSE files for more details.+ * +++ */++import { Controller } from '@hotwired/stimulus';++export default class AutomaticallyManagedProjectFoldersFormController extends Controller {+ static targets = [+ 'applicationPasswordInput',+ ];++ static values = {+ isAutomaticallyManaged: Boolean,+ };++ declare readonly applicationPasswordInputTarget:HTMLElement;+ declare readonly hasApplicationPasswordInputTarget:boolean;++ declare isAutomaticallyManagedValue:boolean;++ connect():void {+ // On first load if isAutomaticallyManaged is true, show the applicationPasswordInput+ this.toggleApplicationPasswordDisplay(this.isAutomaticallyManagedValue);+ }++ public updateDisplay(evt:Event):void {+ this.toggleApplicationPasswordDisplay((evt.target as HTMLInputElement).checked);+ }++ toggleApplicationPasswordDisplay(displayApplicationPasswordInput:boolean):void {+ if (!this.hasApplicationPasswordInputTarget) {+ return;+ }++ if (displayApplicationPasswordInput) {+ this.applicationPasswordInputTarget.style.display = 'flex';+ } else {+ this.applicationPasswordInputTarget.style.display = 'none';+ }+ }+}diff --git a/modules/storages/app/contracts/storages/storages/base_contract.rb b/modules/storages/app/contracts/storages/storages/base_contract.rbindex 275ff14f7d9..2ea7b6f3658 100644--- a/modules/storages/app/contracts/storages/storages/base_contract.rb+++ b/modules/storages/app/contracts/storages/storages/base_contract.rb@@ -51,5 +51,35 @@ module Storages::Storages# Check that a host actually is a storage server.# But only do so if the validations above for URL were successful.validates :host, secure_context_uri: true, nextcloud_compatible_host: true, unless: -> { errors.include?(:host) }++ attribute :provider_fields+ attribute :automatically_managed++ attribute :username+ validates :username, presence: true, if: :nextcloud_storage_automatically_managed?+ validates :username, absence: true,+ unless: -> { nextcloud_storage_automatically_managed? || nextcloud_default_storage_username? }++ attribute :password+ validates :password, presence: true, if: :nextcloud_storage_automatically_managed?+ validates :password, absence: true, unless: :nextcloud_storage_automatically_managed?++ private++ def nextcloud_storage_automatically_managed?+ return false unless nextcloud_storage?++ @model.automatically_managed?+ end++ def nextcloud_default_storage_username?+ return false unless nextcloud_storage?++ @model.username == @model.provider_fields_defaults[:username]+ end++ def nextcloud_storage?+ @model.is_a?(Storages::NextcloudStorage)+ endendenddiff --git a/modules/storages/app/controllers/storages/admin/automatically_managed_project_folders_controller.rb b/modules/storages/app/controllers/storages/admin/automatically_managed_project_folders_controller.rbnew file mode 100644index 00000000000..953168cdbc2--- /dev/null+++ b/modules/storages/app/controllers/storages/admin/automatically_managed_project_folders_controller.rb@@ -0,0 +1,130 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 COPYRIGHT and LICENSE files for more details.+#++++# Purpose: Let OpenProject create folders per project automatically.+# This is recommended as it ensures that every team member always has the correct access permissions.+#+class Storages::Admin::AutomaticallyManagedProjectFoldersController < ApplicationController+ # See https://guides.rubyonrails.org/layouts_and_rendering.html for reference on layout+ layout 'admin'++ # Before executing any action below: Make sure the current user is an admin+ # and set the @<controller_name> variable to the object referenced in the URL.+ before_action :require_admin++ # specify which model #find_model_object should look up+ model_object Storages::NextcloudStorage+ before_action :find_model_object, only: %i[new edit update]++ # menu_item is defined in the Redmine::MenuManager::MenuController+ # module, included from ApplicationController.+ # The menu item is defined in the engine.rb+ menu_item :storages_admin_settings++ # Show the admin page to set storage folder automatic management (for an already existing storage).+ # Sets the attributes automatically_managed as default true unless already set to false+ # renders a form (allowing the user to change automatically_managed bool and password).+ # Used by: The OauthClientsController#create, after the user inputs Oauth credentials for the first time.+ # Called by: Global app/config/routes.rb to serve Web page+ def new+ # Set default parameters using a "service".+ # See also: storages/services/storages/storages/set_attributes_services.rb+ # That service inherits from ::BaseServices::SetAttributes+ @storage = ::Storages::Storages::SetNextcloudProviderFieldsAttributesService+ .new(user: current_user,+ model: @object,+ contract_class: ::Storages::Storages::BaseContract)+ .call+ .result+ render '/storages/admin/storages/automatically_managed_project_folders/edit'+ end++ # Renders an edit page (allowing the user to change automatically_managed bool and password).+ # Used by: The StoragesController#edit, when user wants to update application credentials.+ # Called by: Global app/config/routes.rb to serve Web page+ def edit+ render '/storages/admin/storages/automatically_managed_project_folders/edit'+ end++ # Update is similar to create above+ # See also: create above+ # Called by: Global app/config/routes.rb to serve Web page+ def update+ service_result = ::Storages::Storages::UpdateService+ .new(user: current_user,+ model: @storage)+ .call(permitted_storage_params_with_defaults)++ if service_result.success?+ flash[:notice] = I18n.t(:notice_successful_update)+ redirect_to admin_settings_storage_path(@storage)+ else+ @errors = service_result.errors+ render '/storages/admin/storages/automatically_managed_project_folders/edit'+ end+ end++ # Used by: admin layout+ # Breadcrumbs is something like OpenProject > Admin > Storages.+ # This returns the name of the last part (Storages admin page)+ def default_breadcrumb+ ActionController::Base.helpers.link_to(t(:project_module_storages), admin_settings_storages_path)+ end++ # See: default_breadcrum above+ # Defines whether to show breadcrumbs on the page or not.+ def show_local_breadcrumb+ true+ end++ private++ # Override default url param `:id` to `:storage` controller is a nested storage resource+ # GET /admin/settings/storages/:storage_id/automatically_managed_project_folders/new+ # POST /admin/settings/storages/:storage_id/automatically_managed_project_folders+ def find_model_object(object_id = :storage_id)+ super(object_id)+ @storage = @object+ end++ def permitted_storage_params_with_defaults+ permitted_storage_params.tap do |permitted_params|+ # If a checkbox is unchecked when its form is submitted, neither the name nor the value is submitted to the server.+ # See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox+ permitted_params.merge!(automatically_managed: false) unless permitted_params.key?('automatically_managed')+ end+ end++ # Called by create and update above in order to check if the+ # update parameters are correctly set.+ def permitted_storage_params+ params+ .require(:storages_nextcloud_storage)+ .permit('automatically_managed', 'password')+ end+enddiff --git a/modules/storages/app/controllers/storages/admin/oauth_clients_controller.rb b/modules/storages/app/controllers/storages/admin/oauth_clients_controller.rbindex 71b3e8b6984..daacecbddc7 100644--- a/modules/storages/app/controllers/storages/admin/oauth_clients_controller.rb+++ b/modules/storages/app/controllers/storages/admin/oauth_clients_controller.rb@@ -55,14 +55,17 @@ class Storages::Admin::OAuthClientsController < ApplicationController# Actually create a OAuthClient object.# Use service pattern to create a new OAuthClient# Called by: Global app/config/routes.rb to serve Web page- def create+ def create # rubocop:disable Metrics/AbcSizeservice_result = ::OAuthClients::CreateService.new(user: User.current).call(permitted_oauth_client_params.merge(integration: @storage))@oauth_client = service_result.resultif service_result.success?flash[:notice] = I18n.t(:notice_successful_create)- # admin_settings_storage_path is automagically created by Ruby routes.- redirect_to admin_settings_storage_path(@storage)+ if OpenProject::FeatureDecisions.automatically_managed_project_folders_active? && @storage.automatic_management_unspecified?+ redirect_to new_admin_settings_storage_automatically_managed_project_folders_path(@storage)+ else+ redirect_to admin_settings_storage_path(@storage)+ endelse@errors = service_result.errorsrender '/storages/admin/storages/new_oauth_client'diff --git a/modules/storages/app/models/storages/nextcloud_storage.rb b/modules/storages/app/models/storages/nextcloud_storage.rbindex 1efe93def2e..acd2d42025b 100644--- a/modules/storages/app/models/storages/nextcloud_storage.rb+++ b/modules/storages/app/models/storages/nextcloud_storage.rb@@ -27,14 +27,16 @@#++class Storages::NextcloudStorage < Storages::Storage- store_accessor :provider_fields,- %i[username- password- group- group_folder- has_managed_project_folders]+ PROVIDER_FIELDS_DEFAULTS = {+ automatically_managed: true,+ username: 'OpenProject'+ }.freeze- alias_method :has_managed_project_folders?, :has_managed_project_folders+ store_attribute :provider_fields, :automatically_managed, :boolean+ store_attribute :provider_fields, :username, :string+ store_attribute :provider_fields, :password, :string+ store_attribute :provider_fields, :group, :string+ store_attribute :provider_fields, :group_folder, :stringdef self.sync_all_group_folders# Returns false if lock cannot be acquired, block is not executed then.@@ -42,7 +44,7 @@ class Storages::NextcloudStorage < Storages::Storage'sync_all_group_folders',timeout_seconds: 0,transaction: false) do- where("provider_fields->>'has_managed_project_folders' = 'true'")+ where("provider_fields->>'automatically_managed' = 'true'").includes(:oauth_client).each do |storage|Storages::GroupFolderPropertiesSyncService.new(storage).call@@ -51,25 +53,17 @@ class Storages::NextcloudStorage < Storages::Storageendend- def group- super || "OpenProject"+ def automatic_management_unspecified?+ automatically_managed.nil?end- def group_folder- super || "OpenProject"- end-- def username- super || "OpenProject"- end-- def has_managed_project_folders=(value)- super(!!value)+ %i[username group group_folder].each do |attribute_method|+ define_method(attribute_method) do+ super().presence || PROVIDER_FIELDS_DEFAULTS[:username]+ endend- # rubocop:disable Naming/PredicateName- def has_managed_project_folders- !!super+ def provider_fields_defaults+ PROVIDER_FIELDS_DEFAULTSend- # rubocop:enable Naming/PredicateNameenddiff --git a/modules/storages/app/models/storages/storage.rb b/modules/storages/app/models/storages/storage.rbindex 07191f810b5..49e717d3a56 100644--- a/modules/storages/app/models/storages/storage.rb+++ b/modules/storages/app/models/storages/storage.rb@@ -94,4 +94,8 @@ class Storages::Storage < ApplicationRecorddef short_provider_type@short_provider_type ||= self.class.shorten_provider_type(provider_type)end++ def provider_type_nextcloud?+ provider_type == ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD+ endenddiff --git a/modules/storages/app/services/storages/storages/create_service.rb b/modules/storages/app/services/storages/storages/create_service.rbindex 03c599007f5..0263f26a1e8 100644--- a/modules/storages/app/services/storages/storages/create_service.rb+++ b/modules/storages/app/services/storages/storages/create_service.rb@@ -42,7 +42,7 @@ module Storages::Storagesstorage = service_call.result# Automatically create an OAuthApplication object for the Nextcloud storage# using values from storage (particularly :host) as defaults- if storage.provider_type == Storages::Storage::PROVIDER_TYPE_NEXTCLOUD+ if storage.provider_type_nextcloud?persist_service_result = ::Storages::OAuthApplications::CreateService.new(storage:, user:).callstorage.oauth_application = persist_service_result.result if persist_service_result.success?service_call.add_dependent!(persist_service_result)@@ -50,5 +50,14 @@ module Storages::Storagesservice_callend++ # @override BaseServices::Create#instance to return a Storages::{ProviderType}Storage class name+ # At this stage, the model contract has already been validated, so we can be sure of the provider_type presence+ # @example instance_klass = Storages::NextcloudStorage+ #+ def instance(params)+ instance_klass = params[:provider_type].constantize+ instance_klass.new+ endendenddiff --git a/modules/storages/app/services/storages/storages/set_attributes_service.rb b/modules/storages/app/services/storages/storages/set_attributes_service.rbindex f7d2a73b2b1..3ff6736b489 100644--- a/modules/storages/app/services/storages/storages/set_attributes_service.rb+++ b/modules/storages/app/services/storages/storages/set_attributes_service.rb@@ -38,10 +38,25 @@ module Storages::Storagesprivate+ def set_attributes(params)+ super(params)+ unset_nextcloud_application_credentials if nextcloud_storage?+ end+def remove_host_trailing_slashesstorage.host = storage.host&.gsub(/\/+$/, '')end+ def unset_nextcloud_application_credentials+ # Do not overwrite if has never been set.+ # E.g. when setting up a new storage for the first time, passthrough, credentials are set in a later stage.+ return if storage.automatic_management_unspecified?++ unless storage.automatically_managed?+ %w[username password].each { |field| storage.provider_fields.delete(field) }+ end+ end+def storagemodelend@@ -54,5 +69,9 @@ module Storages::Storages"#{prefix} #{last_id + 1}"end++ def nextcloud_storage?+ storage.is_a?(Storages::NextcloudStorage)+ endendenddiff --git a/modules/storages/app/services/storages/storages/set_nextcloud_provider_fields_attributes_service.rb b/modules/storages/app/services/storages/storages/set_nextcloud_provider_fields_attributes_service.rbnew file mode 100644index 00000000000..f7a889d0546--- /dev/null+++ b/modules/storages/app/services/storages/storages/set_nextcloud_provider_fields_attributes_service.rb@@ -0,0 +1,51 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 COPYRIGHT and LICENSE files for more details.+#++++# Used by Storages::ManagedProjectFoldersController#new to set the default values for the provider fields+# when creating a new storage for the first time. These attributes are only for building the view and are not enforced+# by the model.+module Storages::Storages+ class SetNextcloudProviderFieldsAttributesService < ::BaseServices::SetAttributes+ def set_default_provider_fields(_params)+ if storage.automatic_management_unspecified?+ storage.automatically_managed = storage.provider_fields_defaults[:automatically_managed]+ end+ end++ private++ def set_attributes(params)+ super(params)+ set_default_provider_fields(params)+ end++ def storage+ model+ end+ end+enddiff --git a/modules/storages/app/services/storages/storages/update_service.rb b/modules/storages/app/services/storages/storages/update_service.rbindex d6bd01ed1c1..88c66f41c7a 100644--- a/modules/storages/app/services/storages/storages/update_service.rb+++ b/modules/storages/app/services/storages/storages/update_service.rb@@ -35,7 +35,7 @@ module Storages::Storagessuper(service_call)storage = service_call.result- if storage.provider_type == ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD+ if storage.provider_type_nextcloud?application = storage.oauth_applicationpersist_service_result = ::OAuth::PersistApplicationService.new(application, user:)diff --git a/modules/storages/app/views/storages/admin/storages/automatically_managed_project_folders/edit.html.erb b/modules/storages/app/views/storages/admin/storages/automatically_managed_project_folders/edit.html.erbnew file mode 100644index 00000000000..eaa0bc57022--- /dev/null+++ b/modules/storages/app/views/storages/admin/storages/automatically_managed_project_folders/edit.html.erb@@ -0,0 +1,105 @@+<%#-- copyright+OpenProject is an open source project management software.+Copyright (C) 2012-2023 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 COPYRIGHT and LICENSE files for more details.++++#%>++<% html_title t(:label_administration), t("project_module_storages"), @storage.name, t("storages.page_titles.managed_project_folders.title") %>+<% local_assigns[:additional_breadcrumb] = [+ link_to(@storage.name, admin_settings_storage_path(@storage)),+ t("storages.label_managed_project_folders_breadcrumb")+] %>+<%= toolbar title: t("storages.page_titles.managed_project_folders.title"),+ subtitle: t("storages.page_titles.managed_project_folders.subtitle")+%>++<%= error_messages_for_contract @storage, @errors %>++<%= labelled_tabular_form_for @storage, url: admin_settings_storage_automatically_managed_project_folders_path(@storage),+ method: :patch,+ data: {+ controller: "storages--automatically-managed-project-folders-form",+ 'application-target': "dynamic",+ 'storages--automatically-managed-project-folders-form-is-automatically-managed-value': @storage.automatically_managed?,+ } do |f| -%>+ <div class="form--field -required">+ <%= styled_label_tag :automatically_managed, class: "-bold -flex" do %>+ <%= t(:"storages.label_managed_project_folders.automatically_managed_folders") %>+ <% end %>++ <div class="form--field-container -horizontal">+ <label class="form--label -flex">+ <%= angular_component_tag 'spot-switch',+ inputs: {+ id: "storages_#{@storage.short_provider_type}_storage_automatically_managed",+ name: "storages_#{@storage.short_provider_type}_storage[automatically_managed]",+ checked: @storage.automatically_managed?,+ },+ data: {+ action: 'change->storages--automatically-managed-project-folders-form#updateDisplay',+ }+ %>+ </label>+ </div>+ </div>++ <div class="form--field -required"+ data-storages--automatically-managed-project-folders-form-target="applicationPasswordInput">+ <label class="form--label -bold"> <%= t(:"storages.label_managed_project_folders.application_password") %> </label>+ <div class="form--field-container -horizontal">+ <%= f.text_field :password,+ container_class: "-middle",+ no_label: true,+ value: nil, # IMPORTANT: We don't want to show the password in the form+ placeholder: @storage.password.present? ? "●●●●●●●●●●●●●●●●" : nil+ %>+ </div>+ <p class="form--field-instructions -xwide">+ <%= t(:"storages.instructions.managed_project_folders_application_password") %>+ <a+ href="<%= URI.join(@storage.oauth_application.integration.host, 'settings/admin/openproject') %>"+ target="_blank"+ class="spot-link"+ >+ <span><%= t("storages.instructions.#{@storage.short_provider_type}.integration") %></span>+ </a>+ </p>+ </div>++ <div class="form--field">+ <% case action_name %>+ <% when 'new' %>+ <%= styled_button_tag t("storages.buttons.done_complete_setup"), class: "-highlight -with-icon icon-checkmark" %>+ <% else %>+ <%= styled_button_tag t("storages.buttons.save"), class: "-highlight -with-icon icon-checkmark" %>+ <% end %>++ <%= link_to admin_settings_storage_path(@storage), class: 'button' do %>+ <%= spot_icon('cancel') %>+ <%= content_tag :span, t(:button_cancel) %>+ <% end %>+ </div>+<% end %>diff --git a/modules/storages/app/views/storages/admin/storages/edit.html.erb b/modules/storages/app/views/storages/admin/storages/edit.html.erbindex 28c932a02c8..f9c23388fc3 100644--- a/modules/storages/app/views/storages/admin/storages/edit.html.erb+++ b/modules/storages/app/views/storages/admin/storages/edit.html.erb@@ -46,3 +46,29 @@<%= link_to(t("js.label_create"), new_admin_settings_storage_oauth_client_path(@object), class: 'button -with-icon icon-add') %><% end %><% end %>++<% if OpenProject::FeatureDecisions.automatically_managed_project_folders_active? %>+ <%= render(AttributeGroups::AttributeGroupComponent.new) do |component| %>+ <% component.with_header(title: t("storages.page_titles.managed_project_folders.title")) %>++ <% if @object.automatic_management_unspecified? %>+ <%= link_to(t("storages.buttons.configure"), new_admin_settings_storage_automatically_managed_project_folders_path(@object), class: 'button -with-icon icon-add') %>+ <% else %>+ <% component.with_attribute(+ key: t(:"storages.label_managed_project_folders.automatically_managed_folders"),+ value: @object.automatically_managed? ? t(:"storages.label_active") : t(:"storages.label_inactive")+ ) %>++ <% if @object.automatically_managed? %>+ <% component.with_attribute(+ key: t(:"storages.label_managed_project_folders.application_password"),+ value: "●●●●●●●●●●●●●●●●"+ ) %>+ <% end %>++ <%= link_to(t("storages.buttons.edit_automatically_managed_project_folders"),+ edit_admin_settings_storage_automatically_managed_project_folders_path(@object),+ class: 'button -with-icon icon-edit') %>+ <% end %>+ <% end %>+<% end %>diff --git a/modules/storages/app/views/storages/admin/storages/new_oauth_client.html.erb b/modules/storages/app/views/storages/admin/storages/new_oauth_client.html.erbindex 8dff7453605..e07ad4ee8d1 100644--- a/modules/storages/app/views/storages/admin/storages/new_oauth_client.html.erb+++ b/modules/storages/app/views/storages/admin/storages/new_oauth_client.html.erb@@ -39,7 +39,8 @@<% if @storage.oauth_client %><%= styled_button_tag t(:button_replace), class: "-highlight -with-icon icon-checkmark" %><% else %>- <%= styled_button_tag t("storages.buttons.save_and_complete_setup"), class: "-highlight -with-icon icon-checkmark" %>+ <% label_action = @storage.automatic_management_unspecified? ? 'continue' : 'complete' %>+ <%= styled_button_tag t("storages.buttons.save_and_#{label_action}_setup"), class: "-highlight -with-icon icon-checkmark" %><% end %><% end %>diff --git a/modules/storages/app/views/storages/admin/storages/show.html.erb b/modules/storages/app/views/storages/admin/storages/show.html.erbindex 6ec1830fe43..426af414e7c 100644--- a/modules/storages/app/views/storages/admin/storages/show.html.erb+++ b/modules/storages/app/views/storages/admin/storages/show.html.erb@@ -97,3 +97,25 @@ See COPYRIGHT and LICENSE files for more details.<% t(:'storages.oauth_client_details_missing') %><% end %><% end %>++<% if OpenProject::FeatureDecisions.automatically_managed_project_folders_active? %>+ <%= render(AttributeGroups::AttributeGroupComponent.new) do |component| %>+ <% component.with_header(title: t("storages.page_titles.managed_project_folders.title")) %>++ <% if @object.automatic_management_unspecified? %>+ <%= t("storages.automatically_managed_project_folder_missing") %>+ <% else %>+ <% component.with_attribute(+ key: t(:"storages.label_managed_project_folders.automatically_managed_folders"),+ value: @object.automatically_managed? ? t(:"storages.label_active") : t(:"storages.label_inactive")+ ) %>++ <% if @object.automatically_managed? %>+ <% component.with_attribute(+ key: t(:"storages.label_managed_project_folders.application_password"),+ value: "●●●●●●●●●●●●●●●●"+ ) %>+ <% end %>+ <% end %>+ <% end %>+<% end %>diff --git a/modules/storages/config/locales/en.yml b/modules/storages/config/locales/en.ymlindex 2ee9aff3157..ff6865d1ed0 100644--- a/modules/storages/config/locales/en.yml+++ b/modules/storages/config/locales/en.yml@@ -50,12 +50,19 @@ en:storages:buttons:done_continue_setup: "Done. Continue setup"+ done_complete_setup: "Done, complete setup"+ edit_automatically_managed_project_folders: "Edit automatically managed project folders"replace_openproject_oauth: "Replace OpenProject OAuth"replace_provider_type_oauth: "Replace %{provider_type} OAuth"save_and_continue_setup: "Save and continue setup"save_and_complete_setup: "Save and complete setup"select_folder: "Select folder"+ configure: "Configure"page_titles:+ managed_project_folders:+ title: "Automatically managed project folders"+ subtitle: >+ Let OpenProject create folders per project automatically. This is recommended as it ensures that every team member always has the correct access permissions.project_settings:index: "File storages available in this project"new: "Add a file storage to this project"@@ -65,6 +72,8 @@ en:type_link_text: "“Integration OpenProject”"name: "Give your storage a name so that users can differentiate between multiple storages."host: "Please add the host address of your storage including the https://. It should not be longer than 255 characters."+ managed_project_folders_application_password: >+ Copy this value from:no_storage_set_up: "There are no file storages set up yet."no_specific_folder: "By default, each user will start at their own home folder when they upload a file."automatic_folder: "This will automatically create a root folder for this project and manage the access permissions for each project member."@@ -92,11 +101,17 @@ en:project_storage: >Are you sure you want to remove this file storage from this project? This will alsoremove all links to files stored in this storage for this project.+ label_active: "Active"+ label_inactive: "Inactive"label_creator: "Creator"label_file_link: "File link"label_file_links: "File links"label_name: "Name"label_host: "Host URL"+ label_managed_project_folders:+ automatically_managed_folders: "Automatically managed folders"+ application_password: "Application password"+ label_managed_project_folders_breadcrumb: "Automatically managed project folders"label_oauth_breadcrumb:openproject: "OpenProject OAuth"nextcloud: "Nextcloud OAuth"@@ -121,4 +136,5 @@ en:confirm_replace_oauth_application: "Are you sure? All users will have to authorize again against OpenProject."confirm_replace_oauth_client: "Are you sure? All users will have to authorize again against the storage."oauth_client_details_missing: "To complete the setup, please add OAuth client credentials from your storage."+ automatically_managed_project_folder_missing: "To complete the setup, please configure automatically managed project folders for your storage."notice_oauth_application_replaced: "The OpenProject OAuth application was successfully replaced."diff --git a/modules/storages/config/routes.rb b/modules/storages/config/routes.rbindex 7e370b3a5e2..55ed46f795d 100644--- a/modules/storages/config/routes.rb+++ b/modules/storages/config/routes.rb@@ -31,6 +31,9 @@ OpenProject::Application.routes.draw donamespace :settings doresources :storages, controller: '/storages/admin/storages' doresource :oauth_client, controller: '/storages/admin/oauth_clients', only: %i[new create]+ resource :automatically_managed_project_folders, controller: '/storages/admin/automatically_managed_project_folders',+ only: %i[new edit update]+member dodelete '/replace_oauth_application' => '/storages/admin/storages#replace_oauth_application'enddiff --git a/modules/storages/lib/api/v3/storages/storage_representer.rb b/modules/storages/lib/api/v3/storages/storage_representer.rbindex 9f9809ff8a8..4cc5eba7f98 100644--- a/modules/storages/lib/api/v3/storages/storage_representer.rb+++ b/modules/storages/lib/api/v3/storages/storage_representer.rb@@ -81,6 +81,28 @@ module API::V3::Storagesproperty :name+ property :applicationPassword,+ skip_render: ->(*) { true },+ getter: ->(*) {},+ setter: ->(fragment:, represented:, **) {+ if fragment.present?+ represented.automatically_managed = true+ represented.password = fragment+ else+ represented.automatically_managed = false+ end+ }++ property :hasApplicationPassword,+ skip_parse: true,+ skip_render: ->(represented:, **) { !represented.provider_type_nextcloud? },+ getter: ->(represented:, **) {+ break unless represented.provider_type_nextcloud?++ represented.automatically_managed?+ },+ setter: ->(*) {}+date_time_property :created_atdate_time_property :updated_atdiff --git a/modules/storages/lib/open_project/storages/engine.rb b/modules/storages/lib/open_project/storages/engine.rbindex 9ec335af905..01c06515762 100644--- a/modules/storages/lib/open_project/storages/engine.rb+++ b/modules/storages/lib/open_project/storages/engine.rb@@ -44,6 +44,7 @@ module OpenProject::StoragesOpenProject::FeatureDecisions.add :storage_file_picking_select_allOpenProject::FeatureDecisions.add :storage_project_foldersOpenProject::FeatureDecisions.add :managed_project_folders+ OpenProject::FeatureDecisions.add :automatically_managed_project_foldersendinitializer 'openproject_storages.event_subscriptions' dodiff --git a/modules/storages/spec/common/peripherals/storage_requests_spec.rb b/modules/storages/spec/common/peripherals/storage_requests_spec.rbindex 917364bfef0..9d5e6951df5 100644--- a/modules/storages/spec/common/peripherals/storage_requests_spec.rb+++ b/modules/storages/spec/common/peripherals/storage_requests_spec.rb@@ -34,7 +34,7 @@ RSpec.describe Storages::Peripherals::StorageRequests, webmock: true dolet(:user) { create(:user) }let(:url) { 'https://example.com' }let(:origin_user_id) { 'admin' }- let(:storage) { build(:storage, host: url, password: 'OpenProjectSecurePassword') }+ let(:storage) { build(:nextcloud_storage, :as_automatically_managed, host: url, password: 'OpenProjectSecurePassword') }subject { described_class.new(storage:) }diff --git a/modules/storages/spec/contracts/storages/storages/base_contract_spec.rb b/modules/storages/spec/contracts/storages/storages/base_contract_spec.rbindex fef869bc642..f1413fcc15b 100644--- a/modules/storages/spec/contracts/storages/storages/base_contract_spec.rb+++ b/modules/storages/spec/contracts/storages/storages/base_contract_spec.rb@@ -31,7 +31,7 @@ require_relative '../../../spec_helper'RSpec.describe Storages::Storages::BaseContract, :storage_server_helpers, webmock: true dolet(:current_user) { create(:admin) }let(:storage_host) { 'https://host1.example.com' }- let(:storage) { build(:storage, host: storage_host) }+ let(:storage) { build(:nextcloud_storage, host: storage_host) }let(:contract) { described_class.new(storage, current_user) }it 'checks the storage url only when changed' dodiff --git a/modules/storages/spec/contracts/storages/storages/create_contract_spec.rb b/modules/storages/spec/contracts/storages/storages/create_contract_spec.rbindex bcb67c35315..cc081bbef36 100644--- a/modules/storages/spec/contracts/storages/storages/create_contract_spec.rb+++ b/modules/storages/spec/contracts/storages/storages/create_contract_spec.rb@@ -37,10 +37,10 @@ RSpec.describe Storages::Storages::CreateContract doit_behaves_like 'storage contract' dolet(:current_user) { create(:admin) }let(:storage) do- Storages::Storage.new(name: storage_name,- provider_type: storage_provider_type,- host: storage_host,- creator: storage_creator)+ Storages::NextcloudStorage.new(name: storage_name,+ provider_type: storage_provider_type,+ host: storage_host,+ creator: storage_creator)endlet(:contract) { described_class.new(storage, current_user) }diff --git a/modules/storages/spec/contracts/storages/storages/shared_contract_examples.rb b/modules/storages/spec/contracts/storages/storages/shared_contract_examples.rbindex 8d68419d716..42d8766dc6b 100644--- a/modules/storages/spec/contracts/storages/storages/shared_contract_examples.rb+++ b/modules/storages/spec/contracts/storages/storages/shared_contract_examples.rb@@ -223,5 +223,44 @@ RSpec.shared_examples_for 'storage contract', :storage_server_helpers, webmock:include_examples 'contract is valid'endend++ context 'when automatically managed, no username or password' do+ before { storage.automatically_managed = true }++ it_behaves_like 'contract is invalid', password: :blank+ end++ context 'when automatically managed, with username and password' do+ before do+ storage.assign_attributes(automatically_managed: true, username: 'OpenProject', password: 'Password')+ end++ it_behaves_like 'contract is valid'+ end++ context 'when not automatically managed, no username or password' do+ before do+ storage.provider_fields = {}+ storage.assign_attributes(automatically_managed: false)+ end++ it_behaves_like 'contract is valid'+ end++ context 'when not automatically managed, with username default and password' do+ before do+ storage.assign_attributes(automatically_managed: false, username: 'OpenProject', password: 'Password')+ end++ it_behaves_like 'contract is invalid', password: :present+ end++ context 'when not automatically managed, with user defined username and password' do+ before do+ storage.assign_attributes(automatically_managed: false, username: 'Username', password: 'Password')+ end++ it_behaves_like 'contract is invalid', username: :present, password: :present+ endendenddiff --git a/modules/storages/spec/contracts/storages/storages/update_contract_spec.rb b/modules/storages/spec/contracts/storages/storages/update_contract_spec.rbindex dd988b047a7..337343d76b2 100644--- a/modules/storages/spec/contracts/storages/storages/update_contract_spec.rb+++ b/modules/storages/spec/contracts/storages/storages/update_contract_spec.rb@@ -36,7 +36,7 @@ RSpec.describe Storages::Storages::UpdateContract doit_behaves_like 'storage contract' dolet(:storage) do- build_stubbed(:storage,+ build_stubbed(:nextcloud_storage,creator: storage_creator,host: storage_host,name: storage_name,diff --git a/modules/storages/spec/factories/storage_factory.rb b/modules/storages/spec/factories/storage_factory.rbindex 64bce66ac8c..72c93ac6991 100644--- a/modules/storages/spec/factories/storage_factory.rb+++ b/modules/storages/spec/factories/storage_factory.rb@@ -27,10 +27,24 @@#++FactoryBot.define do- factory :storage, class: '::Storages::NextcloudStorage' do+ factory :storage, class: '::Storages::Storage' doprovider_type { Storages::Storage::PROVIDER_TYPE_NEXTCLOUD }sequence(:name) { |n| "Storage #{n}" }sequence(:host) { |n| "https://host#{n}.example.com" }creator factory: :user++ factory :nextcloud_storage, class: '::Storages::NextcloudStorage' do+ provider_type { Storages::Storage::PROVIDER_TYPE_NEXTCLOUD }++ trait :as_automatically_managed do+ automatically_managed { true }+ username { 'OpenProject' }+ password { 'Password123' }+ end++ trait :as_not_automatically_managed do+ automatically_managed { false }+ end+ endendenddiff --git a/modules/storages/spec/features/admin_storages_spec.rb b/modules/storages/spec/features/admin_storages_spec.rbindex 1ee97b9eab4..4ce9b408018 100644--- a/modules/storages/spec/features/admin_storages_spec.rb+++ b/modules/storages/spec/features/admin_storages_spec.rb@@ -28,7 +28,7 @@require_relative '../spec_helper'-RSpec.describe 'Admin storages', :storage_server_helpers, js: true do+RSpec.describe 'Admin storages', :storage_server_helpers, js: true, with_flag: { automatically_managed_project_folders: true } dolet(:admin) { create(:admin) }before do@@ -38,6 +38,7 @@ RSpec.describe 'Admin storages', :storage_server_helpers, js: true doit 'creates, edits and deletes storages', webmock: true dovisit admin_settings_storages_path+ ######### Step 1: Begin Create a storage ########## Show empty storages listexpect(page).to have_title('File storages')expect(page.find('.title-container')).to have_text('File storages')@@ -60,7 +61,9 @@ RSpec.describe 'Admin storages', :storage_server_helpers, js: true dopage.find_by_id('storages_storage_name').set("NC 1")page.find_by_id('storages_storage_host').set("https://example.com")page.find('button[type=submit]', text: "Save and continue setup").click+ ######### Step 1: End Create a storage #########+ ######### Step 2: Begin Show OAuth application ########## Show created oauth applicationstorage_type = I18n.t('storages.provider_types.nextcloud.name')expect(page).to have_title("#{storage_type} #{I18n.t('storages.label_oauth_application_details')}")@@ -68,7 +71,9 @@ RSpec.describe 'Admin storages', :storage_server_helpers, js: true doexpect(oauth_app_client_id.length).to eq 43expect(page.find_by_id('secret').value.length).to eq 43page.find('a.button', text: 'Done. Continue setup').click+ ######### Step 2: End Show OAuth application #########+ ######### Step 3: Begin Add OAuthClient ########## Add OAuthClient - Testing a number of different invalid states# However, more detailed checks are performed in the service spec.expect(page).to have_title("OAuth client details")@@ -90,6 +95,31 @@ RSpec.describe 'Admin storages', :storage_server_helpers, js: true dopage.find_by_id('oauth_client_client_id').set("0123456789")page.find_by_id('oauth_client_client_secret').set("1234567890")page.find('button[type=submit]', text: 'Save').click+ ######### Step 3: End Add OAuthClient #########++ ######### Step 4: Begin Automatically managed project folders #########+ # Nextcloud - Automatically managed project folders settings+ # Switch is checked by default, expects input for password+ expect(page).to have_title("Automatically managed project folders")+ automatically_managed_switch = page.find('[name="storages_nextcloud_storage[automatically_managed]"]')+ application_password_input = page.find_by_id('storages_nextcloud_storage_password')+ expect(automatically_managed_switch).to be_checked+ expect(application_password_input.value).to be_empty++ # Clicking submit with application password empty should show an error+ page.click_button('Done, complete setup')+ # Check that we're still on the same page+ expect(page).to have_title("Automatically managed project folders")+ expect(page).to have_content("Password can't be blank.")++ # Fill in application password and submit+ automatically_managed_switch = page.find('[name="storages_nextcloud_storage[automatically_managed]"]')+ expect(automatically_managed_switch).to be_checked+ page.fill_in 'storages_nextcloud_storage_password', with: "1234567890"+ page.click_button('Save')+ expect(page).to have_text("Active")+ expect(page).to have_text("●●●●●●●●●●●●●●●●")+ ######### Step 4: End Automatically managed project folders ########## Show details of a storagecreated_storage = Storages::Storage.find_by(name: 'NC 1')@@ -101,6 +131,7 @@ RSpec.describe 'Admin storages', :storage_server_helpers, js: true do# Check for client_id of nextcloud client and oauth applicationexpect(page).to have_text(oauth_app_client_id)expect(page).to have_text("0123456789")+ # Check for the automatically managed project folders settings# Edit storage againpage.find('.button--icon.icon-edit').click@@ -165,6 +196,29 @@ RSpec.describe 'Admin storages', :storage_server_helpers, js: true doexpect(page).to have_text('https://example.com')expect(page).to have_text(created_storage.created_at.localtime.strftime("%m/%d/%Y %I:%M %p"))+ ######### Begin Edit Automatically managed project folders #########+ page.find('.button--icon.icon-edit').click+ page.find('a', text: 'Edit automatically managed project folders').click++ expect(page).to have_title("Automatically managed project folders")+ automatically_managed_switch = page.find('[name="storages_nextcloud_storage[automatically_managed]"]')+ application_password_input = page.find_by_id('storages_nextcloud_storage_password')+ expect(automatically_managed_switch).to be_checked+ expect(application_password_input.value).to be_empty+ expect(application_password_input['placeholder']).to eq("●●●●●●●●●●●●●●●●")++ # Clicking submit without inputing new application password should show an error+ page.click_button('Save')+ # Check that we're still on the same page+ expect(page).to have_title("Automatically managed project folders")+ expect(page).to have_content("Password can't be blank.")++ # Switch off automatically managed project folders+ page.find('[data-qa-selector="spot-switch-handle"]').click+ page.click_button('Save')+ expect(page).to have_text("Inactive")+ ######### End Edit Automatically managed project folders #########+# List of storagespage.find("ul.op-breadcrumb li", text: "File storages").clickdiff --git a/modules/storages/spec/features/manage_project_storage_spec.rb b/modules/storages/spec/features/manage_project_storage_spec.rbindex 045a4c7d945..5f11348acf3 100644--- a/modules/storages/spec/features/manage_project_storage_spec.rb+++ b/modules/storages/spec/features/manage_project_storage_spec.rb@@ -42,7 +42,7 @@ RSpec.describe 'Activation of storages in projects', js: true, webmock: true, wiedit_project])endlet(:oauth_application) { create(:oauth_application) }- let(:storage) { create(:storage, oauth_application:) }+ let(:storage) { create(:nextcloud_storage, oauth_application:) }let(:project) docreate(:project,members: { user => role },diff --git a/modules/storages/spec/lib/api/v3/storages/storages_representer_parsing_spec.rb b/modules/storages/spec/lib/api/v3/storages/storages_representer_parsing_spec.rbnew file mode 100644index 00000000000..b783b0c0baf--- /dev/null+++ b/modules/storages/spec/lib/api/v3/storages/storages_representer_parsing_spec.rb@@ -0,0 +1,103 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 COPYRIGHT and LICENSE files for more details.+#++++require 'spec_helper'++RSpec.describe API::V3::Storages::StorageRepresenter, 'parsing' do+ let(:storage) { build_stubbed(:nextcloud_storage) }+ let(:current_user) { build_stubbed(:user) }++ describe 'parsing' do+ subject(:parsed) { representer.from_hash parsed_hash }++ let(:representer) { described_class.new(storage, current_user:) }++ let(:parsed_hash) do+ {+ "name" => "Nextcloud Local",+ "_links" => {+ "origin" => {+ "href" => storage.host+ },+ "type" => {+ "href" => API::V3::Storages::URN_STORAGE_TYPE_NEXTCLOUD+ }+ }+ }+ end++ context 'with basic attributes' do+ it 'is parsed correctly' do+ expect(parsed).to have_attributes(name: 'Nextcloud Local', host: storage.host,+ provider_type: "Storages::NextcloudStorage")++ aggregate_failures 'does not parse nextcloud provider fields' do+ expect(parsed.provider_fields).to eq({})+ end+ end+ end++ describe 'automatically managed project folders' do+ context 'with applicationPassword' do+ let(:parsed_hash) do+ super().merge(+ "applicationPassword" => "secret"+ )+ end++ it 'is parsed correctly' do+ expect(parsed).to have_attributes(automatically_managed: true, password: 'secret')+ end+ end++ context 'with applicationPassword null' do+ let(:parsed_hash) do+ super().merge(+ "applicationPassword" => nil+ )+ end++ it 'is parsed as automatic folder management disabled' do+ expect(parsed).to have_attributes(automatically_managed: false, password: nil)+ end+ end++ context 'with applicationPassword blank' do+ let(:parsed_hash) do+ super().merge(+ "applicationPassword" => ''+ )+ end++ it 'is parsed as automatic folder management disabled' do+ expect(parsed).to have_attributes(automatically_managed: false, password: nil)+ end+ end+ end+ end+enddiff --git a/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rb b/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rbindex 756de7a1906..7a397783fae 100644--- a/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rb+++ b/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rb@@ -31,7 +31,7 @@ require 'spec_helper'RSpec.describe API::V3::Storages::StorageRepresenter, 'rendering' dolet(:oauth_application) { build_stubbed(:oauth_application) }let(:oauth_client_credentials) { build_stubbed(:oauth_client) }- let(:storage) { build_stubbed(:storage, oauth_application:, oauth_client: oauth_client_credentials) }+ let(:storage) { build_stubbed(:nextcloud_storage, oauth_application:, oauth_client: oauth_client_credentials) }let(:user) { build_stubbed(:user) }let(:representer) { described_class.new(storage, current_user: user, embed_links: true) }let(:connection_manager) { instance_double(OAuthClients::ConnectionManager) }@@ -82,7 +82,7 @@ RSpec.describe API::V3::Storages::StorageRepresenter, 'rendering' docontext 'when user has :manage_file_links permission on some projects linked to the storage' dolet(:oauth_application) { create(:oauth_application) }let(:oauth_client_credentials) { create(:oauth_client) }- let(:storage) { create(:storage, oauth_application:, oauth_client: oauth_client_credentials) }+ let(:storage) { create(:nextcloud_storage, oauth_application:, oauth_client: oauth_client_credentials) }let(:user) { create(:user) }let(:another_user) { create(:user) }let(:no_permissions_role) { create(:role, permissions: []) }@@ -123,8 +123,7 @@ RSpec.describe API::V3::Storages::StorageRepresenter, 'rendering' doproject_ids = JSON.parse(generated).dig('_links', 'prepareUpload').map { _1.dig('payload', 'projectId') }expect(project_ids)- .to match_array([project_linked_with_upload_permission.id,- another_project_linked_with_upload_permission.id])+ .to contain_exactly(project_linked_with_upload_permission.id, another_project_linked_with_upload_permission.id)end# rubocop:enable RSpec/ExampleLengthend@@ -217,5 +216,61 @@ RSpec.describe API::V3::Storages::StorageRepresenter, 'rendering' doit_behaves_like 'datetime property', :updatedAt dolet(:value) { storage.updated_at }end++ describe 'Automatically managed project folders' do+ shared_examples 'protects applicationPassword' do+ it 'does not render the applicationPassword' do+ expect(generated).not_to have_json_path('applicationPassword')+ end+ end++ context 'with automatic project folder management enabled' do+ let(:storage) do+ build(:nextcloud_storage, :as_automatically_managed, oauth_application:, oauth_client: oauth_client_credentials)+ end++ it_behaves_like 'property', :hasApplicationPassword do+ let(:value) { true }+ end++ it_behaves_like 'protects applicationPassword'+ end++ context 'with automatic project folder management disabled' do+ let(:storage) do+ build(:nextcloud_storage, :as_not_automatically_managed, oauth_application:, oauth_client: oauth_client_credentials)+ end++ it_behaves_like 'property', :hasApplicationPassword do+ let(:value) { false }+ end++ it_behaves_like 'protects applicationPassword'+ end++ context 'when automatic project folder management is not configured' do+ let(:storage) do+ build(:nextcloud_storage, provider_fields: {}, oauth_application:, oauth_client: oauth_client_credentials)+ end++ it 'hasApplicationPassword is false' do+ expect(generated).to be_json_eql(false).at_path('hasApplicationPassword')+ end++ it_behaves_like 'protects applicationPassword'+ end++ context 'with a non-Nextcloud storage' do+ let(:storage) do+ build(:storage, provider_type: 'unknown', oauth_application:, oauth_client: oauth_client_credentials)+ end++ it 'does not include the property hasApplicationPassword' do+ expect(generated).not_to have_json_path('hasApplicationPassword')+ end++ it_behaves_like 'protects applicationPassword'+ end+ endendenddiff --git a/modules/storages/spec/models/nextcloud_storage_spec.rb b/modules/storages/spec/models/nextcloud_storage_spec.rbindex 9ca8e0cdc40..6ac1574162e 100644--- a/modules/storages/spec/models/nextcloud_storage_spec.rb+++ b/modules/storages/spec/models/nextcloud_storage_spec.rb@@ -29,6 +29,48 @@require_relative '../spec_helper'RSpec.describe Storages::NextcloudStorage do+ let(:storage) { build(:nextcloud_storage) }++ shared_examples 'a stored attribute with default value' do |attribute, default_value|+ context "when the provider fields are empty" do+ let(:storage) { build(:nextcloud_storage, provider_fields: {}) }++ it "has a default runtime value of #{default_value}" do+ expect(storage.provider_fields).to eq({})+ expect(storage.public_send(attribute)).to eq(default_value)+ end+ end++ context "with a new value of 'foo'" do+ it "sets the value to 'foo'" do+ storage.public_send("#{attribute}=", 'foo')+ expect(storage.public_send(attribute)).to eq('foo')+ end+ end+ end++ shared_examples 'a stored boolean attribute' do |attribute|+ it "#{attribute} has a default value of false" do+ expect(storage.public_send(:"#{attribute}?")).to be(false)+ end++ ['1', 'true', true].each do |boolean_like|+ context "with truthy value #{boolean_like}" do+ it "sets #{attribute} to true" do+ storage.public_send(:"#{attribute}=", boolean_like)+ expect(storage.public_send(attribute)).to be(true)+ end+ end+ end++ it "#{attribute} can be set to true" do+ storage.public_send(:"#{attribute}=", true)++ expect(storage.public_send(attribute)).to be(true)+ expect(storage.public_send(:"#{attribute}?")).to be(true)+ end+ end+describe '.sync_all_group_folders' dosubject { described_class.sync_all_group_folders }@@ -38,12 +80,11 @@ RSpec.describe Storages::NextcloudStorage doendit 'calls GroupFolderPropertiesSyncService for each appropriate storage' do- storage1 = create(:storage, has_managed_project_folders: true)- storage2 = create(:storage, has_managed_project_folders: false)+ storage1 = create(:nextcloud_storage, :as_automatically_managed)+ storage2 = create(:nextcloud_storage, :as_not_automatically_managed)+allow(Storages::GroupFolderPropertiesSyncService).to receive(:new).and_call_original- # rubocop:disable RSpec/AnyInstance- allow_any_instance_of(Storages::GroupFolderPropertiesSyncService).to receive(:call).and_return(nil)- # rubocop:enable RSpec/AnyInstance+ allow_any_instance_of(Storages::GroupFolderPropertiesSyncService).to receive(:call).and_return(nil) # rubocop:disable RSpec/AnyInstanceexpect(subject).to be(true)expect(Storages::GroupFolderPropertiesSyncService).to have_received(:new).with(storage1).once@@ -64,4 +105,50 @@ RSpec.describe Storages::NextcloudStorage doendendend++ describe '#username' do+ it_behaves_like 'a stored attribute with default value', :username, 'OpenProject'+ end++ describe '#group' do+ it_behaves_like 'a stored attribute with default value', :group, 'OpenProject'+ end++ describe '#group_folder' do+ it_behaves_like 'a stored attribute with default value', :group_folder, 'OpenProject'+ end++ describe '#automatically_managed?' do+ it_behaves_like 'a stored boolean attribute', :automatically_managed+ end++ describe '#automatic_management_unspecified?' do+ context 'when automatically_managed is nil' do+ let(:storage) { build(:nextcloud_storage, automatically_managed: nil) }++ it { expect(storage).to be_automatic_management_unspecified }+ end++ context 'when automatically_managed is true' do+ let(:storage) { build(:nextcloud_storage, automatically_managed: true) }++ it { expect(storage).not_to be_automatic_management_unspecified }+ end++ context 'when automatically_managed is false' do+ let(:storage) { build(:nextcloud_storage, automatically_managed: false) }++ it { expect(storage).not_to be_automatic_management_unspecified }+ end+ end++ describe '#provider_fields_defaults' do+ let(:storage) { build(:nextcloud_storage) }++ it 'returns the default values for nextcloud' do+ expect(storage.provider_fields_defaults).to eq(+ { automatically_managed: true, username: 'OpenProject' }+ )+ end+ endenddiff --git a/modules/storages/spec/models/storage_spec.rb b/modules/storages/spec/models/storage_spec.rbindex f492faae12c..34ec56f7290 100644--- a/modules/storages/spec/models/storage_spec.rb+++ b/modules/storages/spec/models/storage_spec.rb@@ -112,4 +112,18 @@ RSpec.describe Storages::Storage doexpect(Storages::FileLink.count).to be 0endend++ describe '#provider_type_nextcloud?' do+ context 'when provider_type is nextcloud' do+ let(:storage) { build(:storage) }++ it { expect(storage).to be_a_provider_type_nextcloud }+ end++ context 'when provider_type is not nextcloud' do+ let(:storage) { build(:storage, provider_type: 'Storages::DropboxStorage') }++ it { expect(storage).not_to be_a_provider_type_nextcloud }+ end+ endenddiff --git a/modules/storages/spec/requests/api/v3/storages/storages_spec.rb b/modules/storages/spec/requests/api/v3/storages/storages_spec.rbindex 9b6d86f8fc3..76e976265a8 100644--- a/modules/storages/spec/requests/api/v3/storages/storages_spec.rb+++ b/modules/storages/spec/requests/api/v3/storages/storages_spec.rb@@ -111,6 +111,34 @@ RSpec.describe 'API v3 storages resource', content_type: :json, webmock: true doit { is_expected.to have_json_path('_embedded/oauthApplication/clientSecret') }end+ context 'with applicationPassword' do+ let(:params) do+ super().merge(+ applicationPassword: 'myappsecret'+ )+ end++ subject { last_response.body }++ it_behaves_like 'successful response', 201++ it { is_expected.to be_json_eql('true').at_path('hasApplicationPassword') }+ end++ context 'with applicationPassword as null' do+ let(:params) do+ super().merge(+ applicationPassword: nil+ )+ end++ subject { last_response.body }++ it_behaves_like 'successful response', 201++ it { is_expected.to be_json_eql('false').at_path('hasApplicationPassword') }+ end+context 'if missing a mandatory value' dolet(:params) do{@@ -251,6 +279,34 @@ RSpec.describe 'API v3 storages resource', content_type: :json, webmock: true doit { is_expected.to be_json_eql(name.to_json).at_path('name') }end++ context 'with applicationPassword' do+ let(:params) do+ super().merge(+ applicationPassword: 'myappsecret'+ )+ end++ subject { last_response.body }++ it_behaves_like 'successful response'++ it { is_expected.to be_json_eql('true').at_path('hasApplicationPassword') }+ end++ context 'with applicationPassword as null' do+ let(:params) do+ super().merge(+ applicationPassword: nil+ )+ end++ subject { last_response.body }++ it_behaves_like 'successful response'++ it { is_expected.to be_json_eql('false').at_path('hasApplicationPassword') }+ endendenddiff --git a/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb b/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rbindex 780308ae093..c5f4cacf5ed 100644--- a/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb+++ b/modules/storages/spec/services/storages/group_folder_properties_sync_service_spec.rb@@ -319,9 +319,9 @@ RSpec.describe Storages::GroupFolderPropertiesSyncService, webmock: true do# rubocop:disable RSpec/ExampleLengthdescribe '#call' doit 'sets properties for project folders' do- storage = create(:storage,+ storage = create(:nextcloud_storage,+ :as_automatically_managed,host: 'https://example.com',- has_managed_project_folders: true,password: '12345678')projects_storage1 = create(:project_storage,project_folder_mode: 'automatic',diff --git a/modules/storages/spec/services/storages/storages/set_attributes_service_spec.rb b/modules/storages/spec/services/storages/storages/set_attributes_service_spec.rbindex d02161de754..0941e5d9057 100644--- a/modules/storages/spec/services/storages/storages/set_attributes_service_spec.rb+++ b/modules/storages/spec/services/storages/storages/set_attributes_service_spec.rb@@ -147,4 +147,48 @@ RSpec.describe Storages::Storages::SetAttributesService, type: :model do.to eql(contract_errors)endend++ describe 'automatically managed project folders' do+ let(:model_instance) { build_stubbed(:nextcloud_storage) }++ context 'with password' do+ let(:params) do+ super().merge(+ "automatically_managed" => true,+ "password" => "secret"+ )+ end++ it 'enables automatic folder management with password' do+ expect(subject.result).to have_attributes(automatically_managed: true, username: 'OpenProject',+ password: 'secret')+ end+ end++ context 'with automatically_managed false' do+ let(:params) do+ super().merge(+ "automatically_managed" => false+ )+ end++ it 'disables automatic folder management' do+ expect(subject.result).to have_attributes(automatically_managed: false)+ expect(subject.result.attributes.keys).not_to include(:username, :password)+ end+ end++ context 'with automatically_managed nil' do+ let(:params) do+ super().merge(+ "automatically_managed" => nil+ )+ end++ it 'does not change the value' do+ expect(subject.result).to have_attributes(automatically_managed: nil)+ expect(subject.result.attributes.keys).not_to include(:username, :password)+ end+ end+ endenddiff --git a/modules/storages/spec/services/storages/storages/set_nextcloud_provider_fields_attributes_service_spec.rb b/modules/storages/spec/services/storages/storages/set_nextcloud_provider_fields_attributes_service_spec.rbnew file mode 100644index 00000000000..3695c6f0c12--- /dev/null+++ b/modules/storages/spec/services/storages/storages/set_nextcloud_provider_fields_attributes_service_spec.rb@@ -0,0 +1,108 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2023 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 COPYRIGHT and LICENSE files for more details.+#++++require 'spec_helper'++RSpec.describe Storages::Storages::SetNextcloudProviderFieldsAttributesService, type: :model do+ let(:current_user) { build_stubbed(:admin) }+ let(:storage) { build(:nextcloud_storage, :as_automatically_managed) }+ let(:contract_class) { stub_valid_contract(Storages::Storages::BaseContract) }++ subject(:provider_fields_attributes_service) do+ described_class.new(user: current_user, model: storage, contract_class:).call+ end++ before { allow(storage).to receive(:valid?).and_return(true) }++ context 'when automatically_managed is not set' do+ let(:storage) { build(:nextcloud_storage, provider_fields: {}) }++ it 'sets automatically_managed to true' do+ expect { provider_fields_attributes_service }+ .to change(storage, :provider_fields).from({}).to({ 'automatically_managed' => true })++ aggregate_failures 'returns the storage model object as the result' do+ expect(provider_fields_attributes_service.result).to eq(storage)+ end++ aggregate_failures 'is valid contract' do+ expect(provider_fields_attributes_service).to be_a_success+ end+ end+ end++ context 'when automatically_managed is already set as true' do+ let(:storage) { build(:nextcloud_storage, :as_automatically_managed) }++ it 'retains the set value, does not change the object' do+ expect { provider_fields_attributes_service }.not_to change(storage, :provider_fields)+ expect(provider_fields_attributes_service.result.automatically_managed).to be(true)++ aggregate_failures 'returns the storage model object as the result' do+ expect(provider_fields_attributes_service.result).to eq(storage)+ end++ aggregate_failures 'is valid contract' do+ expect(provider_fields_attributes_service).to be_a_success+ end+ end+ end++ context 'when automatically_managed is set as false' do+ let(:storage) { build(:nextcloud_storage, :as_not_automatically_managed) }++ it 'retains the set value, does not change the object' do+ expect { provider_fields_attributes_service }.not_to change(storage, :provider_fields)+ expect(provider_fields_attributes_service.result.automatically_managed).to be(false)++ aggregate_failures 'returns the storage model object as the result' do+ expect(provider_fields_attributes_service.result).to eq(storage)+ end++ aggregate_failures 'is valid contract' do+ expect(provider_fields_attributes_service).to be_a_success+ end+ end+ end++ def stub_valid_contract(contract_class)+ contract_errors = instance_double(ActiveModel::Errors, 'contract_errors')+ contract_valid = true+ contract_instance = stub_contract_instance(contract_class, contract_valid, contract_errors)+ allow(contract_class).to receive(:new).and_return(contract_instance)++ contract_class+ end++ def stub_contract_instance(contract_class, contract_valid, contract_errors)+ contract_instance = instance_double(contract_class, 'contract_instance')+ allow(contract_instance).to receive(:validate).and_return(contract_valid)+ allow(contract_instance).to receive(:errors).and_return(contract_errors)+ contract_instance+ end+enddiff --git a/modules/storages/spec/services/storages/storages/update_service_spec.rb b/modules/storages/spec/services/storages/storages/update_service_spec.rbindex 40ea8dc1fdd..bb7f7d9554c 100644--- a/modules/storages/spec/services/storages/storages/update_service_spec.rb+++ b/modules/storages/spec/services/storages/storages/update_service_spec.rb@@ -66,7 +66,7 @@ RSpec.describe Storages::Storages::UpdateService, type: :model doit 'cannot update storage creator' dostorage_creator = create(:admin, login: "storage_creator")- storage = create(:storage, creator: storage_creator)+ storage = create(:nextcloud_storage, creator: storage_creator)service = described_class.new(user: create(:admin), model: storage)service_result = service.call(creator: create(:user, login: "impostor"))@@ -77,7 +77,7 @@ RSpec.describe Storages::Storages::UpdateService, type: :model doenddescribe 'updates the nested OAuth application' do- let(:storage) { create(:storage) }+ let(:storage) { create(:nextcloud_storage) }let!(:oauth_application) { create(:oauth_application, integration: storage) }let(:user) { create(:admin) }let(:name) { 'Awesome Storage' }diff --git a/modules/storages/spec/workers/storages/manage_nextcloud_integration_events_job_spec.rb b/modules/storages/spec/workers/storages/manage_nextcloud_integration_events_job_spec.rbindex d42f26b7a4c..56b5eef7fab 100644--- a/modules/storages/spec/workers/storages/manage_nextcloud_integration_events_job_spec.rb+++ b/modules/storages/spec/workers/storages/manage_nextcloud_integration_events_job_spec.rb@@ -37,7 +37,7 @@ RSpec.describe Storages::ManageNextcloudIntegrationEventsJob, type: :job dosame_handler_within_timeframe1 = described_class.set(wait: 10.seconds).perform_later.provider_job_idsame_handler_within_timeframe2 = described_class.set(wait: 12.seconds).perform_later.provider_job_idsame_handler_within_timeframe3 = described_class.set(wait: 16.seconds).perform_later.provider_job_id- same_handler_out_of_timeframe = described_class.set(wait: 1.minutes).perform_later.provider_job_id+ same_handler_out_of_timeframe = described_class.set(wait: 1.minute).perform_later.provider_job_idsame_handler_within_timeframe_in_progress = described_class.set(wait: 18.seconds).perform_later.tap do |job|# simulate in progress stateDelayed::Job.where(id: job.provider_job_id).update_all(locked_at: Time.current, locked_by: "test_process #{Process.pid}")