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

extract root api into separate superclass

ulfertsc6b17e8a7a42
diff --git a/config/routes.rb b/config/routes.rb
index bd1b1b1d1d2..5e2635eeb21 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -91,7 +91,7 @@ OpenProject::Application.routes.draw do
# returned for all routes for which the v3 has also resources. Grape does
# remove the prefix (v3) before checking whether the method is supported. I
# don't understand why that should make sense.
- mount API::Root => '/'
+ mount API::Root => '/api'
# OAuth authorization routes
use_doorkeeper do
diff --git a/lib/api/formatter.rb b/lib/api/formatter.rb
new file mode 100644
index 00000000000..efe1851bd43
--- /dev/null
+++ b/lib/api/formatter.rb
@@ -0,0 +1,43 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is a project management system.
+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
+#
+# 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
+ class Formatter
+ def call(object, _env)
+ if object.is_a?(String)
+ object
+ elsif object.respond_to?(:to_json)
+ object.to_json
+ else
+ MultiJson.dump(object)
+ end
+ end
+ end
+end
diff --git a/lib/api/root.rb b/lib/api/root.rb
index 0c3ded23681..053b557bcf7 100644
--- a/lib/api/root.rb
+++ b/lib/api/root.rb
@@ -32,239 +32,14 @@
# This is the place for all API wide configuration, helper methods, exceptions
# rescuing, mounting of differnet API versions etc.
-require 'open_project/authentication'
-
module API
- class Root < Grape::API
- include OpenProject::Authentication::Scope
- extend API::Utilities::GrapeHelper
-
- prefix :api
-
- class Formatter
- def call(object, _env)
- if object.is_a?(String)
- object
- elsif object.respond_to?(:to_json)
- object.to_json
- else
- MultiJson.dump(object)
- end
- end
- end
-
- class Parser
- def call(object, _env)
- MultiJson.load(object)
- rescue MultiJson::ParseError => e
- error = ::API::Errors::ParseError.new(details: e.message)
- representer = ::API::V3::Errors::ErrorRepresenter.new(error)
-
- throw :error, status: 400, message: representer.to_json
- end
- end
-
- content_type 'hal+json', 'application/hal+json; charset=utf-8'
- content_type :json, 'application/json; charset=utf-8'
+ class Root < ::API::RootAPI
+ #content_type 'hal+json', 'application/hal+json; charset=utf-8'
+ #content_type :json, 'application/json; charset=utf-8'
format 'hal+json'
- formatter 'hal+json', Formatter.new
-
- parser :json, Parser.new
-
- use OpenProject::Authentication::Manager
-
- helpers API::Caching::Helpers
- helpers do
- def current_user
- User.current
- end
-
- def warden
- env['warden']
- end
-
- ##
- # Helper to access only the declared
- # params to avoid unvalidated access
- # (e.g., in before blocks)
- def declared_params
- declared(params)
- end
-
- def request_body
- env['api.request.body']
- end
-
- def authenticate
- warden.authenticate! scope: API_V3
-
- User.current = warden.user scope: API_V3
-
- if Setting.login_required? and not logged_in?
- raise ::API::Errors::Unauthenticated
- end
- end
-
- def set_localization
- SetLocalizationService.new(User.current, env['HTTP_ACCEPT_LANGUAGE']).call
- end
-
- # Global helper to set allowed content_types
- # This may be overriden when multipart is allowed (file uploads)
- def allowed_content_types
- %w(application/json application/hal+json)
- end
-
- def enforce_content_type
- # Content-Type is not present in GET
- return if request.get?
-
- # Raise if missing header
- content_type = request.content_type
- error!('Missing content-type header', 406) unless content_type.present?
-
- # Allow JSON and JSON+HAL per default
- # and anything that each endpoint may optionally add to that
- if content_type.present?
- allowed_content_types.each do |mime|
- # Content-Type header looks like this (e.g.,)
- # application/json;encoding=utf8
- return if content_type.start_with?(mime)
- end
- end
-
- bad_type = content_type.presence || I18n.t('api_v3.errors.missing_content_type')
- message = I18n.t('api_v3.errors.invalid_content_type',
- content_type: allowed_content_types.join(" "),
- actual: bad_type)
-
- fail ::API::Errors::UnsupportedMediaType, message
- end
-
- def logged_in?
- # An admin SystemUser is anonymous but still a valid user to be logged in.
- current_user && (current_user.admin? || !current_user.anonymous?)
- end
-
- def authorize(permission, context: nil, global: false, user: current_user, &block)
- auth_service = AuthorizationService.new(permission,
- context: context,
- global: global,
- user: user)
-
- authorize_by_with_raise auth_service, &block
- end
-
- def authorize_by_with_raise(callable)
- is_authorized = callable.respond_to?(:call) ? callable.call : callable
+ formatter 'hal+json', API::Formatter.new
- return true if is_authorized
-
- if block_given?
- yield
- else
- raise API::Errors::Unauthorized
- end
-
- false
- end
-
- # checks whether the user has
- # any of the provided permission in any of the provided
- # projects
- def authorize_any(permissions, projects: nil, global: false, user: current_user, &block)
- raise ArgumentError if projects.nil? && !global
-
- projects = Array(projects)
-
- authorized = permissions.any? do |permission|
- if global
- authorize(permission, global: true, user: user) do
- false
- end
- else
- allowed_projects = Project.allowed_to(user, permission)
- !(allowed_projects & projects).empty?
- end
- end
-
- authorize_by_with_raise(authorized, &block)
- end
-
- def authorize_admin
- authorize_by_with_raise(current_user.admin? && (current_user.active? || current_user.is_a?(SystemUser)))
- end
-
- def authorize_logged_in
- authorize_by_with_raise(current_user.logged? && current_user.active? || current_user.is_a?(SystemUser))
- end
-
- def raise_invalid_query_on_service_failure
- service = yield
-
- if service.success?
- service
- else
- api_errors = service.errors.full_messages.map do |message|
- ::API::Errors::InvalidQuery.new(message)
- end
-
- raise ::API::Errors::MultipleErrors.create_if_many api_errors
- end
- end
- end
-
- def self.auth_headers
- lambda do
- header = OpenProject::Authentication::WWWAuthenticate
- .response_header(scope: API_V3, request_headers: env)
-
- { 'WWW-Authenticate' => header }
- end
- end
-
- ##
- # Return JSON error response on authentication failure.
- OpenProject::Authentication.handle_failure(scope: API_V3) do |warden, _opts|
- e = grape_error_for warden.env, self
- error_message = I18n.t('api_v3.errors.code_401_wrong_credentials')
- api_error = ::API::Errors::Unauthenticated.new error_message
- representer = ::API::V3::Errors::ErrorRepresenter.new api_error
-
- e.error_response status: 401, message: representer.to_json, headers: warden.headers, log: false
- end
-
- error_response ActiveRecord::RecordNotFound, ::API::Errors::NotFound, log: false
- error_response ActiveRecord::StaleObjectError, ::API::Errors::Conflict, log: false
-
- error_response MultiJson::ParseError, ::API::Errors::ParseError
-
- error_response ::API::Errors::Unauthenticated, headers: auth_headers, log: false
- error_response ::API::Errors::ErrorBase, rescue_subclasses: true, log: false
-
- # Handle grape validation errors
- error_response ::Grape::Exceptions::ValidationErrors, ::API::Errors::BadRequest, log: false
-
- # Handle connection timeouts with appropriate payload
- error_response ActiveRecord::ConnectionTimeoutError,
- ::API::Errors::InternalError,
- log: ->(exception) do
- payload = ::OpenProject::Logging::ThreadPoolContextBuilder.build!
- ::OpenProject.logger.error exception, reference: :APIv3, payload: payload
- end
-
- # hide internal errors behind the same JSON response as all other errors
- # only doing it in production to allow for easier debugging
- if Rails.env.production?
- error_response StandardError, ::API::Errors::InternalError, rescue_subclasses: true
- end
-
- # run authentication before each request
- after_validation do
- authenticate
- set_localization
- enforce_content_type
- end
+ parser :json, API::V3::Parser.new
version 'v3', using: :path do
mount API::V3::Root
diff --git a/modules/bcf/app/controllers/bcf/api/v2_1/root.rb b/lib/api/root_api.rb
similarity index 84%
rename from modules/bcf/app/controllers/bcf/api/v2_1/root.rb
rename to lib/api/root_api.rb
index 5de17f19101..1cb7a70b8ac 100644
--- a/modules/bcf/app/controllers/bcf/api/v2_1/root.rb
+++ b/lib/api/root_api.rb
@@ -30,52 +30,38 @@
# Root class of the API
# This is the place for all API wide configuration, helper methods, exceptions
-# rescuing, mounting of different API versions etc.
+# rescuing, mounting of differnet API versions etc.
require 'open_project/authentication'
-module Bcf::API::V2_1
- class Root < Grape::API
- extend ::API::Utilities::GrapeHelper
+module API
+ class RootAPI < Grape::API
+ include OpenProject::Authentication::Scope
+ extend API::Utilities::GrapeHelper
- class Formatter
- def call(object, _env)
- object.respond_to?(:to_json) ? object.to_json : MultiJson.dump(object)
- end
- end
-
- class Parser
- def call(object, _env)
- MultiJson.load(object)
- rescue MultiJson::ParseError => e
- error = ::API::Errors::ParseError.new(details: e.message)
- representer = ::API::V3::Errors::ErrorRepresenter.new(error)
-
- throw :error, status: 400, message: representer.to_json
- end
- end
-
- content_type :json, 'application/json; charset=utf-8'
- format 'json'
- formatter 'json', Formatter.new
-
- parser :json, Parser.new
+ content_type 'hal+json', 'application/hal+json; charset=utf-8'
+ content_type :json, 'application/json; charset=utf-8'
- use ::OpenProject::Authentication::Manager
+ use OpenProject::Authentication::Manager
+ helpers API::Caching::Helpers
helpers do
def current_user
User.current
end
- def declared_param(key)
- declared(params)[key.to_s]
- end
-
def warden
env['warden']
end
+ ##
+ # Helper to access only the declared
+ # params to avoid unvalidated access
+ # (e.g., in before blocks)
+ def declared_params
+ declared(params)
+ end
+
def request_body
env['api.request.body']
end
@@ -97,7 +83,7 @@ module Bcf::API::V2_1
# Global helper to set allowed content_types
# This may be overriden when multipart is allowed (file uploads)
def allowed_content_types
- %w(application/json)
+ %w(application/json application/hal+json)
end
def enforce_content_type
@@ -227,6 +213,17 @@ module Bcf::API::V2_1
error_response ::API::Errors::Unauthenticated, headers: auth_headers, log: false
error_response ::API::Errors::ErrorBase, rescue_subclasses: true, log: false
+ # Handle grape validation errors
+ error_response ::Grape::Exceptions::ValidationErrors, ::API::Errors::BadRequest, log: false
+
+ # Handle connection timeouts with appropriate payload
+ error_response ActiveRecord::ConnectionTimeoutError,
+ ::API::Errors::InternalError,
+ log: ->(exception) do
+ payload = ::OpenProject::Logging::ThreadPoolContextBuilder.build!
+ ::OpenProject.logger.error exception, reference: :APIv3, payload: payload
+ end
+
# hide internal errors behind the same JSON response as all other errors
# only doing it in production to allow for easier debugging
if Rails.env.production?
@@ -234,20 +231,10 @@ module Bcf::API::V2_1
end
# run authentication before each request
- before do
- # authenticate
- User.current = User.find_by login: 'admin'
+ after_validation do
+ authenticate
set_localization
enforce_content_type
end
-
- version '2.1', using: :path do
- ## /auth
- #mount ::OpenProject::Bcf::API::AuthEndpoint
- ## /current-user
- #mount ::OpenProject::Bcf::API::CurrentUserEndpoint
- # /projects
- mount ::Bcf::API::V2_1::ProjectsAPI
- end
end
end
diff --git a/lib/api/utilities/grape_helper.rb b/lib/api/utilities/grape_helper.rb
index f159a8ddb1a..db73104cf5a 100644
--- a/lib/api/utilities/grape_helper.rb
+++ b/lib/api/utilities/grape_helper.rb
@@ -49,7 +49,7 @@ module API
end
end
- def error_response(rescued_error, error = nil, rescue_subclasses: nil, headers: ->() { {} }, log: true)
+ def error_response(rescued_error, error = nil, rescue_subclasses: nil, headers: -> { {} }, log: true)
error_response_lambda = default_error_response(headers, log)
response =
diff --git a/lib/api/v3/parser.rb b/lib/api/v3/parser.rb
new file mode 100644
index 00000000000..eff6f4f5fd2
--- /dev/null
+++ b/lib/api/v3/parser.rb
@@ -0,0 +1,42 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is a project management system.
+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
+#
+# 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::V3
+ class Parser
+ def call(object, _env)
+ MultiJson.load(object)
+ rescue MultiJson::ParseError => e
+ error = ::API::Errors::ParseError.new(details: e.message)
+ representer = ::API::V3::Errors::ErrorRepresenter.new(error)
+
+ throw :error, status: 400, message: representer.to_json
+ end
+ end
+end
diff --git a/modules/bcf/app/controllers/bcf/api/root.rb b/modules/bcf/app/controllers/bcf/api/root.rb
new file mode 100644
index 00000000000..bac93ddc452
--- /dev/null
+++ b/modules/bcf/app/controllers/bcf/api/root.rb
@@ -0,0 +1,56 @@
+#-- encoding: UTF-8
+
+#-- copyright
+# OpenProject is a project management system.
+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
+#
+# 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.
+#++
+
+# Root class of the API
+# This is the place for all API wide configuration, helper methods, exceptions
+# rescuing, mounting of different API versions etc.
+
+require 'open_project/authentication'
+
+module Bcf::API
+ class Root < ::API::RootAPI
+ format :json
+ formatter :json, API::Formatter.new
+
+ # run authentication before each request
+ before do
+ # authenticate
+ # TODO: proper authentication
+ User.current = User.find_by login: 'admin'
+ set_localization
+ enforce_content_type
+ end
+
+ version '2.1', using: :path do
+ # /projects
+ mount ::Bcf::API::V2_1::ProjectsAPI
+ end
+ end
+end
diff --git a/modules/bcf/app/controllers/bcf/api/v2_1/projects_api.rb b/modules/bcf/app/controllers/bcf/api/v2_1/projects_api.rb
index 8fa93db0d7a..aba2a834347 100644
--- a/modules/bcf/app/controllers/bcf/api/v2_1/projects_api.rb
+++ b/modules/bcf/app/controllers/bcf/api/v2_1/projects_api.rb
@@ -1,3 +1,5 @@
+#-- encoding: UTF-8
+
#-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)
@@ -28,8 +30,6 @@
module Bcf::API::V2_1
class ProjectsAPI < ::API::OpenProjectAPI
- include OpenProject::StaticRouting::UrlHelpers
-
resources :projects do
route_param :id, regexp: /\A(\d+)\z/ do
after_validation do
diff --git a/modules/bcf/config/routes.rb b/modules/bcf/config/routes.rb
index e75aa626935..d1f02d6efb0 100644
--- a/modules/bcf/config/routes.rb
+++ b/modules/bcf/config/routes.rb
@@ -35,7 +35,7 @@
OpenProject::Application.routes.draw do
scope '', as: 'bcf' do
- mount Bcf::API::V2_1::Root => '/bcf'
+ mount Bcf::API::Root => '/api/bcf'
scope 'projects/:project_id', as: 'project' do
resources :issues, controller: 'bcf/issues' do
diff --git a/modules/bcf/spec/requests/api/bcf/v2_1/projects/projects_api_spec.rb b/modules/bcf/spec/requests/api/bcf/v2_1/projects/projects_api_spec.rb
index 1c1eceafc06..670eff66114 100644
--- a/modules/bcf/spec/requests/api/bcf/v2_1/projects/projects_api_spec.rb
+++ b/modules/bcf/spec/requests/api/bcf/v2_1/projects/projects_api_spec.rb
@@ -35,8 +35,8 @@ describe 'BCF 2.1 projects resource', type: :request do
let(:project) { FactoryBot.create(:project) }
subject(:response) { last_response }
- describe 'GET /bcf/2.1/projects/:project_id' do
- let(:path) { "/bcf/2.1/projects/#{project.id}" }
+ describe 'GET /api/bcf/2.1/projects/:project_id' do
+ let(:path) { "/api/bcf/2.1/projects/#{project.id}" }
before do
get path
@@ -56,5 +56,10 @@ describe 'BCF 2.1 projects resource', type: :request do
expect(subject.body)
.to be_json_eql(expected.to_json)
end
+
+ it 'is has a json content type header' do
+ expect(subject.headers['Content-Type'])
+ .to eql 'application/json; charset=utf-8'
+ end
end
end