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

Capabilities API (#9083)

ulferts4bf7a26eb18d
diff --git a/app/models/action.rb b/app/models/action.rb
new file mode 100644
index 00000000000..91ab68fed53
--- /dev/null
+++ b/app/models/action.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.
+#++
+
+class Action < ApplicationRecord
+ include Tableless
+ include Scopes::Scoped
+
+ scopes :default
+
+ default_scope { default }
+
+ attribute :id, :text, default: nil
+ attribute :permission, :text, default: nil
+ attribute :global, :boolean, default: false
+ attribute :module, :text, default: false
+end
diff --git a/app/models/actions/scopes/default.rb b/app/models/actions/scopes/default.rb
new file mode 100644
index 00000000000..cb81f097272
--- /dev/null
+++ b/app/models/actions/scopes/default.rb
@@ -0,0 +1,75 @@
+#-- 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 Actions::Scopes
+ module Default
+ extend ActiveSupport::Concern
+
+ class_methods do
+ def default
+ capabilities_sql = <<~SQL
+ (SELECT id, permission, global, module FROM (VALUES #{action_map}) AS t(id, permission, global, module)) actions
+ SQL
+
+ select('actions.*')
+ .from(capabilities_sql)
+ end
+
+ private
+
+ def action_map
+ OpenProject::AccessControl
+ .contract_actions_map
+ .map { |permission, v| map_actions(permission, v[:actions], v[:global], v[:module]) }
+ .flatten
+ .join(', ')
+ end
+
+ def map_actions(permission, actions, global, module_name)
+ actions.map do |namespace, actions|
+ actions.map do |action|
+ values = [quote_string("#{action_v3_name(namespace)}/#{action}"),
+ quote_string(permission),
+ global,
+ module_name ? quote_string(module_name) : 'NULL'].join(', ')
+
+ "(#{values})"
+ end
+ end
+ end
+
+ def action_v3_name(name)
+ API::Utilities::PropertyNameConverter.from_ar_name(name.to_s.singularize).pluralize
+ end
+
+ def quote_string(string)
+ ActiveRecord::Base.connection.quote(string.to_s)
+ end
+ end
+ end
+end
diff --git a/app/models/capabilities/scopes/default.rb b/app/models/capabilities/scopes/default.rb
new file mode 100644
index 00000000000..2e29e3beb24
--- /dev/null
+++ b/app/models/capabilities/scopes/default.rb
@@ -0,0 +1,124 @@
+#-- 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 Capabilities::Scopes
+ module Default
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # Currently, this does not reflect the behaviour present in the backend that every permission in at least one project
+ # leads to having that permission in the global context as well. Hopefully, this is not necessary to be added.
+ def default
+ capabilities_sql = <<~SQL
+ (
+ #{default_sql_by_member}
+ UNION
+ #{default_sql_by_non_member}
+ UNION
+ #{default_sql_by_admin}
+ ) capabilities
+ SQL
+
+ select('capabilities.*')
+ .from(capabilities_sql)
+ end
+
+ private
+
+ def default_sql_by_member
+ <<~SQL
+ SELECT DISTINCT
+ actions.id "action",
+ users.id principal_id,
+ projects.id context_id
+ FROM (#{Action.default.to_sql}) actions
+ LEFT OUTER JOIN "role_permissions" ON "role_permissions"."permission" = "actions"."permission"
+ LEFT OUTER JOIN "roles" ON "roles".id = "role_permissions".role_id
+ LEFT OUTER JOIN "member_roles" ON "member_roles".role_id = "roles".id
+ LEFT OUTER JOIN "members" ON members.id = member_roles.member_id
+ JOIN (#{Principal.visible.not_builtin.not_locked.to_sql}) users
+ ON "users".id = members.user_id
+ LEFT OUTER JOIN "projects"
+ ON "projects".id = members.project_id
+ LEFT OUTER JOIN enabled_modules
+ ON enabled_modules.project_id = projects.id
+ AND actions.module = enabled_modules.name
+ WHERE (projects.active AND (enabled_modules.project_id IS NOT NULL OR "actions".module IS NULL))
+ OR (projects.id IS NULL AND "actions".global)
+ SQL
+ end
+
+ def default_sql_by_admin
+ <<~SQL
+ SELECT DISTINCT
+ actions.id "action",
+ users.id principal_id,
+ projects.id context_id
+ FROM (#{Action.default.to_sql}) actions
+ JOIN (#{Principal.visible.not_builtin.not_locked.to_sql}) users
+ ON "users".admin = true
+ LEFT OUTER JOIN "projects"
+ ON "projects".active = true
+ AND NOT "actions".global
+ LEFT OUTER JOIN enabled_modules
+ ON enabled_modules.project_id = projects.id
+ AND actions.module = enabled_modules.name
+ WHERE (projects.id IS NOT NULL AND (enabled_modules.project_id IS NOT NULL OR "actions".module IS NULL)) OR "actions".global
+ SQL
+ end
+
+ def default_sql_by_non_member
+ <<~SQL
+ SELECT DISTINCT
+ actions.id "action",
+ users.id principal_id,
+ projects.id context_id
+ FROM (#{Action.default.to_sql}) actions
+ JOIN "role_permissions" ON "role_permissions"."permission" = "actions"."permission"
+ JOIN "roles" ON "roles".id = "role_permissions".role_id AND roles.builtin = #{Role::BUILTIN_NON_MEMBER}
+ JOIN (#{Principal.visible.not_builtin.not_locked.to_sql}) users
+ ON 1 = 1
+ JOIN "projects"
+ ON "projects".active = true
+ AND ("projects".public = true OR EXISTS (SELECT 1
+ FROM members
+ WHERE members.project_id = projects.id
+ AND members.user_id = users.id
+ LIMIT 1))
+ LEFT OUTER JOIN enabled_modules
+ ON enabled_modules.project_id = projects.id
+ AND actions.module = enabled_modules.name
+
+ WHERE enabled_modules.project_id IS NOT NULL OR "actions".module IS NULL
+ SQL
+ end
+ end
+ end
+end
diff --git a/app/models/capability.rb b/app/models/capability.rb
new file mode 100644
index 00000000000..77a32bbd0c7
--- /dev/null
+++ b/app/models/capability.rb
@@ -0,0 +1,45 @@
+#-- 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 Capability < ApplicationRecord
+ include Tableless
+ include Scopes::Scoped
+
+ scopes :default
+
+ default_scope { default }
+
+ belongs_to :context, class_name: 'Project'
+ belongs_to :principal
+
+ attribute :action, :text, default: nil
+ attribute :context_id, :integer, default: nil
+ attribute :principal_id, :integer, default: nil
+end
diff --git a/app/models/concerns/tableless.rb b/app/models/concerns/tableless.rb
new file mode 100644
index 00000000000..1e009ecfe39
--- /dev/null
+++ b/app/models/concerns/tableless.rb
@@ -0,0 +1,57 @@
+#-- 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 Tableless
+ extend ActiveSupport::Concern
+
+ def persisted?
+ false
+ end
+
+ class_methods do
+ def attribute_names
+ @attribute_names ||= attribute_types.keys
+ end
+
+ def load_schema!
+ @columns_hash ||= Hash.new
+
+ # From active_record/attributes.rb
+ attributes_to_define_after_schema_loads.each do |name, (type, options)|
+ if type.is_a?(Symbol)
+ type = ActiveRecord::Type.lookup(type, **options.except(:default))
+ end
+
+ define_attribute(name, type, **options.slice(:default))
+
+ # Improve Model#inspect output
+ @columns_hash[name.to_s] = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default])
+ end
+ end
+ end
+end
diff --git a/app/models/queries/actions.rb b/app/models/queries/actions.rb
new file mode 100644
index 00000000000..6efc5ba9db5
--- /dev/null
+++ b/app/models/queries/actions.rb
@@ -0,0 +1,34 @@
+#-- 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 Queries::Actions
+ query = Queries::Actions::ActionQuery
+ filter_ns = Queries::Actions::Filters
+
+ Queries::Register.filter query, filter_ns::IdFilter
+end
diff --git a/app/models/queries/actions/action_query.rb b/app/models/queries/actions/action_query.rb
new file mode 100644
index 00000000000..e47b2fcb0fb
--- /dev/null
+++ b/app/models/queries/actions/action_query.rb
@@ -0,0 +1,44 @@
+#-- 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 Queries::Actions::ActionQuery < Queries::BaseQuery
+ def self.model
+ Action
+ end
+
+ def results
+ super
+ .reorder(id: :asc)
+ end
+
+ def default_scope
+ Action
+ .default
+ .distinct
+ end
+end
diff --git a/app/models/queries/actions/filters/action_filter.rb b/app/models/queries/actions/filters/action_filter.rb
new file mode 100644
index 00000000000..312d1e3d2c0
--- /dev/null
+++ b/app/models/queries/actions/filters/action_filter.rb
@@ -0,0 +1,37 @@
+#-- 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 Queries::Actions::Filters::ActionFilter < Queries::Filters::Base
+ self.model = Action
+
+ def human_name
+ Action.human_attribute_name(name)
+ end
+end
diff --git a/app/models/queries/actions/filters/id_filter.rb b/app/models/queries/actions/filters/id_filter.rb
new file mode 100644
index 00000000000..547c5187feb
--- /dev/null
+++ b/app/models/queries/actions/filters/id_filter.rb
@@ -0,0 +1,49 @@
+#-- 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 Queries::Actions::Filters::IdFilter < Queries::Actions::Filters::ActionFilter
+ include ::Queries::Filters::Shared::ParsedFilter
+
+ private
+
+ def split_values
+ values.map do |value|
+ if (matches = value.match(/\A(\w+\/\w+)\z/))
+ {
+ action: matches[1]
+ }
+ end
+ end
+ end
+
+ def value_conditions
+ split_values.map do |value|
+ "id = '#{value[:action]}'"
+ end
+ end
+end
diff --git a/app/models/queries/base_query.rb b/app/models/queries/base_query.rb
index 74dc79393fa..ebe2c1358cb 100644
--- a/app/models/queries/base_query.rb
+++ b/app/models/queries/base_query.rb
@@ -93,6 +93,10 @@ class Queries::BaseQuery
available_filters.detect { |f| f.name == name }
end
+ def ordered?
+ orders.any?
+ end
+
protected
attr_accessor :user
diff --git a/app/models/queries/capabilities.rb b/app/models/queries/capabilities.rb
new file mode 100644
index 00000000000..6a8b1472a7f
--- /dev/null
+++ b/app/models/queries/capabilities.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 Queries::Capabilities
+ query = Queries::Capabilities::CapabilityQuery
+ filter_ns = Queries::Capabilities::Filters
+
+ Queries::Register.filter query, filter_ns::IdFilter
+ Queries::Register.filter query, filter_ns::PrincipalIdFilter
+ Queries::Register.filter query, filter_ns::ContextFilter
+
+ order_ns = Queries::Capabilities::Orders
+
+ Queries::Register.order query, order_ns::IdOrder
+end
diff --git a/app/models/queries/capabilities/capability_query.rb b/app/models/queries/capabilities/capability_query.rb
new file mode 100644
index 00000000000..2af6664c1b1
--- /dev/null
+++ b/app/models/queries/capabilities/capability_query.rb
@@ -0,0 +1,58 @@
+#-- 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 Queries::Capabilities::CapabilityQuery < Queries::BaseQuery
+ def self.model
+ Capability
+ end
+
+ def results
+ super
+ .reorder('action ASC', 'principal_id ASC', 'capabilities.context_id ASC')
+ end
+
+ def default_scope
+ Capability
+ .default
+ .distinct
+ end
+
+ validate :minimum_filters_set
+
+ private
+
+ def minimum_filters_set
+ any_required = filters.any? do |filter|
+ [Queries::Capabilities::Filters::PrincipalIdFilter,
+ Queries::Capabilities::Filters::ContextFilter,
+ Queries::Capabilities::Filters::IdFilter].include?(filter.class) && filter.operator == '='
+ end
+
+ errors.add(:filters, I18n.t('activerecord.errors.models.capability.query.filters.minimum')) unless any_required
+ end
+end
diff --git a/app/models/queries/capabilities/filters/capability_filter.rb b/app/models/queries/capabilities/filters/capability_filter.rb
new file mode 100644
index 00000000000..a7e70568c9b
--- /dev/null
+++ b/app/models/queries/capabilities/filters/capability_filter.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.
+#++
+
+class Queries::Capabilities::Filters::CapabilityFilter < Queries::Filters::Base
+ self.model = Capability
+
+ def human_name
+ Capability.human_attribute_name(name)
+ end
+
+ def where
+ operator_strategy.sql_for_field(values, 'capabilities', self.class.key)
+ end
+end
diff --git a/app/models/queries/capabilities/filters/context_filter.rb b/app/models/queries/capabilities/filters/context_filter.rb
new file mode 100644
index 00000000000..75f9a395370
--- /dev/null
+++ b/app/models/queries/capabilities/filters/context_filter.rb
@@ -0,0 +1,54 @@
+#-- 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 Queries::Capabilities::Filters::ContextFilter < Queries::Capabilities::Filters::CapabilityFilter
+ include Queries::Filters::Shared::ParsedFilter
+
+ private
+
+ def split_values
+ values.map do |value|
+ if (matches = value.match(/\A([gp])(\d*)\z/))
+ {
+ context_key: matches[1],
+ context_id: matches[2]
+ }
+ end
+ end
+ end
+
+ def value_conditions
+ split_values.map do |value|
+ if value[:context_id].present?
+ "context_id = #{value[:context_id]}"
+ else
+ "context_id IS NULL"
+ end
+ end
+ end
+end
diff --git a/app/models/queries/capabilities/filters/id_filter.rb b/app/models/queries/capabilities/filters/id_filter.rb
new file mode 100644
index 00000000000..c4a96926617
--- /dev/null
+++ b/app/models/queries/capabilities/filters/id_filter.rb
@@ -0,0 +1,60 @@
+#-- 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 Queries::Capabilities::Filters::IdFilter < Queries::Capabilities::Filters::CapabilityFilter
+ include Queries::Filters::Shared::ParsedFilter
+
+ private
+
+ def split_values
+ values.map do |value|
+ if (matches = value.match(/\A(\w+\/\w+)\/([pg])(\d*)-(\d+)\z/))
+ {
+ action: matches[1],
+ context_key: matches[2],
+ context_id: matches[3],
+ principal_id: matches[4]
+ }
+ end
+ end
+ end
+
+ def value_conditions
+ split_values.map do |value|
+ conditions = ["action = '#{value[:action]}' AND principal_id = #{value[:principal_id]}"]
+
+ conditions << if value[:context_id].present?
+ ["context_id = #{value[:context_id]}"]
+ else
+ ["context_id IS NULL"]
+ end
+
+ "(#{conditions.join(' AND ')})"
+ end
+ end
+end
diff --git a/app/models/queries/capabilities/filters/principal_id_filter.rb b/app/models/queries/capabilities/filters/principal_id_filter.rb
new file mode 100644
index 00000000000..2094298d336
--- /dev/null
+++ b/app/models/queries/capabilities/filters/principal_id_filter.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.
+#++
+
+class Queries::Capabilities::Filters::PrincipalIdFilter < Queries::Capabilities::Filters::CapabilityFilter
+ def type
+ :integer
+ end
+end
diff --git a/app/models/queries/capabilities/orders/id_order.rb b/app/models/queries/capabilities/orders/id_order.rb
new file mode 100644
index 00000000000..b70403e5024
--- /dev/null
+++ b/app/models/queries/capabilities/orders/id_order.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.
+#++
+
+class Queries::Capabilities::Orders::IdOrder < Queries::BaseOrder
+ self.model = Capability
+
+ def self.key
+ :id
+ end
+
+ def name
+ :action
+ end
+end
diff --git a/app/models/queries/filters/shared/parsed_filter.rb b/app/models/queries/filters/shared/parsed_filter.rb
new file mode 100644
index 00000000000..81e8af51cb7
--- /dev/null
+++ b/app/models/queries/filters/shared/parsed_filter.rb
@@ -0,0 +1,63 @@
+#-- 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 Queries::Filters::Shared::ParsedFilter
+ def type
+ :string
+ end
+
+ def where
+ case operator
+ when '='
+ value_conditions.join(' OR ')
+ when '!'
+ "NOT #{value_conditions.join(' AND NOT ')}"
+ end
+ end
+
+ def available_operators
+ [Queries::Operators::Equals,
+ Queries::Operators::NotEquals]
+ end
+
+ private
+
+ def split_values
+ raise NotImplementedError
+ end
+
+ def value_conditions
+ raise NotImplementedError
+ end
+
+ def validate_values
+ super
+
+ errors.add(:values, "malformed value") if split_values.any?(&:nil?)
+ end
+end
diff --git a/app/models/query.rb b/app/models/query.rb
index 9c6a5b431f8..c87e0f7f3e3 100644
--- a/app/models/query.rb
+++ b/app/models/query.rb
@@ -316,7 +316,7 @@ class Query < ApplicationRecord
.detect { |candidate| candidate.name == attribute }
end
- def sorted?
+ def ordered?
sort_criteria.any?
end
diff --git a/config/constants/ar_to_api_conversions.rb b/config/constants/ar_to_api_conversions.rb
index ee8f0c265ce..91a431329b9 100644
--- a/config/constants/ar_to_api_conversions.rb
+++ b/config/constants/ar_to_api_conversions.rb
@@ -47,6 +47,7 @@ module Constants
message: 'post',
firstname: 'firstName',
lastname: 'lastName',
+ member: 'membership'
}.freeze
# Conversions that are unidirectional (from the API to AR)
diff --git a/config/initializers/permissions.rb b/config/initializers/permissions.rb
index cbdfbbde1e0..8d9e3271679 100644
--- a/config/initializers/permissions.rb
+++ b/config/initializers/permissions.rb
@@ -47,7 +47,8 @@ OpenProject::AccessControl.map do |map|
map.permission :add_project,
{ projects: %i[new create] },
require: :loggedin,
- global: true
+ global: true,
+ contract_actions: { projects: %i[create] }
map.permission :manage_user,
{
@@ -56,7 +57,8 @@ OpenProject::AccessControl.map do |map|
admin: %i[index]
},
require: :loggedin,
- global: true
+ global: true,
+ contract_actions: { users: %i[create read update] }
map.permission :manage_placeholder_user,
{
@@ -65,7 +67,8 @@ OpenProject::AccessControl.map do |map|
admin: %i[index]
},
require: :loggedin,
- global: true
+ global: true,
+ contract_actions: { placeholder_users: %i[create read update] }
map.permission :view_project,
{ projects: [:show],
@@ -78,7 +81,8 @@ OpenProject::AccessControl.map do |map|
map.permission :edit_project,
edit_project_hash,
- require: :member
+ require: :member,
+ contract_actions: { projects: %i[update] }
map.permission :select_project_modules,
{ projects: :modules },
@@ -87,10 +91,12 @@ OpenProject::AccessControl.map do |map|
map.permission :manage_members,
{ members: %i[index new create update destroy autocomplete_for_member] },
require: :member,
- dependencies: :view_members
+ dependencies: :view_members,
+ contract_actions: { members: %i[create update destroy] }
map.permission :view_members,
- { members: [:index] }
+ { members: [:index] },
+ contract_actions: { members: %i[read] }
map.permission :manage_versions,
{
@@ -115,13 +121,15 @@ OpenProject::AccessControl.map do |map|
end
map.project_module :work_package_tracking, order: 90 do |wpt|
- # Issues
wpt.permission :view_work_packages,
- versions: %i[index show status_by],
- journals: %i[index diff],
- work_packages: %i[show index],
- work_packages_api: [:get],
- 'work_packages/reports': %i[report report_details]
+ {
+ versions: %i[index show status_by],
+ journals: %i[index diff],
+ work_packages: %i[show index],
+ work_packages_api: [:get],
+ 'work_packages/reports': %i[report report_details]
+ },
+ contract_actions: { work_packages: %i[read] }
wpt.permission :add_work_packages,
{}
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 233123a20f4..6022872d7a2 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -609,6 +609,12 @@ en:
unremovable: "cannot be removed."
wrong_length: "is the wrong length (should be %{count} characters)."
models:
+ capability:
+ context:
+ global: 'Global'
+ query:
+ filters:
+ minimum: "need to include at least a one filter for principal, context or id with the '=' operator."
custom_field:
at_least_one_custom_option: "At least one option needs to be available."
custom_actions:
@@ -2799,6 +2805,9 @@ en:
invalid_json: "The request could not be parsed as JSON."
invalid_relation: "The relation is invalid."
invalid_resource: "For property '%{property}' a link like '%{expected}' is expected, but got '%{actual}'."
+ invalid_signal:
+ embed: "The requested embedding of %{invalid} is not supported. Supported embeddings are %{supported}."
+ select: "The requested select of %{invalid} is not supported. Supported selects are %{supported}."
invalid_user_status_transition: "The current user account status does not allow this operation."
missing_content_type: "not specified"
missing_request_body: "There was no request body."
diff --git a/docs/api/apiv3/endpoints/users.apib b/docs/api/apiv3/endpoints/users.apib
index a6ba701ed87..0f22aeaeb67 100644
--- a/docs/api/apiv3/endpoints/users.apib
+++ b/docs/api/apiv3/endpoints/users.apib
@@ -6,7 +6,7 @@
| lock | Restrict the user from logging in and performing any actions | not locked; **Permission**: Administrator |
| show | Link to the OpenProject user page (HTML) | |
| unlock | Allow a locked user to login and act again | locked; **Permission**: Administrator |
-| updateImmediately | Updates the user's attributes. | **Permission**: Administrator, manage_users global permission |
+| updateImmediately | Updates the user's attributes. | **Permission**: Administrator, manage_user global permission |
| delete | Permanently remove a user from the instance | **Permission**: Administrator, self-delete |
## Linked Properties
@@ -25,15 +25,15 @@ Depending on custom fields defined for users, additional links might exist.
| Property | Description | Type | Constraints | Supported operations | Condition |
| :----------: | --------------------------------------------------------- | -------- | ---------------------------------------------------- | -------------------- | ----------------------------------------------------------- |
| id | User's id | Integer | x > 0 | READ | |
-| login | User's login name | String | unique, 256 max length | READ / WRITE | **Permission**: Administrator, manage_users global permission |
-| firstName | User's first name | String | 30 max length | READ / WRITE | **Permission**: Administrator, manage_users global permission |
-| lastName | User's last name | String | 30 max length | READ / WRITE | **Permission**: Administrator, manage_users global permission |
+| login | User's login name | String | unique, 256 max length | READ / WRITE | **Permission**: Administrator, manage_user global permission |
+| firstName | User's first name | String | 30 max length | READ / WRITE | **Permission**: Administrator, manage_user global permission |
+| lastName | User's last name | String | 30 max length | READ / WRITE | **Permission**: Administrator, manage_user global permission |
| name | User's full name, formatting depends on instance settings | String | | READ | |
-| email | User's email address | String | unique, 60 max length | READ / WRITE | E-Mail address not hidden, **Permission**: Administrator, manage_users global permission |
+| email | User's email address | String | unique, 60 max length | READ / WRITE | E-Mail address not hidden, **Permission**: Administrator, manage_user global permission |
| admin | Flag indicating whether or not the user is an admin | Boolean | in: [true, false] | READ / WRITE | **Permission**: Administrator |
| avatar | URL to user's avatar | Url | | READ | |
| status | The current activation status of the user (see below) | String | in: ["active", "registered", "locked", "invited"] | READ | |
-| language | User's language | String | ISO 639-1 | READ / WRITE | **Permission**: Administrator, manage_users global permission |
+| language | User's language | String | ISO 639-1 | READ / WRITE | **Permission**: Administrator, manage_user global permission |
| password | User's password for the default password authentication | String | | WRITE | **Permission**: Administrator |
| identity_url | User's identity_url for OmniAuth authentication | String | | READ / WRITE | **Permission**: Administrator |
| createdAt | Time of creation | DateTime | | READ | |
@@ -135,7 +135,7 @@ Please note that custom fields are not yet supported by the api although the bac
## Create User [POST]
-Creates a new user. Only administrators and users with manage_users global permission are allowed to do so.
+Creates a new user. Only administrators and users with manage_user global permission are allowed to do so.
When calling this endpoint the client provides a single object, containing at least the properties and links that are required, in the body.
Valid values for `status`:
@@ -267,7 +267,7 @@ When calling this endpoint the client provides a single object, containing at le
Returned if the client does not have sufficient permissions.
- **Required permission:** Administrators, manage_users global permission
+ **Required permission:** Administrators, manage_user global permission
+ Body
@@ -520,7 +520,7 @@ Permanently deletes the specified user account.
## List Users [GET]
-Lists users. Only administrators or users with manage_users global permission have permission to do this.
+Lists users. Only administrators or users with manage_user global permission have permission to do this.
+ Parameters
+ offset = `1` (optional, integer, `25`) ... Page number inside the requested collection.
diff --git a/lib/api/decorators/offset_paginated_collection.rb b/lib/api/decorators/offset_paginated_collection.rb
index e93c9e12f22..69429ac0606 100644
--- a/lib/api/decorators/offset_paginated_collection.rb
+++ b/lib/api/decorators/offset_paginated_collection.rb
@@ -41,9 +41,7 @@ module API
@self_link_base = self_link
@query = query
@page = page.to_i > 0 ? page.to_i : 1
- @per_page = [per_page || self.class.per_page_default(models), maximum_page_size]
- .map(&:to_i)
- .min
+ @per_page = resulting_page_size(per_page, models)
full_self_link = make_page_link(page: @page, page_size: @per_page)
paged = paged_models(models)
diff --git a/lib/api/decorators/query_params_representer.rb b/lib/api/decorators/query_params_representer.rb
new file mode 100644
index 00000000000..1cb146a939c
--- /dev/null
+++ b/lib/api/decorators/query_params_representer.rb
@@ -0,0 +1,88 @@
+#-- 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.
+#++
+
+# Other than the Roar based representers of the api v3, this
+# representer is only responsible for transforming a query's
+# attributes into a hash which in turn can be used e.g. to be displayed
+# in a url
+
+module API
+ module Decorators
+ class QueryParamsRepresenter
+ def initialize(query)
+ self.query = query
+ end
+
+ ##
+ # To json hash outputs the hash to be parsed to the frontend http
+ # which contains a reference to the columns array as columns[].
+ # This will match the Rails +to_query+ output
+ def to_json(*_args)
+ to_h.to_json
+ end
+
+ def to_h(*args)
+ p = default_hash
+
+ p[:sortBy] = orders_to_v3 if query.ordered?
+
+ # an empty filter param is also relevant as this would mean to not apply
+ # the default filter (status - open)
+ p[:filters] = filters_to_v3
+
+ p
+ end
+
+ private
+
+ def orders_to_v3
+ converted = query.orders.map { |order| [convert_to_v3(order.attribute), order.direction] }
+
+ JSON::dump(converted)
+ end
+
+ def filters_to_v3
+ converted = query.filters.map do |filter|
+ { convert_to_v3(filter.name) => { operator: filter.operator, values: filter.values } }
+ end
+
+ JSON::dump(converted)
+ end
+
+ def convert_to_v3(attribute)
+ ::API::Utilities::PropertyNameConverter.from_ar_name(attribute).to_sym
+ end
+
+ def default_hash
+ { offset: 1, pageSize: Setting.per_page_options_array.first }
+ end
+
+ attr_accessor :query
+ end
+ end
+end
diff --git a/lib/api/decorators/sql/hal.rb b/lib/api/decorators/sql/hal.rb
new file mode 100644
index 00000000000..9b888343ab4
--- /dev/null
+++ b/lib/api/decorators/sql/hal.rb
@@ -0,0 +1,251 @@
+#-- 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-2017 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 API
+ module Decorators
+ module Sql
+ module Hal
+ extend ActiveSupport::Concern
+
+ included do
+ extend ::API::V3::Utilities::PathHelper
+
+ class_attribute :embed_map,
+ default: {}
+ class_attribute :properties,
+ default: {}
+ class_attribute :links,
+ default: {}
+ class_attribute :embeddeds,
+ default: {}
+ end
+
+ class_methods do
+ def properties_sql(select, walker_results)
+ selected_properties(select)
+ .map do |name, options|
+ representation = if options[:representation]
+ options[:representation].call(walker_results)
+ else
+ options[:column]
+ end
+
+ "'#{name}', #{representation}"
+ end.join(', ')
+ end
+
+ def property(name,
+ column: name,
+ representation: nil,
+ render_if: nil)
+ properties[name] = { column: column, render_if: render_if, representation: representation }
+ end
+
+ def joins(select, scope)
+ selected_links(select)
+ .select { |_, link| link[:join] }
+ .map do |name, link|
+ join = "LEFT OUTER JOIN #{link[:join][:table]} #{name.to_s.pluralize} ON #{link[:join][:condition]}"
+
+ scope = scope.joins(join).select(link[:join][:select])
+ end
+
+ scope
+ end
+
+ def link(name, column: nil, path: nil, title: nil, href: nil, join: nil, render_if: nil, **additional_properties)
+ links[name] = { column: column,
+ path: path,
+ title: title,
+ join: join,
+ href: href,
+ render_if: render_if,
+ additional_properties: additional_properties }
+ end
+
+ def links_selects(select, walker_result)
+ selected_links(select)
+ .map do |name, link|
+ path_name = link[:path] ? link[:path][:api] : name
+ title = link[:title] ? link[:title].call : "#{name}.name"
+ column = link[:column] ? link[:column].call : name
+
+ href = link[:href] ? link[:href].call(walker_result) : "format('#{api_v3_paths.send(path_name, '%s')}', #{column})"
+
+ link_attributes = ["'href'", href]
+
+ if title
+ link_attributes += ["'title'", title]
+ end
+
+ (link[:additional_properties] || {}).each do |key, value|
+ link_attributes += ["'#{key}'", value]
+ end
+
+ if link[:render_if]
+ <<-SQL
+ '#{name}',
+ CASE WHEN #{link[:render_if].call(walker_result)} THEN
+ json_build_object(#{link_attributes.join(', ')})
+ ELSE
+ NULL
+ END
+ SQL
+ else
+ <<-SQL
+ '#{name}', json_build_object(#{link_attributes.join(', ')})
+ SQL
+ end
+ end
+ .join(', ')
+ end
+
+ def embedded(name,
+ representation: nil)
+ embeddeds[name] = { representation: representation }
+ end
+
+ def embedded_selects(_selects, walker_results)
+ # TODO: This does not yet support signaling
+ embeddeds
+ .map do |name, link|
+
+ representation = if link[:representation]
+ link[:representation].call(walker_results)
+ else
+ link[:column]
+ end
+
+ <<-SQL
+ '#{name}', #{representation}
+ SQL
+ end
+ .join(', ')
+ end
+
+ def select_sql(select, walker_result)
+ <<~SELECT
+ json_strip_nulls(json_build_object(
+ #{[properties_sql(select, walker_result),
+ select_links(select, walker_result),
+ select_embedded(select, walker_result)].compact.join(', ')}
+ ))
+ SELECT
+ end
+
+ def ctes(_walker_result)
+ {}
+ end
+
+ def to_sql(walker_result)
+ ctes = walker_result.ctes.map do |key, sql|
+ <<~SQL
+ #{key} AS (
+ #{sql}
+ )
+ SQL
+ end
+
+ ctes_sql = ctes.any? ? "WITH #{ctes.join(', ')}" : ""
+
+ <<~SQL
+ #{ctes_sql}
+
+ SELECT
+ #{walker_result.selects} AS json
+ FROM
+ #{select_from(walker_result)}
+ SQL
+ end
+
+ private
+
+ def select_embedded(select, walker_result)
+ embedded = embedded_selects(select, walker_result)
+
+ if embedded.present?
+ <<~SQL
+ '_embedded', json_strip_nulls(json_build_object(
+ #{embedded_selects(select, walker_result)}
+ ))
+ SQL
+ end
+ end
+
+ def select_links(select, walker_result)
+ <<~SELECT
+ '_links', json_strip_nulls(json_build_object(
+ #{links_selects(select, walker_result)}
+ ))
+ SELECT
+ end
+
+ def select_from(walker_result)
+ "(#{walker_result.scope.to_sql}) element"
+ end
+
+ def selected_links(select)
+ selected(select, links)
+ end
+
+ def selected_properties(select)
+ selected(select, properties)
+ end
+
+ def selected(select, list)
+ selects = cleaned_selects(select)
+
+ ensure_valid_selects(selects)
+
+ if selects.include?(:*)
+ list
+ else
+ list.slice(*selects)
+ end
+ end
+
+ def cleaned_selects(select)
+ select
+ .symbolize_keys
+ .select { |_, v| v.empty? }
+ .keys
+ end
+
+ def ensure_valid_selects(requested)
+ supported = links.keys + properties.keys + [:*]
+ invalid = requested - supported
+
+ raise API::Errors::InvalidSignal.new(invalid, supported, :select) if invalid.any?
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/api/decorators/sql_collection_representer.rb b/lib/api/decorators/sql_collection_representer.rb
new file mode 100644
index 00000000000..c0308427779
--- /dev/null
+++ b/lib/api/decorators/sql_collection_representer.rb
@@ -0,0 +1,111 @@
+#-- 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 API
+ module Decorators
+ class SqlCollectionRepresenter
+ include API::Decorators::Sql::Hal
+
+ class << self
+ def ctes(walker_result)
+ {
+ all_elements: walker_result.scope.to_sql,
+ page_elements: "SELECT * FROM all_elements LIMIT #{sql_limit(walker_result)} OFFSET #{sql_offset(walker_result)}",
+ total: "SELECT COUNT(*) from all_elements"
+ }
+ end
+
+ private
+
+ def select_from(walker_result)
+ "page_elements"
+ end
+
+ def full_self_path(walker_results, overrides = {})
+ "#{walker_results.self_path}?#{href_query(walker_results, overrides)}"
+ end
+
+ def href_query(walker_results, overrides)
+ walker_results.url_query.merge(overrides).to_query
+ end
+
+ def sql_offset(walker_result)
+ (walker_result.offset - 1) * walker_result.page_size
+ end
+
+ def sql_limit(walker_result)
+ walker_result.page_size
+ end
+ end
+
+ property :_type,
+ representation: ->(*) { "'Collection'" }
+
+ property :count,
+ representation: ->(*) { "COUNT(*)" }
+
+ property :total,
+ representation: ->(*) { "(SELECT * from total)" }
+
+ property :pageSize,
+ representation: ->(walker_result) { walker_result.page_size }
+
+ property :offset,
+ representation: ->(walker_result) { walker_result.offset }
+
+ link :self,
+ href: ->(walker_result) { "'#{full_self_path(walker_result)}'" },
+ title: -> { nil }
+
+ link :jumpTo,
+ href: ->(walker_result) { "'#{full_self_path(walker_result, offset: '{offset}')}'" },
+ title: -> { nil },
+ templated: true
+
+ link :changeSize,
+ href: ->(walker_result) { "'#{full_self_path(walker_result, pageSize: '{size}')}'" },
+ title: -> { nil },
+ templated: true
+
+ link :previousByOffset,
+ href: ->(walker_result) { "'#{full_self_path(walker_result, offset: walker_result.offset - 1)}'" },
+ render_if: ->(walker_result) { walker_result.offset > 1 },
+ title: -> { nil }
+
+ link :nextByOffset,
+ href: ->(walker_result) { "'#{full_self_path(walker_result, offset: walker_result.offset + 1)}'" },
+ render_if: ->(walker_result) { "#{walker_result.offset * walker_result.page_size} < (SELECT * FROM total)" },
+ title: -> { nil }
+
+ embedded :elements,
+ representation: ->(walker_result) do
+ "json_agg(#{walker_result.replace_map['elements']})"
+ end
+ end
+ end
+end
diff --git a/lib/api/errors/invalid_signal.rb b/lib/api/errors/invalid_signal.rb
new file mode 100644
index 00000000000..b9cac27f87c
--- /dev/null
+++ b/lib/api/errors/invalid_signal.rb
@@ -0,0 +1,45 @@
+#-- 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 API
+ module Errors
+ class InvalidSignal < ErrorBase
+ identifier 'InvalidSignal'
+ code 400
+
+ def initialize(invalid, supported, type)
+ message = I18n.t("api_v3.errors.invalid_signal.#{type}",
+ invalid: Array(invalid).join(', '),
+ supported: Array(supported).join(', '))
+ super message
+ end
+ end
+ end
+end
diff --git a/lib/api/utilities/page_size_helper.rb b/lib/api/utilities/page_size_helper.rb
index 5c2d847fa6d..b3a1775d97c 100644
--- a/lib/api/utilities/page_size_helper.rb
+++ b/lib/api/utilities/page_size_helper.rb
@@ -48,6 +48,18 @@ module API
resolved_value
end
+ ##
+ # Determine the page size from the minimum of
+ # * the provided value
+ # * the page size specified for the relation (per_page)
+ # * the minimum of the per page options specified in the settings
+ # * the maximum page size
+ def resulting_page_size(value, relation = nil)
+ [value || relation&.base_class&.per_page || Setting.per_page_options_array.min, maximum_page_size]
+ .map(&:to_i)
+ .min
+ end
+
##
# Get the maximum allowed page size from
# the largest option of per_page size,
diff --git a/lib/api/v3/actions/action_sql_collection_representer.rb b/lib/api/v3/actions/action_sql_collection_representer.rb
new file mode 100644
index 00000000000..f4f8a4d36d2
--- /dev/null
+++ b/lib/api/v3/actions/action_sql_collection_representer.rb
@@ -0,0 +1,39 @@
+#-- 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 API
+ module V3
+ module Actions
+ class ActionSqlCollectionRepresenter < API::Decorators::SqlCollectionRepresenter
+ self.embed_map = {
+ elements: ActionSqlRepresenter
+ }.with_indifferent_access
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/actions/action_sql_representer.rb b/lib/api/v3/actions/action_sql_representer.rb
new file mode 100644
index 00000000000..1fdd16352a2
--- /dev/null
+++ b/lib/api/v3/actions/action_sql_representer.rb
@@ -0,0 +1,47 @@
+#-- 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-2017 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 API
+ module V3
+ module Actions
+ class ActionSqlRepresenter
+ include API::Decorators::Sql::Hal
+
+ property :_type,
+ representation: ->(*) { "'Action'" }
+
+ property :id
+
+ link :self,
+ path: { api: :action, params: %w(action) },
+ column: -> { :id },
+ title: -> { nil }
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/actions/actions_api.rb b/lib/api/v3/actions/actions_api.rb
new file mode 100644
index 00000000000..15d94b59a8d
--- /dev/null
+++ b/lib/api/v3/actions/actions_api.rb
@@ -0,0 +1,50 @@
+#-- 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 API
+ module V3
+ module Actions
+ class ActionsAPI < ::API::OpenProjectAPI
+ resources :actions do
+ get &API::V3::Utilities::Endpoints::SqlIndex
+ .new(model: Action)
+ .mount
+
+ params do
+ requires :id, type: String, desc: 'The action identifier'
+ end
+ namespace '*id' do
+ get &API::V3::Utilities::Endpoints::SqlShow
+ .new(model: Action)
+ .mount
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/capabilities/capabilities_api.rb b/lib/api/v3/capabilities/capabilities_api.rb
new file mode 100644
index 00000000000..8f2dd624db5
--- /dev/null
+++ b/lib/api/v3/capabilities/capabilities_api.rb
@@ -0,0 +1,54 @@
+#-- 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 API
+ module V3
+ module Capabilities
+ class CapabilitiesAPI < ::API::OpenProjectAPI
+ resources :capabilities do
+ get &API::V3::Utilities::Endpoints::SqlIndex
+ .new(model: Capability)
+ .mount
+
+ namespace :contexts do
+ mount API::V3::Capabilities::Contexts::GlobalAPI
+ end
+
+ params do
+ requires :id, type: String, desc: 'The capability identifier'
+ end
+ namespace '*id' do
+ get &API::V3::Utilities::Endpoints::SqlShow
+ .new(model: Capability)
+ .mount
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/capabilities/capability_sql_collection_representer.rb b/lib/api/v3/capabilities/capability_sql_collection_representer.rb
new file mode 100644
index 00000000000..e1f43041d67
--- /dev/null
+++ b/lib/api/v3/capabilities/capability_sql_collection_representer.rb
@@ -0,0 +1,39 @@
+#-- 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 API
+ module V3
+ module Capabilities
+ class CapabilitySqlCollectionRepresenter < API::Decorators::SqlCollectionRepresenter
+ self.embed_map = {
+ elements: CapabilitySqlRepresenter
+ }.with_indifferent_access
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/capabilities/capability_sql_representer.rb b/lib/api/v3/capabilities/capability_sql_representer.rb
new file mode 100644
index 00000000000..2e5521deaa6
--- /dev/null
+++ b/lib/api/v3/capabilities/capability_sql_representer.rb
@@ -0,0 +1,122 @@
+#-- 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-2017 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 API
+ module V3
+ module Capabilities
+ class CapabilitySqlRepresenter
+ include API::Decorators::Sql::Hal
+
+ property :_type,
+ representation: ->(*) { "'Capability'" }
+
+ property :id,
+ representation: ->(*) {
+ <<~SQL
+ CASE
+ WHEN context_id IS NULL THEN action || '/g-' || principal_id
+ ELSE action || '/p' || context_id || '-' || principal_id
+ END
+ SQL
+ }
+
+ link :self,
+ path: { api: :capability, params: %w(action) },
+ column: -> {
+ <<~SQL
+ CASE
+ WHEN context_id IS NULL THEN action || '/g-' || principal_id
+ ELSE action || '/p' || context_id || '-' || principal_id
+ END
+ SQL
+ },
+ title: -> { nil }
+
+ link :action,
+ path: { api: :action, params: %w(action) },
+ title: -> { nil }
+
+ link :context,
+ href: ->(*) {
+ <<~SQL
+ CASE
+ WHEN context_id IS NULL THEN '#{api_v3_paths.capabilities_contexts_global}'
+ ELSE format('#{api_v3_paths.project('%s')}', context_id)
+ END
+ SQL
+ },
+ title: ->(*) {
+ <<~SQL
+ CASE
+ WHEN context_id IS NULL THEN '#{I18n.t('activerecord.errors.models.capability.context.global')}'
+ ELSE context_name
+ END
+ SQL
+ },
+ join: { table: :projects,
+ condition: "contexts.id = capabilities.context_id",
+ select: ['contexts.name context_name'] }
+
+ link :principal,
+ href: ->(*) {
+ <<~SQL
+ CASE principal_type
+ WHEN 'Group' THEN format('#{api_v3_paths.group('%s')}', principal_id)
+ WHEN 'PlaceholderUser' THEN format('#{api_v3_paths.placeholder_user('%s')}', principal_id)
+ ELSE format('#{api_v3_paths.user('%s')}', principal_id)
+ END
+ SQL
+ },
+ title: -> {
+ join_string = if Setting.user_format == :lastname_coma_firstname
+ " || ', ' || "
+ else
+ " || ' ' || "
+ end
+
+ <<~SQL
+ CASE principal_type
+ WHEN 'Group' THEN lastname
+ WHEN 'PlaceholderUser' THEN lastname
+ ELSE #{User::USER_FORMATS_STRUCTURE[Setting.user_format].map { |p| p }.join(join_string)}
+ END
+ SQL
+ },
+ join: { table: :users,
+ condition: "principals.id = capabilities.principal_id",
+ select: ['principals.firstname',
+ 'principals.lastname',
+ 'principals.login',
+ 'principals.mail',
+ 'principals.type principal_type'] }
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/work_packages/work_package_list_representer.rb b/lib/api/v3/capabilities/contexts/global_api.rb
similarity index 76%
rename from lib/api/v3/work_packages/work_package_list_representer.rb
rename to lib/api/v3/capabilities/contexts/global_api.rb
index 23a9fe4f3c6..8eb9082d875 100644
--- a/lib/api/v3/work_packages/work_package_list_representer.rb
+++ b/lib/api/v3/capabilities/contexts/global_api.rb
@@ -1,5 +1,3 @@
-#-- encoding: UTF-8
-
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) 2012-2021 the OpenProject GmbH
@@ -30,14 +28,15 @@
module API
module V3
- module WorkPackages
- class WorkPackageListRepresenter < ::API::Decorators::UnpaginatedCollection
- element_decorator ::API::V3::WorkPackages::WorkPackageRepresenter
-
- def initialize(models, self_link, current_user:)
- super
-
- @represented = ::API::V3::WorkPackages::WorkPackageEagerLoadingWrapper.wrap(represented, current_user)
+ module Capabilities
+ module Contexts
+ class GlobalAPI < ::API::OpenProjectAPI
+ resources :global do
+ get do
+ Contexts::GlobalRepresenter.create(nil,
+ current_user: current_user)
+ end
+ end
end
end
end
diff --git a/lib/api/v3/capabilities/contexts/global_representer.rb b/lib/api/v3/capabilities/contexts/global_representer.rb
new file mode 100644
index 00000000000..1cda71586e7
--- /dev/null
+++ b/lib/api/v3/capabilities/contexts/global_representer.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 API
+ module V3
+ module Capabilities
+ module Contexts
+ class GlobalRepresenter < ::API::Decorators::Single
+ link :self do
+ api_v3_paths.capabilities_contexts_global
+ end
+
+ property :id,
+ getter: ->(*) { 'global' }
+
+ def _type
+ 'CapabilityContext'
+ end
+
+ def model_required?
+ false
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/queries/query_params_representer.rb b/lib/api/v3/queries/query_params_representer.rb
index d4ba93e040e..c4b1c4f0491 100644
--- a/lib/api/v3/queries/query_params_representer.rb
+++ b/lib/api/v3/queries/query_params_representer.rb
@@ -36,11 +36,7 @@
module API
module V3
module Queries
- class QueryParamsRepresenter
- def initialize(query)
- self.query = query
- end
-
+ class QueryParamsRepresenter < API::Decorators::QueryParamsRepresenter
##
# To json hash outputs the hash to be parsed to the frontend http
# which contains a reference to the columns array as columns[].
@@ -59,18 +55,13 @@ module API
end
def to_h(column_key: :columns)
- p = default_hash
+ p = super
p[:showHierarchies] = query.show_hierarchies
p[:showSums] = query.display_sums?
p[:groupBy] = query.group_by if query.group_by?
- p[:sortBy] = sort_criteria_to_v3 if query.sorted?
p[column_key] = columns_to_v3 unless query.has_default_columns?
- # an empty filter param is also relevant as this would mean to not apply
- # the default filter (status - open)
- p[:filters] = filters_to_v3
-
p
end
@@ -84,30 +75,14 @@ module API
private
- def columns_to_v3
- query.column_names.map { |name| convert_to_v3(name) }
- end
-
- def sort_criteria_to_v3
+ def orders_to_v3
converted = query.sort_criteria.map { |first, last| [convert_to_v3(first), last] }
JSON::dump(converted)
end
- def filters_to_v3
- converted = query.filters.map do |filter|
- { convert_to_v3(filter.name) => { operator: filter.operator, values: filter.values } }
- end
-
- JSON::dump(converted)
- end
-
- def convert_to_v3(attribute)
- ::API::Utilities::PropertyNameConverter.from_ar_name(attribute).to_sym
- end
-
- def default_hash
- { offset: 1, pageSize: Setting.per_page_options_array.first }
+ def columns_to_v3
+ query.column_names.map { |name| convert_to_v3(name) }
end
attr_accessor :query
diff --git a/lib/api/v3/root.rb b/lib/api/v3/root.rb
index b035f59bfb2..4c14a700936 100644
--- a/lib/api/v3/root.rb
+++ b/lib/api/v3/root.rb
@@ -42,8 +42,10 @@ module API
transform_eprops
end
+ mount ::API::V3::Actions::ActionsAPI
mount ::API::V3::Activities::ActivitiesAPI
mount ::API::V3::Attachments::AttachmentsAPI
+ mount ::API::V3::Capabilities::CapabilitiesAPI
mount ::API::V3::Categories::CategoriesAPI
mount ::API::V3::Configuration::ConfigurationAPI
mount ::API::V3::CustomActions::CustomActionsAPI
diff --git a/lib/api/v3/utilities/endpoints/index.rb b/lib/api/v3/utilities/endpoints/index.rb
index 9d4e7d82fae..0a0809c06e3 100644
--- a/lib/api/v3/utilities/endpoints/index.rb
+++ b/lib/api/v3/utilities/endpoints/index.rb
@@ -31,8 +31,6 @@ module API
module Utilities
module Endpoints
class Index < API::Utilities::Endpoints::Index
- include ::API::Utilities::PageSizeHelper
-
def mount
index = self
@@ -75,18 +73,21 @@ module API
results = merge_scopes(base_scope, query.results)
if paginated_representer?
- render_paginated_success(results, params, self_path)
+ render_paginated_success(results, query, params, self_path)
else
render_unpaginated_success(results, self_path)
end
end
- def render_paginated_success(results, params, self_path)
+ def render_paginated_success(results, query, params, self_path)
+ resulting_params = calculate_resulting_params(query, params)
+
render_representer
.new(results,
self_link: self_path,
- page: to_i_or_nil(params[:offset]),
- per_page: resolve_page_size(params[:pageSize]),
+ query: resulting_params,
+ page: resulting_params[:offset],
+ per_page: resulting_params[:pageSize],
current_user: User.current)
end
@@ -97,6 +98,19 @@ module API
current_user: User.current)
end
+ def calculate_resulting_params(query, provided_params)
+ calculate_default_params(query).merge(provided_params.slice('offset', 'pageSize').symbolize_keys).tap do |params|
+ params[:offset] = to_i_or_nil(params[:offset])
+ params[:pageSize] = to_i_or_nil(params[:pageSize])
+ end
+ end
+
+ def calculate_default_params(query)
+ ::API::Decorators::QueryParamsRepresenter
+ .new(query)
+ .to_h
+ end
+
def paginated_representer?
render_representer.ancestors.include?(::API::Decorators::OffsetPaginatedCollection)
end
diff --git a/lib/api/v3/utilities/endpoints/sql_index.rb b/lib/api/v3/utilities/endpoints/sql_index.rb
new file mode 100644
index 00000000000..12d8ff3dc13
--- /dev/null
+++ b/lib/api/v3/utilities/endpoints/sql_index.rb
@@ -0,0 +1,60 @@
+#-- 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 API
+ module V3
+ module Utilities
+ module Endpoints
+ class SqlIndex < Index
+ private
+
+ def render_paginated_success(results, query, params, self_path)
+ resulting_params = calculate_resulting_params(query, params)
+
+ ::API::V3::Utilities::SqlRepresenterWalker
+ .new(results,
+ embed: { 'elements' => {} },
+ select: { '*' => {}, 'elements' => { '*' => {} } },
+ current_user: User.current,
+ self_path: self_path,
+ url_query: resulting_params)
+ .walk(deduce_render_representer)
+ end
+
+ def paginated_representer?
+ true
+ end
+
+ def deduce_render_representer
+ "::API::V3::#{deduce_api_namespace}::#{api_name}SqlCollectionRepresenter".constantize
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/utilities/endpoints/sql_show.rb b/lib/api/v3/utilities/endpoints/sql_show.rb
new file mode 100644
index 00000000000..80840b07ba9
--- /dev/null
+++ b/lib/api/v3/utilities/endpoints/sql_show.rb
@@ -0,0 +1,85 @@
+#-- 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 API
+ module V3
+ module Utilities
+ module Endpoints
+ class SqlShow
+ def initialize(model:)
+
+ self.model = model
+ end
+
+ def mount
+ show = self
+
+ -> do
+ scope = show.scope(params)
+
+ show.check_visibility(scope)
+ show.render(scope)
+ end
+ end
+
+ def scope(params)
+ query_class.new(user: User.current)
+ .where('id', '=', params[:id])
+ .results
+ end
+
+ def check_visibility(scope)
+ raise ::API::Errors::NotFound.new unless scope.exists?
+ end
+
+ def render(scope)
+ ::API::V3::Utilities::SqlRepresenterWalker
+ .new(scope.limit(1),
+ embed: {},
+ select: { '*' => {} },
+ current_user: User.current)
+ .walk(render_representer)
+ end
+
+ attr_accessor :model,
+ :api_name
+
+ private
+
+ def render_representer
+ "API::V3::#{model.name.pluralize}::#{model.name}SqlRepresenter".constantize
+ end
+
+ def query_class
+ "Queries::#{model.name.pluralize}::#{model.name}Query".constantize
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/api/v3/utilities/path_helper.rb b/lib/api/v3/utilities/path_helper.rb
index 4bf2e9754d9..b1571282872 100644
--- a/lib/api/v3/utilities/path_helper.rb
+++ b/lib/api/v3/utilities/path_helper.rb
@@ -97,9 +97,11 @@ module API
"#{root_path}api/v3"
end
- def self.activity(id)
- "#{root}/activities/#{id}"
- end
+ index :action
+ show :action
+
+ index :activity
+ show :activity
index :attachment
show :attachment
@@ -163,6 +165,13 @@ module API
"#{work_package(work_package_id)}/available_relation_candidates"
end
+ index :capability
+ show :capability
+
+ def self.capabilities_contexts_global
+ "#{capabilities}/contexts/global"
+ end
+
index :category
show :category
diff --git a/lib/api/v3/utilities/sql_representer_walker.rb b/lib/api/v3/utilities/sql_representer_walker.rb
new file mode 100644
index 00000000000..b73aa6931ba
--- /dev/null
+++ b/lib/api/v3/utilities/sql_representer_walker.rb
@@ -0,0 +1,112 @@
+#-- 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-2017 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 API
+ module V3
+ module Utilities
+ class SqlRepresenterWalker
+ include API::Utilities::PageSizeHelper
+
+ def initialize(scope,
+ current_user:,
+ url_query: {},
+ embed: {},
+ select: {},
+ self_path: nil)
+ self.scope = scope
+ self.current_user = current_user
+ self.embed = embed
+ self.select = select
+ self.self_path = self_path
+ self.url_query = url_query
+ end
+
+ def walk(start)
+ result = SqlWalkerResults.new(scope,
+ url_query: url_query,
+ self_path: self_path)
+
+ result.selects = embedded_depth_first([], start) do |map, stack, current_representer|
+ result.replace_map.merge!(map)
+
+ current_representer.select_sql(select_for(stack), result)
+ end
+
+ embedded_depth_first([], start) do |_, stack, current_representer|
+ result.scope = current_representer.joins(select_for(stack), result.scope)
+ end
+
+ embedded_depth_first([], start) do |_, _, current_representer|
+ result.ctes.merge!(current_representer.ctes(result))
+ end
+
+ self.sql = start.to_sql(result)
+
+ self
+ end
+
+ def to_json(*)
+ ActiveRecord::Base.connection.select_one(sql)['json']
+ end
+
+ protected
+
+ attr_accessor :scope,
+ :current_user,
+ :embed,
+ :select,
+ :sql,
+ :url_query,
+ :self_path
+
+ def embedded_depth_first(stack, current_representer, &block)
+ up_map = {}
+
+ embed_for(stack).each_key do |key|
+ representer = current_representer
+ .embed_map[key]
+
+ up_map[key] = embedded_depth_first(stack.dup << key, representer, &block)
+ end
+
+ yield up_map, stack, current_representer
+ end
+
+ def select_for(stack)
+ stack.any? ? select.dig(*stack) : select
+ end
+
+ def embed_for(stack)
+ stack.any? ? embed.dig(*stack) : embed
+ end
+ end
+ end
+ end
+end
\ No newline at end of file
diff --git a/lib/api/v3/utilities/sql_walker_results.rb b/lib/api/v3/utilities/sql_walker_results.rb
new file mode 100644
index 00000000000..d8b41298fd5
--- /dev/null
+++ b/lib/api/v3/utilities/sql_walker_results.rb
@@ -0,0 +1,61 @@
+#-- 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-2017 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 API
+ module V3
+ module Utilities
+ class SqlWalkerResults
+ def initialize(scope, url_query:, self_path: nil, replace_map: {})
+ self.scope = scope
+ self.ctes = {}
+ self.self_path = self_path
+ self.url_query = url_query
+ self.replace_map = replace_map
+ end
+
+ attr_accessor :scope,
+ :sql,
+ :selects,
+ :ctes,
+ :self_path,
+ :url_query,
+ :replace_map
+
+ def page_size
+ url_query[:pageSize]
+ end
+
+ def offset
+ url_query[:offset]
+ end
+ end
+ end
+ end
+end
diff --git a/lib/open_project/access_control.rb b/lib/open_project/access_control.rb
index 19c5f813f15..026967e18ae 100644
--- a/lib/open_project/access_control.rb
+++ b/lib/open_project/access_control.rb
@@ -71,13 +71,13 @@ module OpenProject
# Returns the actions that are allowed by the permission of given name
def allowed_actions(permission_name)
perm = permission(permission_name)
- perm ? perm.actions : []
+ perm ? perm.controller_actions : []
end
def allow_actions(action_hash)
action = "#{action_hash[:controller]}/#{action_hash[:action]}"
- permissions.select { |p| p.actions.include? action }
+ permissions.select { |p| p.controller_actions.include? action }
end
def public_permissions
@@ -115,6 +115,14 @@ module OpenProject
@permissions.select { |p| p.project_module.nil? || modules.include?(p.project_module.to_s) }
end
+ def contract_actions_map
+ @contract_actions_map ||= permissions.each_with_object({}) do |p, hash|
+ next unless p.contract_actions.any?
+
+ hash[p.name] = { actions: p.contract_actions, global: p.global?, module: p.project_module }
+ end
+ end
+
def remove_modules_permissions(module_name)
permissions = @permissions
@@ -130,6 +138,7 @@ module OpenProject
@public_permissions = nil
@members_only_permissions = nil
@loggedin_only_permissions = nil
+ @contract_actions_map = nil
end
end
end
diff --git a/lib/open_project/access_control/permission.rb b/lib/open_project/access_control/permission.rb
index ed15e17c1bc..732da61a8d0 100644
--- a/lib/open_project/access_control/permission.rb
+++ b/lib/open_project/access_control/permission.rb
@@ -32,26 +32,28 @@ module OpenProject
module AccessControl
class Permission
attr_reader :name,
- :actions,
+ :controller_actions,
+ :contract_actions,
:project_module,
:dependencies
def initialize(name, hash, options)
@name = name
- @actions = []
+ @controller_actions = []
@public = options[:public] || false
@require = options[:require]
@global = options[:global] || false
@dependencies = Array(options[:dependencies]) || []
@project_module = options[:project_module]
+ @contract_actions = options[:contract_actions] || []
hash.each do |controller, actions|
- @actions << if actions.is_a? Array
- actions.map { |action| "#{controller}/#{action}" }
- else
- "#{controller}/#{actions}"
- end
+ @controller_actions << if actions.is_a? Array
+ actions.map { |action| "#{controller}/#{action}" }
+ else
+ "#{controller}/#{actions}"
+ end
end
- @actions.flatten!
+ @controller_actions.flatten!
end
def public?
diff --git a/lib/tasks/permissions.rake b/lib/tasks/permissions.rake
index 967c3c3be63..90de154d87e 100644
--- a/lib/tasks/permissions.rake
+++ b/lib/tasks/permissions.rake
@@ -33,7 +33,7 @@ namespace :redmine do
task permissions: :environment do
puts 'Permission Name - controller/action pairs'
OpenProject::AccessControl.permissions.sort { |a, b| a.name.to_s <=> b.name.to_s }.each do |permission|
- puts ":#{permission.name} - #{permission.actions.join(', ')}"
+ puts ":#{permission.name} - #{permission.controller_actions.join(', ')}"
end
end
end
diff --git a/modules/backlogs/lib/open_project/backlogs/engine.rb b/modules/backlogs/lib/open_project/backlogs/engine.rb
index 4ef4446e1fa..73fb1cffd49 100644
--- a/modules/backlogs/lib/open_project/backlogs/engine.rb
+++ b/modules/backlogs/lib/open_project/backlogs/engine.rb
@@ -52,21 +52,21 @@ module OpenProject::Backlogs
bundled: true,
settings: settings do
OpenProject::AccessControl.permission(:edit_project).tap do |add|
- add.actions << 'projects/project_done_statuses'
- add.actions << 'projects/rebuild_positions'
- add.actions << 'backlogs_project_settings/show'
+ add.controller_actions << 'projects/project_done_statuses'
+ add.controller_actions << 'projects/rebuild_positions'
+ add.controller_actions << 'backlogs_project_settings/show'
end
OpenProject::AccessControl.permission(:add_work_packages).tap do |add|
- add.actions << 'rb_stories/create'
- add.actions << 'rb_tasks/create'
- add.actions << 'rb_impediments/create'
+ add.controller_actions << 'rb_stories/create'
+ add.controller_actions << 'rb_tasks/create'
+ add.controller_actions << 'rb_impediments/create'
end
OpenProject::AccessControl.permission(:edit_work_packages).tap do |edit|
- edit.actions << 'rb_stories/update'
- edit.actions << 'rb_tasks/update'
- edit.actions << 'rb_impediments/update'
+ edit.controller_actions << 'rb_stories/update'
+ edit.controller_actions << 'rb_tasks/update'
+ edit.controller_actions << 'rb_impediments/update'
end
project_module :backlogs do
diff --git a/modules/bim/lib/open_project/bim/engine.rb b/modules/bim/lib/open_project/bim/engine.rb
index f97178d1162..1095c4d2f9f 100644
--- a/modules/bim/lib/open_project/bim/engine.rb
+++ b/modules/bim/lib/open_project/bim/engine.rb
@@ -72,7 +72,7 @@ module OpenProject::Bim
delete_work_packages]
end
- OpenProject::AccessControl.permission(:view_work_packages).actions << 'bim/bcf/issues/redirect_to_bcf_issues_list'
+ OpenProject::AccessControl.permission(:view_work_packages).controller_actions << 'bim/bcf/issues/redirect_to_bcf_issues_list'
::Redmine::MenuManager.map(:project_menu) do |menu|
menu.push(:ifc_models,
diff --git a/modules/overviews/lib/overviews/engine.rb b/modules/overviews/lib/overviews/engine.rb
index 33b2616e723..186b05b9585 100644
--- a/modules/overviews/lib/overviews/engine.rb
+++ b/modules/overviews/lib/overviews/engine.rb
@@ -17,7 +17,7 @@ module Overviews
initializer 'overviews.permissions' do
OpenProject::AccessControl.permission(:view_project)
- .actions
+ .controller_actions
.push('overviews/overviews/show')
OpenProject::AccessControl.map do |ac_map|
diff --git a/modules/reporting/lib/open_project/reporting/engine.rb b/modules/reporting/lib/open_project/reporting/engine.rb
index df13df24d4f..737a9990dd6 100644
--- a/modules/reporting/lib/open_project/reporting/engine.rb
+++ b/modules/reporting/lib/open_project/reporting/engine.rb
@@ -48,10 +48,10 @@ module OpenProject::Reporting
# register additional permissions for viewing time and cost entries through the CostReportsController
view_actions.each do |action|
- OpenProject::AccessControl.permission(:view_time_entries).actions << "cost_reports/#{action}"
- OpenProject::AccessControl.permission(:view_own_time_entries).actions << "cost_reports/#{action}"
- OpenProject::AccessControl.permission(:view_cost_entries).actions << "cost_reports/#{action}"
- OpenProject::AccessControl.permission(:view_own_cost_entries).actions << "cost_reports/#{action}"
+ OpenProject::AccessControl.permission(:view_time_entries).controller_actions << "cost_reports/#{action}"
+ OpenProject::AccessControl.permission(:view_own_time_entries).controller_actions << "cost_reports/#{action}"
+ OpenProject::AccessControl.permission(:view_cost_entries).controller_actions << "cost_reports/#{action}"
+ OpenProject::AccessControl.permission(:view_own_cost_entries).controller_actions << "cost_reports/#{action}"
end
# menu extensions
diff --git a/spec/lib/api/v3/actions/action_sql_respresenter_rendering_spec.rb b/spec/lib/api/v3/actions/action_sql_respresenter_rendering_spec.rb
new file mode 100644
index 00000000000..315f687358e
--- /dev/null
+++ b/spec/lib/api/v3/actions/action_sql_respresenter_rendering_spec.rb
@@ -0,0 +1,70 @@
+#-- 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'
+
+describe ::API::V3::Actions::ActionSqlRepresenter, 'rendering' do
+ include ::API::V3::Utilities::PathHelper
+
+ let(:scope) do
+ Action
+ .where(id: action_id)
+ .limit(1)
+ end
+ let(:action_id) do
+ 'memberships/create'
+ end
+ current_user do
+ FactoryBot.create(:user)
+ end
+
+ subject(:json) do
+ ::API::V3::Utilities::SqlRepresenterWalker
+ .new(scope,
+ embed: {},
+ select: { 'id' => {}, '_type' => {}, 'self' => {} },
+ current_user: current_user)
+ .walk(API::V3::Actions::ActionSqlRepresenter)
+ .to_json
+ end
+
+ context 'with a project action' do
+ it 'renders as expected' do
+ expect(json)
+ .to be_json_eql({
+ "id": action_id,
+ "_type": "Action",
+ "_links": {
+ "self": {
+ "href": api_v3_paths.action(action_id)
+ }
+ }
+ }.to_json)
+ end
+ end
+end
diff --git a/spec/lib/api/v3/capabilities/capability_sql_representer_rendering_spec.rb b/spec/lib/api/v3/capabilities/capability_sql_representer_rendering_spec.rb
new file mode 100644
index 00000000000..7901a344a20
--- /dev/null
+++ b/spec/lib/api/v3/capabilities/capability_sql_representer_rendering_spec.rb
@@ -0,0 +1,159 @@
+#-- 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'
+
+describe ::API::V3::Capabilities::CapabilitySqlRepresenter, 'rendering' do
+ include ::API::V3::Utilities::PathHelper
+
+ let(:scope) do
+ Capability
+ .where(principal_id: principal.id,
+ context_id: context&.id)
+ .limit(1)
+ end
+ let(:principal) do
+ FactoryBot.create(:user,
+ member_in_project: project,
+ member_with_permissions: %i[view_members])
+ end
+ let(:project) do
+ FactoryBot.create(:project)
+ end
+ let(:context) do
+ project
+ end
+
+ current_user do
+ FactoryBot.create(:user,
+ member_in_project: project,
+ member_with_permissions: [])
+ end
+
+ subject(:json) do
+ ::API::V3::Utilities::SqlRepresenterWalker
+ .new(scope,
+ embed: {},
+ select: { 'id' => {}, '_type' => {}, 'self' => {}, 'action' => {}, 'context' => {}, 'principal' => {} },
+ current_user: current_user)
+ .walk(API::V3::Capabilities::CapabilitySqlRepresenter)
+ .to_json
+ end
+
+ context 'with a project and user' do
+ it 'renders as expected' do
+ expect(json)
+ .to be_json_eql({
+ "id": "memberships/read/p#{context.id}-#{principal.id}",
+ "_type": "Capability",
+ "_links": {
+ "context": {
+ "href": api_v3_paths.project(project.id),
+ "title": project.name
+ },
+ "principal": {
+ "href": api_v3_paths.user(principal.id),
+ "title": principal.name
+ },
+ "action": {
+ "href": api_v3_paths.action("memberships/read")
+ },
+ "self": {
+ "href": api_v3_paths.capability("memberships/read/p#{context.id}-#{principal.id}")
+ }
+ }
+ }.to_json)
+ end
+ end
+
+ context 'with a project and group' do
+ let(:principal) do
+ FactoryBot.create(:group,
+ member_in_project: project,
+ member_with_permissions: %i[view_members])
+ end
+
+ it 'renders as expected' do
+ expect(json)
+ .to be_json_eql({
+ "id": "memberships/read/p#{context.id}-#{principal.id}",
+ "_type": "Capability",
+ "_links": {
+ "context": {
+ "href": api_v3_paths.project(project.id),
+ "title": project.name
+ },
+ "principal": {
+ "href": api_v3_paths.group(principal.id),
+ "title": principal.name
+ },
+ "action": {
+ "href": api_v3_paths.action("memberships/read")
+ },
+ "self": {
+ "href": api_v3_paths.capability("memberships/read/p#{context.id}-#{principal.id}")
+ }
+ }
+ }.to_json)
+ end
+ end
+
+ context 'with a global permission' do
+ let(:principal) do
+ FactoryBot.create(:user,
+ global_permission: %i[manage_user],
+ member_in_project: project,
+ member_with_permissions: [])
+ end
+ let(:context) { nil }
+
+ it 'renders as expected' do
+ expect(json)
+ .to be_json_eql({
+ "id": "users/update/g-#{principal.id}",
+ "_type": "Capability",
+ "_links": {
+ "context": {
+ "href": api_v3_paths.capabilities_contexts_global,
+ "title": 'Global'
+ },
+ "principal": {
+ "href": api_v3_paths.user(principal.id),
+ "title": principal.name
+ },
+ "action": {
+ "href": api_v3_paths.action("users/update")
+ },
+ "self": {
+ "href": api_v3_paths.capability("users/update/g-#{principal.id}")
+ }
+ }
+ }.to_json)
+ end
+ end
+end
diff --git a/spec/lib/api/v3/capabilities/contexts/global_representer_rendering_spec.rb b/spec/lib/api/v3/capabilities/contexts/global_representer_rendering_spec.rb
new file mode 100644
index 00000000000..6ddae7c4c72
--- /dev/null
+++ b/spec/lib/api/v3/capabilities/contexts/global_representer_rendering_spec.rb
@@ -0,0 +1,61 @@
+#-- 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'
+
+describe ::API::V3::Capabilities::Contexts::GlobalRepresenter, 'rendering' do
+ include ::API::V3::Utilities::PathHelper
+
+ subject { representer.to_json }
+
+ let(:representer) do
+ described_class
+ .create(nil,
+ current_user: nil,
+ embed_links: true)
+ end
+
+ describe '_links' do
+ describe 'self' do
+ it_behaves_like 'has an untitled link' do
+ let(:link) { 'self' }
+ let(:href) { api_v3_paths.capabilities_contexts_global }
+ end
+ end
+ end
+
+ describe 'properties' do
+ it_behaves_like 'property', :_type do
+ let(:value) { 'CapabilityContext' }
+ end
+
+ it_behaves_like 'property', :id do
+ let(:value) { 'global' }
+ end
+ end
+end
diff --git a/spec/lib/api/v3/utilities/path_helper_spec.rb b/spec/lib/api/v3/utilities/path_helper_spec.rb
index 0821e90eb9b..47964e24434 100644
--- a/spec/lib/api/v3/utilities/path_helper_spec.rb
+++ b/spec/lib/api/v3/utilities/path_helper_spec.rb
@@ -112,7 +112,13 @@ describe ::API::V3::Utilities::PathHelper do
it_behaves_like 'api v3 path'
end
+ context 'actions paths' do
+ it_behaves_like 'index', :action
+ it_behaves_like 'show', :action
+ end
+
context 'activities paths' do
+ it_behaves_like 'index', :activities
it_behaves_like 'show', :activity
end
@@ -156,6 +162,17 @@ describe ::API::V3::Utilities::PathHelper do
end
end
+ context 'capabilities paths' do
+ it_behaves_like 'index', :capability
+ it_behaves_like 'show', :capability
+
+ describe '#capabilties_contexts_global' do
+ subject { helper.capabilities_contexts_global }
+
+ it_behaves_like 'api v3 path', '/capabilities/contexts/global'
+ end
+ end
+
context 'configuration paths' do
describe '#configuration' do
subject { helper.configuration }
diff --git a/spec/lib/open_project/access_control_spec.rb b/spec/lib/open_project/access_control_spec.rb
index 2e09397d5c8..74fcf3cb38f 100644
--- a/spec/lib/open_project/access_control_spec.rb
+++ b/spec/lib/open_project/access_control_spec.rb
@@ -42,7 +42,7 @@ describe OpenProject::AccessControl do
def setup_global_permissions
OpenProject::AccessControl.map do |map|
- map.permission :proj0, { dont: :care }, require: :member
+ map.permission :proj0, { dont: :care }, require: :member, contract_actions: { foo: :create }
map.permission :global0, { dont: :care }, global: true
map.permission :proj1, { dont: :care }
@@ -51,12 +51,12 @@ describe OpenProject::AccessControl do
end
map.project_module :project_module do |mod|
- mod.permission :proj2, { dont: :care }
+ mod.permission :proj2, { dont: :care }, contract_actions: { bar: %i[create read] }
end
map.project_module :mixed_module do |mod|
mod.permission :proj3, { dont: :care }
- mod.permission :global2, { dont: :care }, global: true
+ mod.permission :global2, { dont: :care }, global: true, contract_actions: { baz: %i[destroy] }
end
end
end
@@ -107,8 +107,8 @@ describe OpenProject::AccessControl do
describe '#permissions' do
it 'is an array of permissions' do
- expect(described_class.permissions.all? { |p| p.is_a?(OpenProject::AccessControl::Permission) })
- .to be_truthy
+ expect(described_class.permissions)
+ .to(be_all{ |p| p.is_a?(OpenProject::AccessControl::Permission) })
end
end
@@ -151,7 +151,7 @@ describe OpenProject::AccessControl do
end
it 'includes actions' do
- expect(subject.actions)
+ expect(subject.controller_actions)
.to include('project_settings/show')
end
end
@@ -205,8 +205,26 @@ describe OpenProject::AccessControl do
restore_access_control_permissions
end
- it { expect(OpenProject::AccessControl.available_project_modules.include?(:global_module)).to be_falsey }
- it { expect(OpenProject::AccessControl.available_project_modules.include?(:global_module)).to be_falsey }
- it { expect(OpenProject::AccessControl.available_project_modules.include?(:mixed_module)).to be_truthy }
+ it { expect(OpenProject::AccessControl.available_project_modules).not_to include(:global_module) }
+ it { expect(OpenProject::AccessControl.available_project_modules).to include(:mixed_module) }
+ end
+
+ describe '#contract_actions_map' do
+ before do
+ stash_access_control_permissions
+
+ setup_global_permissions
+ end
+
+ after do
+ restore_access_control_permissions
+ end
+
+ it 'contains all contract actions grouped by the permission' do
+ expect(subject.contract_actions_map)
+ .to eql(global2: { actions: { baz: [:destroy] }, global: true, module: :mixed_module },
+ proj0: { actions: { foo: :create }, global: false, module: nil },
+ proj2: { actions: { bar: %i[create read] }, global: false, module: :project_module })
+ end
end
end
diff --git a/spec/models/actions/scopes/default_spec.rb b/spec/models/actions/scopes/default_spec.rb
new file mode 100644
index 00000000000..8073108f6f9
--- /dev/null
+++ b/spec/models/actions/scopes/default_spec.rb
@@ -0,0 +1,56 @@
+#-- 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'
+
+describe Actions::Scopes::Default, type: :model do
+ subject(:scope) { Action.default }
+
+ describe '.default' do
+ let(:expected) do
+ # This complicated and programmatic way is chosen so that the test can deal with additional actions being defined
+ item = ->(permission, namespace, action, global, module_name) {
+ ["#{API::Utilities::PropertyNameConverter.from_ar_name(namespace.to_s.singularize).pluralize}/#{action}",
+ permission.to_s,
+ global,
+ module_name&.to_s]
+ }
+
+ OpenProject::AccessControl
+ .contract_actions_map
+ .map do |permission, v|
+ v[:actions].map { |vk, vv| vv.map { |vvv| item.call(permission, vk, vvv, v[:global], v[:module]) } }
+ end.flatten(2)
+ end
+
+ it 'contains all actions' do
+ expect(scope.pluck(:id, :permission, :global, :module))
+ .to match_array(expected)
+ end
+ end
+end
diff --git a/spec/models/capabilities/scopes/default_spec.rb b/spec/models/capabilities/scopes/default_spec.rb
new file mode 100644
index 00000000000..6906a58d665
--- /dev/null
+++ b/spec/models/capabilities/scopes/default_spec.rb
@@ -0,0 +1,310 @@
+#-- 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'
+
+describe Capabilities::Scopes::Default, type: :model do
+ # we focus on the non current user capabilities to make the tests easier to understand
+ subject(:scope) { Capability.default.where(principal_id: user.id) }
+
+ let(:permissions) { %i[] }
+ let(:global_permissions) { %i[] }
+ let(:non_member_permissions) { %i[] }
+ let(:project_public) { false }
+ let(:project_active) { true }
+ let!(:project) { FactoryBot.create(:project, public: project_public, active: project_active) }
+ let(:role) do
+ FactoryBot.create(:role, permissions: permissions)
+ end
+ let(:global_role) do
+ FactoryBot.create(:global_role, permissions: global_permissions)
+ end
+ let(:user_admin) { false }
+ let(:user_status) { Principal.statuses[:active] }
+ let(:current_user_admin) { true }
+ let!(:user) { FactoryBot.create(:user, admin: user_admin, status: user_status) }
+ let(:global_member) do
+ FactoryBot.create(:global_member,
+ principal: user,
+ roles: [global_role])
+ end
+ let(:member) do
+ FactoryBot.create(:member,
+ principal: user,
+ roles: [role],
+ project: project)
+ end
+ let(:non_member_role) do
+ FactoryBot.create(:non_member,
+ permissions: non_member_permissions)
+ end
+ let(:own_role) { FactoryBot.create(:role, permissions: [] )}
+ let(:own_member) do
+ FactoryBot.create(:member,
+ principal: current_user,
+ roles: [own_role],
+ project: project)
+ end
+ let(:members) { [] }
+
+ current_user do
+ FactoryBot.create(:user, admin: current_user_admin)
+ end
+
+ shared_examples_for 'consists of contract actions' do
+ it 'includes the expected for the scoped to user' do
+ expect(scope.pluck(:action, :principal_id, :context_id))
+ .to match_array(expected)
+ end
+ end
+
+ shared_examples_for 'is empty' do
+ it 'is empty for the scoped to user' do
+ expect(scope)
+ .to be_empty
+ end
+ end
+
+ describe '.default' do
+ before do
+ members
+ end
+
+ context 'without any members and non member roles' do
+ it_behaves_like 'is empty'
+ end
+
+ context 'with a member without a permission' do
+ let(:members) { [member] }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'with a global member without a permission' do
+ let(:members) { [global_member] }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'with a non member role without a permission' do
+ let(:members) { [non_member_role] }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'with a global member with an action permission' do
+ let(:global_permissions) { %i[manage_user] }
+ let(:members) { [global_member] }
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ [['users/create', user.id, nil],
+ ['users/read', user.id, nil],
+ ['users/update', user.id, nil]]
+ end
+ end
+ end
+
+ context 'with a member with an action permission' do
+ let(:permissions) { %i[manage_members] }
+ let(:members) { [member] }
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ [['memberships/create', user.id, project.id],
+ ['memberships/destroy', user.id, project.id],
+ ['memberships/update', user.id, project.id]]
+ end
+ end
+ end
+
+ context 'with a lgobal member with an action permission and the user being locked' do
+ let(:permissions) { %i[manage_members] }
+ let(:members) { [member] }
+ let(:user_status) { Principal.statuses[:locked] }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'with a member with an action permission and the user being locked' do
+ let(:permissions) { %i[manage_members] }
+ let(:members) { [member] }
+ let(:user_status) { Principal.statuses[:locked] }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'with the non member role with an action permission' do
+ let(:non_member_permissions) { %i[view_members] }
+ let(:members) { [non_member_role] }
+
+ context 'with the project being private' do
+ it_behaves_like 'is empty'
+ end
+
+ context 'with the project being public' do
+ let(:project_public) { true }
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ [
+ ['memberships/read', user.id, project.id]
+ ]
+ end
+ end
+ end
+ end
+
+ context 'with a member without a permission and with the non member having a permission' do
+ let(:non_member_permissions) { %i[view_members] }
+ let(:members) { [member, non_member_role] }
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ [
+ ['memberships/read', user.id, project.id]
+ ]
+ end
+ end
+ end
+
+ context 'with a member with a permission and with the non member having the same permission' do
+ let(:non_member_permissions) { %i[view_members] }
+ let(:member_permissions) { %i[view_members] }
+ let(:members) { [member, non_member_role] }
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ [
+ ['memberships/read', user.id, project.id]
+ ]
+ end
+ end
+ end
+
+ context 'with the non member role with an action permission and the user being locked' do
+ let(:non_member_permissions) { %i[view_members] }
+ let(:members) { [non_member_role] }
+ let(:project_public) { true }
+ let(:user_status) { Principal.statuses[:locked] }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'with an admin' do
+ let(:user_admin) { true }
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ # This complicated and programmatic way is chosen so that the test can deal with additional actions being defined
+ item = ->(namespace, action, global) {
+ ["#{API::Utilities::PropertyNameConverter.from_ar_name(namespace.to_s.singularize).pluralize}/#{action}",
+ user.id,
+ global ? nil : project.id]
+ }
+
+ OpenProject::AccessControl
+ .contract_actions_map
+ .map { |_, v| v[:actions].map { |vk, vv| vv.map { |vvv| item.call(vk, vvv, v[:global]) } } }
+ .flatten(2)
+ end
+ end
+ end
+
+ context 'with an admin but with modules deactivated' do
+ let(:user_admin) { true }
+
+ before do
+ project.enabled_modules = []
+ end
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ # This complicated and programmatic way is chosen so that the test can deal with additional actions being defined
+ item = ->(namespace, action, global) {
+ return if namespace == :work_packages
+
+ ["#{API::Utilities::PropertyNameConverter.from_ar_name(namespace.to_s.singularize).pluralize}/#{action}",
+ user.id,
+ global ? nil : project.id]
+ }
+
+ OpenProject::AccessControl
+ .contract_actions_map
+ .map { |_, v| v[:actions].map { |vk, vv| vv.map { |vvv| item.call(vk, vvv, v[:global]) } } }
+ .flatten(2)
+ .compact
+ end
+ end
+ end
+
+ context 'with an admin but being locked' do
+ let(:user_admin) { true }
+ let(:user_status) { Principal.statuses[:locked] }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'without the current user being member in a project' do
+ let(:permissions) { %i[manage_members] }
+ let(:global_permissions) { %i[manage_user] }
+ let(:members) { [member, global_member] }
+ let(:current_user_admin) { false }
+
+ it_behaves_like 'is empty'
+ end
+
+ context 'with the current user being member in a project' do
+ let(:permissions) { %i[manage_members] }
+ let(:global_permissions) { %i[manage_user] }
+ let(:members) { [own_member, member, global_member] }
+ let(:current_user_admin) { false }
+
+ it_behaves_like 'consists of contract actions' do
+ let(:expected) do
+ [
+ ['memberships/create', user.id, project.id],
+ ['memberships/destroy', user.id, project.id],
+ ['memberships/update', user.id, project.id],
+ ['users/create', user.id, nil],
+ ['users/read', user.id, nil],
+ ['users/update', user.id, nil]
+ ]
+ end
+ end
+ end
+
+ context 'with a member with an action permission and the project being archived' do
+ let(:permissions) { %i[manage_members] }
+ let(:members) { [member] }
+ let(:project_active) { false }
+
+ it_behaves_like 'is empty'
+ end
+ end
+end
diff --git a/spec/models/queries/capabilities/capability_query_spec.rb b/spec/models/queries/capabilities/capability_query_spec.rb
new file mode 100644
index 00000000000..0226f752aee
--- /dev/null
+++ b/spec/models/queries/capabilities/capability_query_spec.rb
@@ -0,0 +1,124 @@
+#-- 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'
+
+describe Queries::Capabilities::CapabilityQuery, type: :model do
+ let(:instance) { described_class.new }
+
+ current_user do
+ FactoryBot.build_stubbed(:user)
+ end
+
+ describe '#valid?' do
+ context 'without filters' do
+ it 'is invalid' do
+ expect(instance)
+ .not_to be_valid
+ end
+ end
+
+ context 'with a principal filter having the `=` operator' do
+ before do
+ instance.where('principal_id', '=', ['1'])
+ end
+
+ it 'is valid' do
+ expect(instance)
+ .to be_valid
+ end
+ end
+
+ context 'with a principal filter having the `!` operator' do
+ before do
+ instance.where('principal_id', '!', ['1'])
+ end
+
+ it 'is invalid' do
+ expect(instance)
+ .not_to be_valid
+ end
+ end
+
+ context 'with a principal filter having the `=` operator but without values' do
+ before do
+ instance.where('principal_id', '=', [])
+ end
+
+ it 'is invalid' do
+ expect(instance)
+ .not_to be_valid
+ end
+ end
+
+ context 'with a context filter having the `=` operator' do
+ before do
+ instance.where('context', '=', ['p1'])
+ end
+
+ it 'is valid' do
+ expect(instance)
+ .to be_valid
+ end
+ end
+
+ context 'with a context filter having the `=` operator but without values' do
+ before do
+ instance.where('context', '=', [])
+ end
+
+ it 'is invalid' do
+ expect(instance)
+ .not_to be_valid
+ end
+ end
+
+ context 'with a context filter having the `!` operator' do
+ before do
+ instance.where('context', '!', ['g'])
+ end
+
+ it 'is invalid' do
+ expect(instance)
+ .not_to be_valid
+ end
+ end
+
+ context 'with a context filter having the `!` operator and also with a principal filter having the `=` operator' do
+ before do
+ instance.where('context', '!', ['g'])
+ instance.where('principal_id', '=', ['1'])
+ end
+
+ it 'is valid' do
+ expect(instance)
+ .to be_valid
+ end
+ end
+ end
+end
diff --git a/spec/models/queries/capabilities/filters/context_filter_spec.rb b/spec/models/queries/capabilities/filters/context_filter_spec.rb
new file mode 100644
index 00000000000..640efa33dc4
--- /dev/null
+++ b/spec/models/queries/capabilities/filters/context_filter_spec.rb
@@ -0,0 +1,82 @@
+#-- 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'
+
+describe Queries::Capabilities::Filters::ContextFilter, type: :model do
+ it_behaves_like 'basic query filter' do
+ let(:class_key) { :context }
+ let(:type) { :string }
+ let(:model) { Capability }
+ let(:attribute) { :context }
+ let(:values) { ['p3'] }
+
+ describe '#available_operators' do
+ it 'supports = and !' do
+ expect(instance.available_operators)
+ .to eql [Queries::Operators::Equals, Queries::Operators::NotEquals]
+ end
+ end
+
+ describe '#valid?' do
+ context 'without values' do
+ let(:values) { [] }
+
+ it 'is invalid' do
+ expect(instance)
+ .to be_invalid
+ end
+ end
+
+ context 'with valid value' do
+ it 'is valid' do
+ expect(instance)
+ .to be_valid
+ end
+ end
+
+ context 'with multiple valid values' do
+ let(:values) { ['p3', 'g'] }
+
+ it 'is valid' do
+ expect(instance)
+ .to be_valid
+ end
+ end
+
+ context 'with malfomed values' do
+ let(:values) { ["a5"] }
+
+ it 'is invalid' do
+ expect(instance)
+ .to be_invalid
+ end
+ end
+ end
+ end
+end
diff --git a/spec/models/queries/capabilities/filters/id_filter_spec.rb b/spec/models/queries/capabilities/filters/id_filter_spec.rb
new file mode 100644
index 00000000000..ccfb679aa3a
--- /dev/null
+++ b/spec/models/queries/capabilities/filters/id_filter_spec.rb
@@ -0,0 +1,82 @@
+#-- 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'
+
+describe Queries::Capabilities::Filters::IdFilter, type: :model do
+ it_behaves_like 'basic query filter' do
+ let(:class_key) { :id }
+ let(:type) { :string }
+ let(:model) { Capability }
+ let(:attribute) { :id }
+ let(:values) { ['memberships/create/p3-5'] }
+
+ describe '#available_operators' do
+ it 'supports = and !' do
+ expect(instance.available_operators)
+ .to eql [Queries::Operators::Equals, Queries::Operators::NotEquals]
+ end
+ end
+
+ describe '#valid?' do
+ context 'without values' do
+ let(:values) { [] }
+
+ it 'is invalid' do
+ expect(instance)
+ .to be_invalid
+ end
+ end
+
+ context 'with valid value' do
+ it 'is valid' do
+ expect(instance)
+ .to be_valid
+ end
+ end
+
+ context 'with multiple valid values' do
+ let(:values) { ['memberships/create/p3-5', 'users/create/g-5'] }
+
+ it 'is valid' do
+ expect(instance)
+ .to be_valid
+ end
+ end
+
+ context 'with malfomed values' do
+ let(:values) { ["foo/bar/baz-5"] }
+
+ it 'is invalid' do
+ expect(instance)
+ .to be_invalid
+ end
+ end
+ end
+ end
+end
diff --git a/spec/models/queries/capabilities/filters/principal_id_filter_spec.rb b/spec/models/queries/capabilities/filters/principal_id_filter_spec.rb
new file mode 100644
index 00000000000..46e968a8cd0
--- /dev/null
+++ b/spec/models/queries/capabilities/filters/principal_id_filter_spec.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.
+#++
+
+require 'spec_helper'
+
+describe Queries::Capabilities::Filters::PrincipalIdFilter, type: :model do
+ it_behaves_like 'basic query filter' do
+ let(:class_key) { :principal_id }
+ let(:type) { :integer }
+ let(:model) { Capability }
+ let(:attribute) { :principal_id }
+ let(:values) { ['5'] }
+ end
+end
diff --git a/spec/requests/api/v3/action_resource_spec.rb b/spec/requests/api/v3/action_resource_spec.rb
new file mode 100644
index 00000000000..e23cc3696e6
--- /dev/null
+++ b/spec/requests/api/v3/action_resource_spec.rb
@@ -0,0 +1,104 @@
+#-- 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 'rack/test'
+
+describe 'API v3 action resource', type: :request, content_type: :json do
+ include Rack::Test::Methods
+ include API::V3::Utilities::PathHelper
+
+ subject(:response) { last_response }
+
+ current_user do
+ FactoryBot.create(:user)
+ end
+
+ describe 'GET api/v3/actions' do
+ let(:path) { api_v3_paths.actions }
+
+ before do
+ get path
+ end
+
+ it 'returns a collection of actions' do
+ expect(subject.body)
+ .to be_json_eql(Action.count.to_json)
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql(Action.order(id: :asc).first.id.to_json)
+ .at_path('_embedded/elements/0/id')
+
+ expect(subject.body)
+ .to be_json_eql(Action.order(id: :asc).last.id.to_json)
+ .at_path("_embedded/elements/#{Action.count - 1}/id")
+ end
+ end
+
+ describe 'GET /api/v3/actions/:id' do
+ let(:path) { api_v3_paths.action("memberships/create") }
+
+ before do
+ get path
+ end
+
+ it 'returns 200 OK' do
+ expect(subject.status)
+ .to eql(200)
+ end
+
+ it 'returns the action' do
+ expect(subject.body)
+ .to be_json_eql('Action'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql("memberships/create".to_json)
+ .at_path('id')
+ end
+
+ context 'if querying a non existing action' do
+ let(:path) { api_v3_paths.action("foo/bar") }
+
+ it 'returns 404 NOT FOUND' do
+ expect(subject.status)
+ .to be 404
+ end
+ end
+
+ context 'if querying with malformed id' do
+ let(:path) { api_v3_paths.action("foobar") }
+
+ it 'returns 404 NOT FOUND' do
+ expect(subject.status)
+ .to be 404
+ end
+ end
+ end
+end
diff --git a/spec/requests/api/v3/capabilities/contexts/global_resource_spec.rb b/spec/requests/api/v3/capabilities/contexts/global_resource_spec.rb
new file mode 100644
index 00000000000..d2dd17ca743
--- /dev/null
+++ b/spec/requests/api/v3/capabilities/contexts/global_resource_spec.rb
@@ -0,0 +1,64 @@
+#-- 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 'rack/test'
+
+describe 'API v3 capabilities global context resource', type: :request, content_type: :json do
+ include Rack::Test::Methods
+ include API::V3::Utilities::PathHelper
+
+ subject(:response) { last_response }
+
+ current_user do
+ FactoryBot.create(:user)
+ end
+
+ describe 'GET /api/v3/capabilities/contexts/global' do
+ let(:path) { api_v3_paths.capabilities_contexts_global }
+
+ before do
+ get path
+ end
+
+ it 'returns 200 OK' do
+ expect(subject.status)
+ .to be 200
+ end
+
+ it 'returns the global context' do
+ expect(subject.body)
+ .to be_json_eql('CapabilityContext'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('global'.to_json)
+ .at_path('id')
+ end
+ end
+end
diff --git a/spec/requests/api/v3/capability_resource_spec.rb b/spec/requests/api/v3/capability_resource_spec.rb
new file mode 100644
index 00000000000..ad13dd41138
--- /dev/null
+++ b/spec/requests/api/v3/capability_resource_spec.rb
@@ -0,0 +1,400 @@
+#-- 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 'rack/test'
+
+describe 'API v3 capabilities resource', type: :request, content_type: :json do
+ include Rack::Test::Methods
+ include API::V3::Utilities::PathHelper
+
+ subject(:response) { last_response }
+
+ current_user do
+ FactoryBot.create(:user,
+ member_in_project: project,
+ member_with_permissions: current_user_permissions)
+ end
+ let(:current_user_permissions) { [] }
+ let(:other_user_permissions) { %i[manage_members] }
+ let(:other_user_global_permissions) { %i[manage_user] }
+ let(:project) { FactoryBot.create(:project) }
+ let(:role) do
+ FactoryBot.create(:role, permissions: other_user_permissions)
+ end
+ let(:global_role) do
+ FactoryBot.create(:global_role, permissions: other_user_global_permissions)
+ end
+ let(:other_user) { FactoryBot.create(:user) }
+ let(:other_user_global_member) do
+ FactoryBot.create(:global_member,
+ principal: other_user,
+ roles: [global_role])
+ end
+ let(:other_user_member) do
+ FactoryBot.create(:member,
+ principal: other_user,
+ roles: [role],
+ project: project)
+ end
+
+ describe 'GET api/v3/capabilities' do
+ let(:setup) do
+ other_user_global_member
+ other_user_member
+ end
+ let(:filters) { nil }
+ let(:path) { api_v3_paths.path_for(:capabilities, filters: filters, sort_by: [%i(id asc)]) }
+
+ before do
+ setup
+
+ get path
+ end
+
+ context 'without params' do
+ it 'responds 400 Bad Request' do
+ expect(subject.status).to eq(400)
+ end
+
+ it 'communicates that either a context or a principal filter is required' do
+ expect(subject.body)
+ .to be_json_eql('Error'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('urn:openproject-org:api:v3:errors:InvalidQuery'.to_json)
+ .at_path('errorIdentifier')
+ end
+ end
+
+ context 'when filtering by principal id (with a user)' do
+ let(:current_user_permissions) { %i[manage_members] }
+ let(:filters) do
+ [{ 'principalId' => {
+ 'operator' => '=',
+ 'values' => [current_user.id.to_s]
+ } }]
+ end
+
+ it 'contains only the filtered capabilities in the response' do
+ expect(subject.body)
+ .to be_json_eql('3')
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql(api_v3_paths.user(current_user.id).to_json)
+ .at_path('_embedded/elements/0/_links/principal/href')
+ end
+ end
+
+ context 'with pageSize, offset and sortBy and filter' do
+ def expect_self_link(link, overrides = {})
+ href = JSON.parse(subject.body).dig('_links', link, 'href').split('?')
+ expected_path_params = Rack::Utils.parse_nested_query(path.split('?').last)
+
+ expect(href.first)
+ .to eql(api_v3_paths.capabilities)
+
+ expect(Rack::Utils.parse_nested_query(href.last))
+ .to eql(expected_path_params.merge(overrides))
+ end
+
+ let(:filters) do
+ [{ 'principal' => {
+ 'operator' => '=',
+ 'values' => [other_user.id.to_s]
+ } }]
+ end
+ let(:path) { "#{api_v3_paths.path_for(:capabilities, filters: filters, sort_by: [%i(id asc)])}&pageSize=2&offset=2" }
+
+ it 'returns a slice of the visible memberships' do
+ expect(subject.body)
+ .to be_json_eql('Collection'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('6')
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql('2')
+ .at_path('count')
+
+ expect(subject.body)
+ .to be_json_eql("users/create/g-#{other_user.id}".to_json)
+ .at_path('_embedded/elements/1/id')
+ end
+
+ it 'includes links for self and jumping' do
+ expect_self_link('self')
+ expect_self_link('jumpTo', 'offset' => '{offset}')
+ expect_self_link('changeSize', 'pageSize' => '{size}')
+ expect_self_link('previousByOffset', 'offset' => '1')
+ expect_self_link('nextByOffset', 'offset' => '3')
+ end
+ end
+
+ context 'when filtering by principal id (group)' do
+ let(:filters) do
+ [{ 'principalId' => {
+ 'operator' => '=',
+ 'values' => [group.id.to_s]
+ } }]
+ end
+ let(:other_user) { group }
+ let(:group) { FactoryBot.create(:group) }
+
+ let(:setup) do
+ other_user_member
+ end
+
+ it 'returns a collection of capabilities' do
+ expect(subject.body)
+ .to be_json_eql('Collection'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('3')
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql("memberships/create/p#{project.id}-#{other_user.id}".to_json)
+ .at_path('_embedded/elements/0/id')
+ end
+ end
+
+ context 'when filtering by principal id (placeholder user)' do
+ let(:filters) do
+ [{ 'principalId' => {
+ 'operator' => '=',
+ 'values' => [placeholder_user.id.to_s]
+ } }]
+ end
+ let(:other_user) { placeholder_user }
+ let(:placeholder_user) do
+ FactoryBot.create(:placeholder_user)
+ end
+
+ let(:setup) do
+ other_user_member
+ end
+
+ it 'returns a collection of capabilities' do
+ expect(subject.body)
+ .to be_json_eql('Collection'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('3')
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql("memberships/create/p#{project.id}-#{other_user.id}".to_json)
+ .at_path('_embedded/elements/0/id')
+ end
+ end
+
+ context 'when filtering by principal id (with a user) but with the not operator' do
+ let(:current_user_permissions) { %i[manage_members] }
+ let(:filters) do
+ [{ 'principalId' => {
+ 'operator' => '!',
+ 'values' => [current_user.id.to_s]
+ } }]
+ end
+
+ it 'responds 400 Bad Request' do
+ expect(subject.status).to eq(400)
+ end
+
+ it 'communicates that either a context or a principal filter is required' do
+ expect(subject.body)
+ .to be_json_eql('Error'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('urn:openproject-org:api:v3:errors:InvalidQuery'.to_json)
+ .at_path('errorIdentifier')
+ end
+ end
+
+ context 'invalid filter' do
+ let(:filters) do
+ [{ 'bogus' => {
+ 'operator' => '=',
+ 'values' => [current_user.id.to_s]
+ } }]
+ end
+
+ it 'returns 400' do
+ expect(subject.status)
+ .to be 400
+ end
+
+ it 'communicates the error message' do
+ expect(subject.body)
+ .to be_json_eql('Error'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql('urn:openproject-org:api:v3:errors:InvalidQuery'.to_json)
+ .at_path('errorIdentifier')
+ end
+ end
+
+ context 'when filtering by project context' do
+ let(:other_project) { FactoryBot.create(:project) }
+ let(:other_user_other_member) do
+ FactoryBot.create(:member,
+ principal: other_user,
+ roles: [role],
+ project: other_project)
+ end
+
+ let(:filters) do
+ [{ 'context' => {
+ 'operator' => '=',
+ 'values' => ["p#{other_project.id}"]
+ } }]
+ end
+
+ let(:setup) do
+ other_user_global_member
+ other_user_member
+ other_user_other_member
+ end
+
+ it 'contains only the filtered capabilities in the response' do
+ expect(subject.body)
+ .to be_json_eql('3')
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql(api_v3_paths.project(other_project.id).to_json)
+ .at_path('_embedded/elements/0/_links/context/href')
+ end
+ end
+
+ context 'when filtering by global context' do
+ let(:filters) do
+ [{ 'context' => {
+ 'operator' => '=',
+ 'values' => ["g"]
+ } }]
+ end
+
+ it 'contains only the filtered capabilities in the response' do
+ expect(subject.body)
+ .to be_json_eql('3')
+ .at_path('total')
+
+ expect(subject.body)
+ .to be_json_eql(api_v3_paths.capabilities_contexts_global.to_json)
+ .at_path('_embedded/elements/0/_links/context/href')
+ end
+ end
+
+ context 'without permissions' do
+ current_user do
+ FactoryBot.create(:user)
+ end
+
+ let(:filters) do
+ [{ 'context' => {
+ 'operator' => '=',
+ 'values' => ["g"]
+ } }]
+ end
+
+ it 'is empty' do
+ expect(subject.body)
+ .to be_json_eql('0')
+ .at_path('total')
+ end
+ end
+ end
+
+ describe 'GET /api/v3/capabilities/:id' do
+ let(:path) { api_v3_paths.capability("memberships/create/p#{project.id}-#{other_user.id}") }
+
+ let(:setup) do
+ other_user_member
+ end
+
+ before do
+ setup
+
+ get path
+ end
+
+ it 'returns 200 OK' do
+ expect(subject.status)
+ .to eql(200)
+ end
+
+ it 'returns the capability' do
+ expect(subject.body)
+ .to be_json_eql('Capability'.to_json)
+ .at_path('_type')
+
+ expect(subject.body)
+ .to be_json_eql("memberships/create/p#{project.id}-#{other_user.id}".to_json)
+ .at_path('id')
+ end
+
+ context 'if querying a non existing capability' do
+ let(:path) { api_v3_paths.capability("foo/bar/p#{project.id}-#{other_user.id}") }
+
+ it 'returns 404 NOT FOUND' do
+ expect(subject.status)
+ .to be 404
+ end
+ end
+
+ context 'if querying with malformed id' do
+ let(:path) { api_v3_paths.capability("foo/bar/baz-5") }
+
+ it 'returns 404 NOT FOUND' do
+ expect(subject.status)
+ .to be 404
+ end
+ end
+
+ context 'if querying for an invisible user' do
+ current_user do
+ FactoryBot.create(:user)
+ end
+
+ it 'returns 404 NOT FOUND' do
+ expect(subject.status)
+ .to be 404
+ end
+ end
+ end
+end