From 9fe709f9b7765b63ef472d1f660bc29946c8b1b4 Mon Sep 17 00:00:00 2001 From: Martin Edenhofer Date: Thu, 30 Jun 2016 10:24:03 +0200 Subject: [PATCH] Improved error handling for json requests. --- app/controllers/application_controller.rb | 120 +++--- app/controllers/calendars_controller.rb | 10 +- app/controllers/channels_controller.rb | 32 +- app/controllers/chats_controller.rb | 10 +- app/controllers/cti_controller.rb | 4 +- app/controllers/email_addresses_controller.rb | 6 +- app/controllers/errors_controller.rb | 5 + .../external_credentials_controller.rb | 14 +- app/controllers/getting_started_controller.rb | 2 +- app/controllers/groups_controller.rb | 6 +- app/controllers/http_logs_controller.rb | 4 +- app/controllers/jobs_controller.rb | 10 +- app/controllers/long_polling_controller.rb | 10 +- .../object_manager_attributes_controller.rb | 29 +- app/controllers/organizations_controller.rb | 19 +- app/controllers/overviews_controller.rb | 10 +- app/controllers/packages_controller.rb | 12 +- .../postmaster_filters_controller.rb | 10 +- app/controllers/reports_controller.rb | 21 +- app/controllers/roles_controller.rb | 6 +- app/controllers/rss_controller.rb | 5 +- app/controllers/sessions_controller.rb | 11 +- app/controllers/settings_controller.rb | 21 +- app/controllers/signatures_controller.rb | 6 +- app/controllers/slas_controller.rb | 10 +- app/controllers/tags_controller.rb | 6 +- app/controllers/taskbar_controller.rb | 12 +- app/controllers/templates_controller.rb | 10 +- app/controllers/tests_controller.rb | 25 ++ app/controllers/ticket_articles_controller.rb | 25 +- .../ticket_priorities_controller.rb | 8 +- app/controllers/ticket_states_controller.rb | 6 +- app/controllers/tickets_controller.rb | 18 +- app/controllers/translations_controller.rb | 18 +- app/controllers/triggers_controller.rb | 10 +- app/controllers/users_controller.rb | 368 ++++++++---------- config/routes.rb | 2 + config/routes/test.rb | 37 +- lib/exceptions.rb | 6 + public/401.html | 21 + public/404.html | 19 +- public/422.html | 20 +- public/500.html | 17 +- public/assets/error/style.css | 4 + test/controllers/basic_controller_test.rb | 121 ++++++ test/controllers/packages_controller_test.rb | 8 +- test/controllers/settings_controller_test.rb | 8 +- .../user_organization_controller_test.rb | 13 +- 48 files changed, 656 insertions(+), 519 deletions(-) create mode 100644 app/controllers/errors_controller.rb create mode 100644 lib/exceptions.rb create mode 100644 public/401.html create mode 100644 test/controllers/basic_controller_test.rb diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 9215ccf6d..5e298d0b8 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,4 +1,5 @@ # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/ +require 'exceptions' class ApplicationController < ActionController::Base # http_basic_authenticate_with :name => "test", :password => "ttt" @@ -18,6 +19,13 @@ class ApplicationController < ActionController::Base before_action :set_user, :session_update, :user_device_check, :cors_preflight_check after_action :trigger_events, :http_log, :set_access_control_headers + rescue_from StandardError, with: :server_error + rescue_from ExecJS::RuntimeError, with: :server_error + rescue_from ActiveRecord::RecordNotFound, with: :not_found + rescue_from ArgumentError, with: :unprocessable_entity + rescue_from Exceptions::UnprocessableEntity, with: :unprocessable_entity + rescue_from Exceptions::NotAuthorized, with: :unauthorized + # For all responses in this controller, return the CORS access control headers. def set_access_control_headers headers['Access-Control-Allow-Origin'] = '*' @@ -192,8 +200,7 @@ class ApplicationController < ActionController::Base # for sessions we need the fingperprint if type == 'session' if !session[:user_device_updated_at] && !params[:fingerprint] && !session[:user_device_fingerprint] - render json: { error: 'Need fingerprint param!' }, status: :unprocessable_entity - return false + raise Exceptions::UnprocessableEntity, 'Need fingerprint param!' end if params[:fingerprint] session[:user_device_fingerprint] = params[:fingerprint] @@ -310,13 +317,7 @@ class ApplicationController < ActionController::Base # return auth not ok if result[:auth] == false - render( - json: { - error: result[:message], - }, - status: :unauthorized - ) - return false + raise Exceptions::NotAuthorized, result[:message] end # return auth ok @@ -330,35 +331,27 @@ class ApplicationController < ActionController::Base def ticket_permission(ticket) return true if ticket.permission(current_user: current_user) - response_access_deny - false + raise Exceptions::NotAuthorized end def article_permission(article) ticket = Ticket.lookup(id: article.ticket_id) return true if ticket.permission(current_user: current_user) - response_access_deny - false + raise Exceptions::NotAuthorized end def deny_if_not_role(role_name) return false if role?(role_name) - response_access_deny - true + raise Exceptions::NotAuthorized end def valid_session_with_user return true if current_user - render json: { message: 'No session user!' }, status: :unprocessable_entity - false + raise Exceptions::UnprocessableEntity, 'No session user!' end def response_access_deny - render( - json: {}, - status: :unauthorized - ) - false + raise Exceptions::NotAuthorized end def config_frontend @@ -401,10 +394,6 @@ class ApplicationController < ActionController::Base end model_create_render_item(generic_object) - rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity end def model_create_render_item(generic_object) @@ -431,10 +420,6 @@ class ApplicationController < ActionController::Base end model_update_render_item(generic_object) - rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity end def model_update_render_item(generic_object) @@ -445,17 +430,13 @@ class ApplicationController < ActionController::Base generic_object = object.find(params[:id]) generic_object.destroy model_destory_render_item() - rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity end def model_destory_render_item () render json: {}, status: :ok end - def model_show_render (object, params) + def model_show_render(object, params) if params[:expand] generic_object = object.find(params[:id]) @@ -471,10 +452,6 @@ class ApplicationController < ActionController::Base generic_object = object.find(params[:id]) model_show_render_item(generic_object) - rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity end def model_show_render_item(generic_object) @@ -522,10 +499,6 @@ class ApplicationController < ActionController::Base generic_objects_with_associations.push item.attributes_with_associations } model_index_render_result(generic_objects_with_associations) - rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity end def model_index_render_result(generic_objects) @@ -546,18 +519,62 @@ class ApplicationController < ActionController::Base generic_object = object.find(params[:id]) result = Models.references(object, generic_object.id) return false if result.empty? - render json: { error: 'Can\'t delete, object has references.' }, status: :unprocessable_entity - true + raise Exceptions::UnprocessableEntity, 'Can\'t delete, object has references.' rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity + raise Exceptions::UnprocessableEntity, e end def not_found(e) + logger.error e.message + logger.error e.backtrace.inspect respond_to do |format| - format.json { render json: { error: e.message }, status: :not_found } - format.any { render text: "Error: #{e.message}", status: :not_found } + format.json { render json: model_match_error(e.message), status: :not_found } + format.any { + @exception = e + @traceback = !Rails.env.production? + file = File.open(Rails.root.join('public', '404.html'), 'r') + render inline: file.read, status: :not_found + } + end + end + + def unprocessable_entity(e) + logger.error e.message + logger.error e.backtrace.inspect + respond_to do |format| + format.json { render json: model_match_error(e.message), status: :unprocessable_entity } + format.any { + @exception = e + @traceback = !Rails.env.production? + file = File.open(Rails.root.join('public', '422.html'), 'r') + render inline: file.read, status: :unprocessable_entity + } + end + end + + def server_error(e) + logger.error e.message + logger.error e.backtrace.inspect + respond_to do |format| + format.json { render json: model_match_error(e.message), status: 500 } + format.any { + @exception = e + @traceback = !Rails.env.production? + file = File.open(Rails.root.join('public', '500.html'), 'r') + render inline: file.read, status: 500 + } + end + end + + def unauthorized(e) + respond_to do |format| + format.json { render json: model_match_error(e.message), status: :unauthorized } + format.any { + @exception = e + @traceback = !Rails.env.production? + file = File.open(Rails.root.join('public', '401.html'), 'r') + render inline: file.read, status: :unauthorized + } end end @@ -571,8 +588,7 @@ class ApplicationController < ActionController::Base def check_maintenance(user) return false if !check_maintenance_only(user) - render json: { error: 'Maintenance mode enabled!' }, status: :unauthorized - true + raise Exceptions::NotAuthorized, 'Maintenance mode enabled!' end end diff --git a/app/controllers/calendars_controller.rb b/app/controllers/calendars_controller.rb index 5a429d0bd..b21a98d74 100644 --- a/app/controllers/calendars_controller.rb +++ b/app/controllers/calendars_controller.rb @@ -4,7 +4,7 @@ class CalendarsController < ApplicationController before_action :authentication_check def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) # calendars assets = {} @@ -25,22 +25,22 @@ class CalendarsController < ApplicationController end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Calendar, params) end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Calendar, params) end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Calendar, params) end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Calendar, params) end end diff --git a/app/controllers/channels_controller.rb b/app/controllers/channels_controller.rb index 4d575ffab..f5cf18316 100644 --- a/app/controllers/channels_controller.rb +++ b/app/controllers/channels_controller.rb @@ -17,8 +17,8 @@ curl http://localhost/api/v1/group/channels.json -v -u #{login}:#{password} -H " =end def group_update - return if deny_if_not_role(Z_ROLENAME_ADMIN) - return if !check_access + deny_if_not_role(Z_ROLENAME_ADMIN) + check_access channel = Channel.find(params[:id]) channel.group_id = params[:group_id] @@ -40,8 +40,8 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) - return if !check_access + deny_if_not_role(Z_ROLENAME_ADMIN) + check_access model_destory_render(Channel, params) end @@ -64,7 +64,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten end def twitter_verify - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Channel, params) end @@ -87,12 +87,12 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten end def facebook_verify - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Channel, params) end def email_index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) system_online_service = Setting.get('system_online_service') account_channel_ids = [] notification_channel_ids = [] @@ -143,7 +143,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten def email_probe # check admin permissions - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) # probe settings based on email and password result = EmailHelper::Probe.full( @@ -163,7 +163,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten def email_outbound # check admin permissions - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) # verify access return if params[:channel_id] && !check_access(params[:channel_id]) @@ -175,7 +175,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten def email_inbound # check admin permissions - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) # verify access return if params[:channel_id] && !check_access(params[:channel_id]) @@ -192,7 +192,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten def email_verify # check admin permissions - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) email = params[:email] || params[:meta][:email] email = email.downcase @@ -284,10 +284,10 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten def email_notification - return if !check_online_service + check_online_service # check admin permissions - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) adapter = params[:adapter].downcase @@ -341,8 +341,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten def check_online_service return true if !Setting.get('system_online_service') - response_access_deny - false + raise Exceptions::NotAuthorized end def check_access(id = nil) @@ -354,7 +353,6 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten channel = Channel.find(id) return true if channel.preferences && !channel.preferences[:online_service_disable] - response_access_deny - false + raise Exceptions::NotAuthorized end end diff --git a/app/controllers/chats_controller.rb b/app/controllers/chats_controller.rb index 8a32d2339..e50da70c1 100644 --- a/app/controllers/chats_controller.rb +++ b/app/controllers/chats_controller.rb @@ -4,7 +4,7 @@ class ChatsController < ApplicationController before_action :authentication_check def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) chat_ids = [] assets = {} Chat.order(:id).each {|chat| @@ -20,22 +20,22 @@ class ChatsController < ApplicationController end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Chat, params) end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Chat, params) end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Chat, params) end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Chat, params) end end diff --git a/app/controllers/cti_controller.rb b/app/controllers/cti_controller.rb index aec3f58fb..5f7c3582a 100644 --- a/app/controllers/cti_controller.rb +++ b/app/controllers/cti_controller.rb @@ -5,7 +5,7 @@ class CtiController < ApplicationController # list current caller log def index - return if deny_if_not_role('CTI') + deny_if_not_role('CTI') backends = [ { @@ -22,7 +22,7 @@ class CtiController < ApplicationController # set caller log to done def done - return if deny_if_not_role('CTI') + deny_if_not_role('CTI') log = Cti::Log.find(params['id']) log.done = params['done'] log.save diff --git a/app/controllers/email_addresses_controller.rb b/app/controllers/email_addresses_controller.rb index 9a531b934..040e47bfc 100644 --- a/app/controllers/email_addresses_controller.rb +++ b/app/controllers/email_addresses_controller.rb @@ -97,7 +97,7 @@ curl http://localhost/api/v1/email_addresses.json -v -u #{login}:#{password} -H =end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(EmailAddress, params) end @@ -128,7 +128,7 @@ curl http://localhost/api/v1/email_addresses/#{id}.json -v -u #{login}:#{passwor =end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(EmailAddress, params) end @@ -146,7 +146,7 @@ curl http://localhost/api/v1/email_addresses/#{id}.json -v -u #{login}:#{passwor =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(EmailAddress, params) end end diff --git a/app/controllers/errors_controller.rb b/app/controllers/errors_controller.rb new file mode 100644 index 000000000..4aa56c74a --- /dev/null +++ b/app/controllers/errors_controller.rb @@ -0,0 +1,5 @@ +class ErrorsController < ApplicationController + def routing + not_found(ActionController::RoutingError.new("No route matches [#{request.method}] #{request.path}")) + end +end diff --git a/app/controllers/external_credentials_controller.rb b/app/controllers/external_credentials_controller.rb index 8ca86bc0f..d764d279d 100644 --- a/app/controllers/external_credentials_controller.rb +++ b/app/controllers/external_credentials_controller.rb @@ -4,27 +4,27 @@ class ExternalCredentialsController < ApplicationController before_action :authentication_check def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(ExternalCredential, params) end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(ExternalCredential, params) end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(ExternalCredential, params) end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(ExternalCredential, params) end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(ExternalCredential, params) end @@ -37,7 +37,7 @@ class ExternalCredentialsController < ApplicationController end def link_account - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) provider = params[:provider].downcase attributes = ExternalCredential.request_account_to_link(provider) session[:request_token] = attributes[:request_token] @@ -45,7 +45,7 @@ class ExternalCredentialsController < ApplicationController end def callback - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) provider = params[:provider].downcase channel = ExternalCredential.link_account(provider, session[:request_token], params) session[:request_token] = nil diff --git a/app/controllers/getting_started_controller.rb b/app/controllers/getting_started_controller.rb index 870711c89..57de10a33 100644 --- a/app/controllers/getting_started_controller.rb +++ b/app/controllers/getting_started_controller.rb @@ -111,7 +111,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password} def base # check admin permissions - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) # validate url messages = {} diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb index 0966040bf..728cbb8ed 100644 --- a/app/controllers/groups_controller.rb +++ b/app/controllers/groups_controller.rb @@ -101,7 +101,7 @@ curl http://localhost/api/v1/groups -v -u #{login}:#{password} -H "Content-Type: =end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Group, params) end @@ -133,7 +133,7 @@ curl http://localhost/api/v1/groups -v -u #{login}:#{password} -H "Content-Type: =end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Group, params) end @@ -151,7 +151,7 @@ curl http://localhost/api/v1/groups/{id} -v -u #{login}:#{password} -H "Content- =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Group, params) end end diff --git a/app/controllers/http_logs_controller.rb b/app/controllers/http_logs_controller.rb index 87ce0aece..b257905a7 100644 --- a/app/controllers/http_logs_controller.rb +++ b/app/controllers/http_logs_controller.rb @@ -5,7 +5,7 @@ class HttpLogsController < ApplicationController # GET /http_logs/:facility def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) list = if params[:facility] HttpLog.where(facility: params[:facility]).order('created_at DESC').limit(params[:limit] || 50) else @@ -16,7 +16,7 @@ class HttpLogsController < ApplicationController # POST /http_logs def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(HttpLog, params) end diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb index 778523d3f..6a9d25948 100644 --- a/app/controllers/jobs_controller.rb +++ b/app/controllers/jobs_controller.rb @@ -4,27 +4,27 @@ class JobsController < ApplicationController before_action :authentication_check def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(Job, params) end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Job, params) end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Job, params) end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Job, params) end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Job, params) end end diff --git a/app/controllers/long_polling_controller.rb b/app/controllers/long_polling_controller.rb index 0df058b34..840975f08 100644 --- a/app/controllers/long_polling_controller.rb +++ b/app/controllers/long_polling_controller.rb @@ -57,10 +57,7 @@ class LongPollingController < ApplicationController # check client id client_id = client_id_verify - if !client_id - render json: { error: 'Invalid client_id receive!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'Invalid client_id receive!' if !client_id # check queue to send begin @@ -95,10 +92,7 @@ class LongPollingController < ApplicationController end end rescue => e - logger.error e.inspect - logger.error e.backtrace - render json: { error: 'Invalid client_id in receive loop!' }, status: :unprocessable_entity - return + raise Exceptions::UnprocessableEntity, 'Invalid client_id in receive loop!' end end diff --git a/app/controllers/object_manager_attributes_controller.rb b/app/controllers/object_manager_attributes_controller.rb index a38fa5458..262165352 100644 --- a/app/controllers/object_manager_attributes_controller.rb +++ b/app/controllers/object_manager_attributes_controller.rb @@ -5,7 +5,7 @@ class ObjectManagerAttributesController < ApplicationController # GET /object_manager_attributes_list def list - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) render json: { objects: ObjectManager.list_frontend_objects, } @@ -13,19 +13,19 @@ class ObjectManagerAttributesController < ApplicationController # GET /object_manager_attributes def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) render json: ObjectManager::Attribute.list_full end # GET /object_manager_attributes/1 def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(ObjectManager::Attribute, params) end # POST /object_manager_attributes def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) check_params # check if attribute already exists @@ -33,10 +33,7 @@ class ObjectManagerAttributesController < ApplicationController object: params[:object], name: params[:name], ) - if exists - render json: model_match_error('already exists'), status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'already exists' if exists begin object_manager_attribute = ObjectManager::Attribute.add( @@ -52,15 +49,13 @@ class ObjectManagerAttributesController < ApplicationController ) render json: object_manager_attribute.attributes_with_associations, status: :created rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity + raise Exceptions::UnprocessableEntity, e end end # PUT /object_manager_attributes/1 def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) check_params begin object_manager_attribute = ObjectManager::Attribute.add( @@ -76,15 +71,13 @@ class ObjectManagerAttributesController < ApplicationController ) render json: object_manager_attribute.attributes_with_associations, status: :ok rescue => e - logger.error e.message - logger.error e.backtrace.inspect - render json: model_match_error(e.message), status: :unprocessable_entity + raise Exceptions::UnprocessableEntity, e end end # DELETE /object_manager_attributes/1 def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) object_manager_attribute = ObjectManager::Attribute.find(params[:id]) ObjectManager::Attribute.remove( object_lookup_id: object_manager_attribute.object_lookup_id, @@ -95,14 +88,14 @@ class ObjectManagerAttributesController < ApplicationController # POST /object_manager_attributes_discard_changes def discard_changes - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) ObjectManager::Attribute.discard_changes render json: {}, status: :ok end # POST /object_manager_attributes_execute_migrations def execute_migrations - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) ObjectManager::Attribute.migration_execute render json: {}, status: :ok end diff --git a/app/controllers/organizations_controller.rb b/app/controllers/organizations_controller.rb index f75ee53df..ea593bb20 100644 --- a/app/controllers/organizations_controller.rb +++ b/app/controllers/organizations_controller.rb @@ -116,10 +116,7 @@ curl http://localhost/api/v1/organizations/#{id} -v -u #{login}:#{password} render json: {} return end - if params[:id].to_i != current_user.organization_id - response_access_deny - return - end + raise Exceptions::NotAuthorized if params[:id].to_i != current_user.organization_id end if params[:expand] @@ -163,7 +160,7 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password} -H "Conten =end def create - return if deny_if_not_role(Z_ROLENAME_AGENT) + deny_if_not_role(Z_ROLENAME_AGENT) model_create_render(Organization, params) end @@ -194,7 +191,7 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password} -H "Conten =end def update - return if deny_if_not_role(Z_ROLENAME_AGENT) + deny_if_not_role(Z_ROLENAME_AGENT) model_update_render(Organization, params) end @@ -212,8 +209,8 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co =end def destroy - return if deny_if_not_role(Z_ROLENAME_AGENT) - return if model_references_check(Organization, params) + deny_if_not_role(Z_ROLENAME_AGENT) + model_references_check(Organization, params) model_destory_render(Organization, params) end @@ -221,8 +218,7 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co def search if role?(Z_ROLENAME_CUSTOMER) && !role?(Z_ROLENAME_ADMIN) && !role?(Z_ROLENAME_AGENT) - response_access_deny - return + raise Exceptions::NotAuthorized end # set limit for pagination if needed @@ -289,8 +285,7 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co # permission check if !role?(Z_ROLENAME_ADMIN) && !role?(Z_ROLENAME_AGENT) - response_access_deny - return + raise Exceptions::NotAuthorized end # get organization data diff --git a/app/controllers/overviews_controller.rb b/app/controllers/overviews_controller.rb index 56c91169a..e570a3bdb 100644 --- a/app/controllers/overviews_controller.rb +++ b/app/controllers/overviews_controller.rb @@ -52,7 +52,7 @@ curl http://localhost/api/v1/overviews.json -v -u #{login}:#{password} =end def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(Overview, params) end @@ -74,7 +74,7 @@ curl http://localhost/api/v1/overviews/#{id}.json -v -u #{login}:#{password} =end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Overview, params) end @@ -108,7 +108,7 @@ curl http://localhost/api/v1/overviews.json -v -u #{login}:#{password} -H "Conte =end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Overview, params) end @@ -142,7 +142,7 @@ curl http://localhost/api/v1/overviews.json -v -u #{login}:#{password} -H "Conte =end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Overview, params) end @@ -160,7 +160,7 @@ curl http://localhost/api/v1/overviews/#{id}.json -v -u #{login}:#{password} -H =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Overview, params) end end diff --git a/app/controllers/packages_controller.rb b/app/controllers/packages_controller.rb index f8732547e..a39a87c28 100644 --- a/app/controllers/packages_controller.rb +++ b/app/controllers/packages_controller.rb @@ -5,7 +5,7 @@ class PackagesController < ApplicationController # GET /api/v1/packages def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) packages = Package.all().order('name') render json: { packages: packages @@ -14,20 +14,20 @@ class PackagesController < ApplicationController # POST /api/v1/packages def install - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) - Package.install( string: params[:file_upload].read ) + Package.install(string: params[:file_upload].read) redirect_to '/#system/package' end # DELETE /api/v1/packages def uninstall - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) - package = Package.find( params[:id] ) + package = Package.find(params[:id]) - Package.uninstall( name: package.name, version: package.version ) + Package.uninstall(name: package.name, version: package.version) render json: { success: true diff --git a/app/controllers/postmaster_filters_controller.rb b/app/controllers/postmaster_filters_controller.rb index 6a51dc6aa..9a7164c2d 100644 --- a/app/controllers/postmaster_filters_controller.rb +++ b/app/controllers/postmaster_filters_controller.rb @@ -54,7 +54,7 @@ curl http://localhost/api/v1/postmaster_filters.json -v -u #{login}:#{password} =end def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(PostmasterFilter, params) end @@ -76,7 +76,7 @@ curl http://localhost/api/v1/postmaster_filters/#{id}.json -v -u #{login}:#{pass =end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(PostmasterFilter, params) end @@ -121,7 +121,7 @@ curl http://localhost/api/v1/postmaster_filters.json -v -u #{login}:#{password} =end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(PostmasterFilter, params) end @@ -164,7 +164,7 @@ curl http://localhost/api/v1/postmaster_filters.json -v -u #{login}:#{password} =end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(PostmasterFilter, params) end @@ -179,7 +179,7 @@ Test: =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(PostmasterFilter, params) end end diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb index 659abcdd1..fa8c2e15d 100644 --- a/app/controllers/reports_controller.rb +++ b/app/controllers/reports_controller.rb @@ -7,7 +7,7 @@ class ReportsController < ApplicationController # GET /api/reports/config def reporting_config - return if deny_if_not_role('Report') + deny_if_not_role('Report') render json: { config: Report.config, profiles: Report::Profile.list, @@ -16,7 +16,7 @@ class ReportsController < ApplicationController # GET /api/reports/generate def generate - return if deny_if_not_role('Report') + deny_if_not_role('Report') get_params = params_all return if !get_params @@ -61,7 +61,7 @@ class ReportsController < ApplicationController # GET /api/reports/sets def sets - return if deny_if_not_role('Report') + deny_if_not_role('Report') get_params = params_all return if !get_params @@ -111,10 +111,7 @@ class ReportsController < ApplicationController def params_all profile = nil if !params[:profiles] && !params[:profile_id] - render json: { - error: 'No such profiles param', - }, status: :unprocessable_entity - return + raise Exceptions::UnprocessableEntity, 'No such profiles param' end if params[:profile_id] profile = Report::Profile.find(params[:profile_id]) @@ -125,18 +122,12 @@ class ReportsController < ApplicationController } end if !profile - render json: { - error: 'No such active profile', - }, status: :unprocessable_entity - return + raise Exceptions::UnprocessableEntity, 'No such active profile' end local_config = Report.config if !local_config || !local_config[:metric] || !local_config[:metric][params[:metric].to_sym] - render json: { - error: "No such metric #{params[:metric]}" - }, status: :unprocessable_entity - return + raise Exceptions::UnprocessableEntity, "No such metric #{params[:metric]}" end metric = local_config[:metric][params[:metric].to_sym] diff --git a/app/controllers/roles_controller.rb b/app/controllers/roles_controller.rb index b8ea0d75a..4dd7b7f39 100644 --- a/app/controllers/roles_controller.rb +++ b/app/controllers/roles_controller.rb @@ -95,7 +95,7 @@ curl http://localhost/api/v1/roles.json -v -u #{login}:#{password} -H "Content-T =end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Role, params) end @@ -124,7 +124,7 @@ curl http://localhost/api/v1/roles.json -v -u #{login}:#{password} -H "Content-T =end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Role, params) end @@ -139,7 +139,7 @@ Test: =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Role, params) end end diff --git a/app/controllers/rss_controller.rb b/app/controllers/rss_controller.rb index 8cd82f995..3ae495842 100644 --- a/app/controllers/rss_controller.rb +++ b/app/controllers/rss_controller.rb @@ -20,10 +20,7 @@ curl http://localhost/api/v1/rss_fetch.json -v -u #{login}:#{password} -H "Conte def fetch items = Rss.fetch(params[:url], params[:limit]) - if items.nil? - render json: { message: "failed to fetch #{params[:url]}", status: :unprocessable_entity } - return - end + raise Exceptions::UnprocessableEntity, "failed to fetch #{params[:url]}" if items.nil? render json: { items: items } end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 9e93bce87..f3224cb1f 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -15,10 +15,7 @@ class SessionsController < ApplicationController return if check_maintenance(user) # auth failed - if !user - render json: { error: 'Wrong Username and Password combination.' }, status: :unauthorized - return - end + raise Exceptions::NotAuthorized, 'Wrong Username and Password combination.' if !user # remember me - set session cookie to expire later request.env['rack.session.options'][:expire_after] = if params[:remember_me] @@ -198,7 +195,7 @@ class SessionsController < ApplicationController # "switch" to user def switch_to_user - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) # check user if !params[:id] @@ -280,7 +277,7 @@ class SessionsController < ApplicationController end def list - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) assets = {} sessions_clean = [] SessionHelper.list.each {|session| @@ -298,7 +295,7 @@ class SessionsController < ApplicationController end def delete - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) SessionHelper.destroy(params[:id]) render json: {} end diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index fb0b021b2..dd4e2a51f 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -5,32 +5,32 @@ class SettingsController < ApplicationController # GET /settings def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(Setting, params) end # GET /settings/1 def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Setting, params) end # POST /settings def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Setting, params) end # PUT /settings/1 def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) - return if !check_access + deny_if_not_role(Z_ROLENAME_ADMIN) + check_access model_update_render(Setting, params) end # PUT /settings/image/:id def update_image - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) if !params[:logo] render json: { @@ -82,8 +82,8 @@ class SettingsController < ApplicationController # DELETE /settings/1 def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) - return if !check_access + deny_if_not_role(Z_ROLENAME_ADMIN) + check_access model_destory_render(Setting, params) end @@ -91,11 +91,8 @@ class SettingsController < ApplicationController def check_access return true if !Setting.get('system_online_service') - setting = Setting.find(params[:id]) return true if setting.preferences && !setting.preferences[:online_service_disable] - - response_access_deny - false + raise Exceptions::NotAuthorized end end diff --git a/app/controllers/signatures_controller.rb b/app/controllers/signatures_controller.rb index 825b48d84..af4a14d26 100644 --- a/app/controllers/signatures_controller.rb +++ b/app/controllers/signatures_controller.rb @@ -96,7 +96,7 @@ curl http://localhost/api/v1/signatures.json -v -u #{login}:#{password} -H "Cont =end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Signature, params) end @@ -125,7 +125,7 @@ curl http://localhost/api/v1/signatures.json -v -u #{login}:#{password} -H "Cont =end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Signature, params) end @@ -140,7 +140,7 @@ Test: =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Signature, params) end end diff --git a/app/controllers/slas_controller.rb b/app/controllers/slas_controller.rb index 45f213e7d..6c02b603d 100644 --- a/app/controllers/slas_controller.rb +++ b/app/controllers/slas_controller.rb @@ -47,7 +47,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} =end def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) if params[:full] @@ -92,7 +92,7 @@ curl http://localhost/api/v1/slas/#{id}.json -v -u #{login}:#{password} =end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Sla, params) end @@ -121,7 +121,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} -H "Content-Ty =end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Sla, params) end @@ -150,7 +150,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} -H "Content-Ty =end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Sla, params) end @@ -168,7 +168,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} -H "Content-Ty =end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Sla, params) end end diff --git a/app/controllers/tags_controller.rb b/app/controllers/tags_controller.rb index 666c8b70c..8556ae2ba 100644 --- a/app/controllers/tags_controller.rb +++ b/app/controllers/tags_controller.rb @@ -75,14 +75,14 @@ class TagsController < ApplicationController # POST /api/v1/tag_list def admin_create - return if deny_if_not_role('Admin') + deny_if_not_role('Admin') Tag::Item.lookup_by_name_and_create(params[:name]) render json: {} end # PUT /api/v1/tag_list/:id def admin_rename - return if deny_if_not_role('Admin') + deny_if_not_role('Admin') Tag::Item.rename( id: params[:id], name: params[:name], @@ -92,7 +92,7 @@ class TagsController < ApplicationController # DELETE /api/v1/tag_list/:id def admin_delete - return if deny_if_not_role('Admin') + deny_if_not_role('Admin') Tag::Item.remove(params[:id]) render json: {} end diff --git a/app/controllers/taskbar_controller.rb b/app/controllers/taskbar_controller.rb index dd643d5f2..2c10db948 100644 --- a/app/controllers/taskbar_controller.rb +++ b/app/controllers/taskbar_controller.rb @@ -12,7 +12,7 @@ class TaskbarController < ApplicationController def show taskbar = Taskbar.find(params[:id]) - return if !access(taskbar) + access(taskbar) model_show_render_item(taskbar) end @@ -23,7 +23,7 @@ class TaskbarController < ApplicationController def update taskbar = Taskbar.find(params[:id]) - return if !access(taskbar) + access(taskbar) taskbar.update_attributes!(Taskbar.param_cleanup(params)) model_update_render_item(taskbar) @@ -31,7 +31,7 @@ class TaskbarController < ApplicationController def destroy taskbar = Taskbar.find(params[:id]) - return if !access(taskbar) + access(taskbar) taskbar.destroy model_destory_render_item() @@ -40,10 +40,6 @@ class TaskbarController < ApplicationController private def access(taskbar) - if taskbar.user_id != current_user.id - render json: { error: 'Not allowed to access this task.' }, status: :unprocessable_entity - return false - end - true + raise Exceptions::UnprocessableEntity, 'Not allowed to access this task.' if taskbar.user_id != current_user.id end end diff --git a/app/controllers/templates_controller.rb b/app/controllers/templates_controller.rb index f12e70b72..96ee542b3 100644 --- a/app/controllers/templates_controller.rb +++ b/app/controllers/templates_controller.rb @@ -47,7 +47,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password} =end def index - return if deny_if_not_role('Agent') + deny_if_not_role('Agent') model_index_render(Template, params) end @@ -69,7 +69,7 @@ curl http://localhost/api/v1/templates/#{id}.json -v -u #{login}:#{password} =end def show - return if deny_if_not_role('Agent') + deny_if_not_role('Agent') model_show_render(Template, params) end @@ -97,7 +97,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password} -H "Conte =end def create - return if deny_if_not_role('Agent') + deny_if_not_role('Agent') model_create_render(Template, params) end @@ -125,7 +125,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password} -H "Conte =end def update - return if deny_if_not_role('Agent') + deny_if_not_role('Agent') model_update_render(Template, params) end @@ -143,7 +143,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password} -H "Conte =end def destroy - return if deny_if_not_role('Agent') + deny_if_not_role('Agent') model_destory_render(Template, params) end end diff --git a/app/controllers/tests_controller.rb b/app/controllers/tests_controller.rb index 70aaf7c23..4e790028e 100644 --- a/app/controllers/tests_controller.rb +++ b/app/controllers/tests_controller.rb @@ -9,4 +9,29 @@ class TestsController < ApplicationController render json: result end + # GET /test/unprocessable_entity + def error_unprocessable_entity + raise Exceptions::UnprocessableEntity, 'some error message' + end + + # GET /test/not_authorized + def error_not_authorized + raise Exceptions::NotAuthorized, 'some error message' + end + + # GET /test/ar_not_found + def error_ar_not_found + raise ActiveRecord::RecordNotFound, 'some error message' + end + + # GET /test/standard_error + def error_standard_error + raise StandardError, 'some error message' + end + + # GET /test/argument_error + def error_argument_error + raise ArgumentError, 'some error message' + end + end diff --git a/app/controllers/ticket_articles_controller.rb b/app/controllers/ticket_articles_controller.rb index 9648e47c6..448b642aa 100644 --- a/app/controllers/ticket_articles_controller.rb +++ b/app/controllers/ticket_articles_controller.rb @@ -5,7 +5,7 @@ class TicketArticlesController < ApplicationController # GET /articles def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(Ticket::Article, params) end @@ -14,7 +14,7 @@ class TicketArticlesController < ApplicationController # permission check article = Ticket::Article.find(params[:id]) - return if !article_permission(article) + article_permission(article) if params[:expand] result = article.attributes_with_relation_names @@ -40,7 +40,7 @@ class TicketArticlesController < ApplicationController # permission check ticket = Ticket.find(params[:id]) - return if !ticket_permission(ticket) + ticket_permission(ticket) articles = [] @@ -98,7 +98,7 @@ class TicketArticlesController < ApplicationController article = Ticket::Article.new(clean_params) # permission check - return if !article_permission(article) + article_permission(article) # find attachments in upload cache if form_id @@ -127,7 +127,7 @@ class TicketArticlesController < ApplicationController # permission check article = Ticket::Article.find(params[:id]) - return if !article_permission(article) + article_permission(article) clean_params = Ticket::Article.param_association_lookup(params) clean_params = Ticket::Article.param_cleanup(clean_params, true) @@ -142,7 +142,7 @@ class TicketArticlesController < ApplicationController # DELETE /articles/1 def destroy article = Ticket::Article.find(params[:id]) - return if !article_permission(article) + article_permission(article) article.destroy head :ok @@ -211,13 +211,11 @@ class TicketArticlesController < ApplicationController # permission check ticket = Ticket.lookup(id: params[:ticket_id]) if !ticket_permission(ticket) - render json: 'No such ticket.', status: :unauthorized - return + raise Exceptions::NotAuthorized, 'No such ticket.' end article = Ticket::Article.find(params[:article_id]) if ticket.id != article.ticket_id - render json: 'No access, article_id/ticket_id is not matching.', status: :unauthorized - return + raise Exceptions::NotAuthorized, 'No access, article_id/ticket_id is not matching.' end list = article.attachments || [] @@ -227,10 +225,7 @@ class TicketArticlesController < ApplicationController access = true end } - if !access - render json: 'Requested file id is not linked with article_id.', status: :unauthorized - return - end + raise Exceptions::NotAuthorized, 'Requested file id is not linked with article_id.' if !access # find file file = Store.find(params[:id]) @@ -247,7 +242,7 @@ class TicketArticlesController < ApplicationController # permission check article = Ticket::Article.find(params[:id]) - return if !article_permission(article) + article_permission(article) list = Store.list( object: 'Ticket::Article::Mail', diff --git a/app/controllers/ticket_priorities_controller.rb b/app/controllers/ticket_priorities_controller.rb index d7f698adf..7d538c506 100644 --- a/app/controllers/ticket_priorities_controller.rb +++ b/app/controllers/ticket_priorities_controller.rb @@ -15,20 +15,20 @@ class TicketPrioritiesController < ApplicationController # POST /ticket_priorities def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Ticket::Priority, params) end # PUT /ticket_priorities/1 def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Ticket::Priority, params) end # DELETE /ticket_priorities/1 def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) - return if model_references_check(Ticket::Priority, params) + deny_if_not_role(Z_ROLENAME_ADMIN) + model_references_check(Ticket::Priority, params) model_destory_render(Ticket::Priority, params) end end diff --git a/app/controllers/ticket_states_controller.rb b/app/controllers/ticket_states_controller.rb index c200cafb9..a03c31c80 100644 --- a/app/controllers/ticket_states_controller.rb +++ b/app/controllers/ticket_states_controller.rb @@ -15,19 +15,19 @@ class TicketStatesController < ApplicationController # POST /ticket_states def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Ticket::State, params) end # PUT /ticket_states/1 def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Ticket::State, params) end # DELETE /ticket_states/1 def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) return if model_references_check(Ticket::State, params) model_destory_render(Ticket::State, params) end diff --git a/app/controllers/tickets_controller.rb b/app/controllers/tickets_controller.rb index efed0db84..79cb2040a 100644 --- a/app/controllers/tickets_controller.rb +++ b/app/controllers/tickets_controller.rb @@ -47,7 +47,7 @@ class TicketsController < ApplicationController # permission check ticket = Ticket.find(params[:id]) - return if !ticket_permission(ticket) + ticket_permission(ticket) if params[:expand] result = ticket.attributes_with_relation_names @@ -119,7 +119,7 @@ class TicketsController < ApplicationController # permission check ticket = Ticket.find(params[:id]) - return if !ticket_permission(ticket) + ticket_permission(ticket) clean_params = Ticket.param_association_lookup(params) clean_params = Ticket.param_cleanup(clean_params, true) @@ -147,7 +147,7 @@ class TicketsController < ApplicationController # permission check ticket = Ticket.find(params[:id]) - return if !ticket_permission(ticket) + ticket_permission(ticket) ticket.destroy @@ -173,7 +173,7 @@ class TicketsController < ApplicationController ticket = Ticket.find(params[:id]) # permission check - return if !ticket_permission(ticket) + ticket_permission(ticket) # get history of ticket history = ticket.history_get(true) @@ -251,7 +251,7 @@ class TicketsController < ApplicationController end # permission check - return if !ticket_permission(ticket_master) + ticket_permission(ticket_master) # check slave ticket ticket_slave = Ticket.find_by(id: params[:slave_ticket_id]) @@ -264,7 +264,7 @@ class TicketsController < ApplicationController end # permission check - return if !ticket_permission(ticket_slave) + ticket_permission(ticket_slave) # check diffetent ticket ids if ticket_slave.id == ticket_master.id @@ -294,7 +294,7 @@ class TicketsController < ApplicationController # permission check ticket = Ticket.find(params[:ticket_id]) - return if !ticket_permission(ticket) + ticket_permission(ticket) assets = ticket.assets({}) # get related articles @@ -356,7 +356,7 @@ class TicketsController < ApplicationController # GET /api/v1/tickets/selector def selector - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) ticket_count, tickets = Ticket.selectors(params[:condition], 6) @@ -385,7 +385,7 @@ class TicketsController < ApplicationController end # permission check - #return if !ticket_permission(ticket) + #ticket_permission(ticket) # lookup open user tickets limit = 100 diff --git a/app/controllers/translations_controller.rb b/app/controllers/translations_controller.rb index c6db7b10e..14532f9c5 100644 --- a/app/controllers/translations_controller.rb +++ b/app/controllers/translations_controller.rb @@ -10,7 +10,7 @@ class TranslationsController < ApplicationController # PUT /translations/push def push - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) start = Time.zone.now Translation.push(params[:locale]) if start > Time.zone.now - 5.seconds @@ -21,51 +21,51 @@ class TranslationsController < ApplicationController # POST /translations/sync/:locale def sync - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) Translation.load(params[:locale]) render json: { message: 'ok' }, status: :ok end # POST /translations/reset def reset - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) Translation.reset(params[:locale]) render json: { message: 'ok' }, status: :ok end # GET /translations/admin/lang/:locale def admin - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) render json: Translation.lang(params[:locale], true) end # GET /translations def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(Translation, params) end # GET /translations/1 def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Translation, params) end # POST /translations def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Translation, params) end # PUT /translations/1 def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Translation, params) end # DELETE /translations/1 def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Translation, params) end end diff --git a/app/controllers/triggers_controller.rb b/app/controllers/triggers_controller.rb index 867f67454..827d8de25 100644 --- a/app/controllers/triggers_controller.rb +++ b/app/controllers/triggers_controller.rb @@ -4,27 +4,27 @@ class TriggersController < ApplicationController before_action :authentication_check def index - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_index_render(Trigger, params) end def show - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_show_render(Trigger, params) end def create - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_create_render(Trigger, params) end def update - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_update_render(Trigger, params) end def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) + deny_if_not_role(Z_ROLENAME_ADMIN) model_destory_render(Trigger, params) end end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index a9291ede0..92d780e66 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -110,127 +110,117 @@ class UsersController < ApplicationController user = User.new(clean_params) user.param_set_associations(params) - begin - - # check if it's first user, tje admin user - # inital admin account - count = User.all.count() - admin_account_exists = true - if count <= 2 - admin_account_exists = false - end - - # if it's a signup, add user to customer role - if !current_user - - # check if feature is enabled - if admin_account_exists && !Setting.get('user_create_account') - render json: { error: 'Feature not enabled!' }, status: :unprocessable_entity - return - end - - # check signup option only after admin account is created - if admin_account_exists && !params[:signup] - render json: { error: 'Only signup with not authenticate user possible!' }, status: :unprocessable_entity - return - end - user.updated_by_id = 1 - user.created_by_id = 1 - - # add first user as admin/agent and to all groups - group_ids = [] - role_ids = [] - if count <= 2 - Role.where(name: [ Z_ROLENAME_ADMIN, 'Agent', 'Chat']).each { |role| - role_ids.push role.id - } - Group.all().each { |group| - group_ids.push group.id - } - - # everybody else will go as customer per default - else - role_ids.push Role.where(name: Z_ROLENAME_CUSTOMER).first.id - end - user.role_ids = role_ids - user.group_ids = group_ids - - # remember source (in case show email verify banner) - # if not inital user creation - if admin_account_exists - user.source = 'signup' - end - - # else do assignment as defined - else - - # permission check by role - return if !permission_check_by_role(params) - - if params[:role_ids] - user.role_ids = params[:role_ids] - end - if params[:group_ids] - user.group_ids = params[:group_ids] - end - end - - # check if user already exists - if user.email - exists = User.where(email: user.email.downcase).first - if exists - render json: { error: 'User already exists!' }, status: :unprocessable_entity - return - end - end - user.save! - - # if first user was added, set system init done - if !admin_account_exists - Setting.set('system_init_done', true) - - # fetch org logo - if user.email - Service::Image.organization_suggest(user.email) - end - end - - # send inviteation if needed / only if session exists - if params[:invite] && current_user - token = Token.create(action: 'PasswordReset', user_id: user.id) - NotificationFactory::Mailer.notification( - template: 'user_invite', - user: user, - objects: { - token: token, - user: user, - current_user: current_user, - } - ) - end - - # send email verify - if params[:signup] && !current_user - result = User.signup_new_token(user) - NotificationFactory::Mailer.notification( - template: 'signup', - user: user, - objects: result, - ) - end - - if params[:expand] - user = User.find(user.id).attributes_with_relation_names - render json: user, status: :created - return - end - - user_new = User.find(user.id).attributes_with_associations - user_new.delete('password') - render json: user_new, status: :created - rescue => e - render json: model_match_error(e.message), status: :unprocessable_entity + # check if it's first user, tje admin user + # inital admin account + count = User.all.count() + admin_account_exists = true + if count <= 2 + admin_account_exists = false end + + # if it's a signup, add user to customer role + if !current_user + + # check if feature is enabled + if admin_account_exists && !Setting.get('user_create_account') + raise Exceptions::UnprocessableEntity, 'Feature not enabled!' + end + + # check signup option only after admin account is created + if admin_account_exists && !params[:signup] + raise Exceptions::UnprocessableEntity, 'Only signup with not authenticate user possible!' + end + user.updated_by_id = 1 + user.created_by_id = 1 + + # add first user as admin/agent and to all groups + group_ids = [] + role_ids = [] + if count <= 2 + Role.where(name: [ Z_ROLENAME_ADMIN, 'Agent', 'Chat']).each { |role| + role_ids.push role.id + } + Group.all().each { |group| + group_ids.push group.id + } + + # everybody else will go as customer per default + else + role_ids.push Role.where(name: Z_ROLENAME_CUSTOMER).first.id + end + user.role_ids = role_ids + user.group_ids = group_ids + + # remember source (in case show email verify banner) + # if not inital user creation + if admin_account_exists + user.source = 'signup' + end + + # else do assignment as defined + else + + # permission check by role + permission_check_by_role(params) + + if params[:role_ids] + user.role_ids = params[:role_ids] + end + if params[:group_ids] + user.group_ids = params[:group_ids] + end + end + + # check if user already exists + if user.email + exists = User.where(email: user.email.downcase).first + raise Exceptions::UnprocessableEntity, 'User already exists!' if exists + end + user.save! + + # if first user was added, set system init done + if !admin_account_exists + Setting.set('system_init_done', true) + + # fetch org logo + if user.email + Service::Image.organization_suggest(user.email) + end + end + + # send inviteation if needed / only if session exists + if params[:invite] && current_user + token = Token.create(action: 'PasswordReset', user_id: user.id) + NotificationFactory::Mailer.notification( + template: 'user_invite', + user: user, + objects: { + token: token, + user: user, + current_user: current_user, + } + ) + end + + # send email verify + if params[:signup] && !current_user + result = User.signup_new_token(user) + NotificationFactory::Mailer.notification( + template: 'signup', + user: user, + objects: result, + ) + end + + if params[:expand] + user = User.find(user.id).attributes_with_relation_names + render json: user, status: :created + return + end + + user_new = User.find(user.id).attributes_with_associations + user_new.delete('password') + render json: user_new, status: :created end # @path [PUT] /users/{id} @@ -252,42 +242,37 @@ class UsersController < ApplicationController clean_params = User.param_association_lookup(params) clean_params = User.param_cleanup(clean_params, true) - begin + # permission check by role + permission_check_by_role(params) + user.update_attributes(clean_params) - # permission check by role - return if !permission_check_by_role(params) - user.update_attributes(clean_params) - - # only allow Admin's and Agent's - if role?(Z_ROLENAME_ADMIN) && role?('Agent') && (params[:role_ids] || params[:roles]) - user.role_ids = params[:role_ids] - user.param_set_associations({ role_ids: params[:role_ids], roles: params[:roles] }) - end - - # only allow Admin's - if role?(Z_ROLENAME_ADMIN) && (params[:group_ids] || params[:groups]) - user.group_ids = params[:group_ids] - user.param_set_associations({ group_ids: params[:group_ids], groups: params[:groups] }) - end - - # only allow Admin's and Agent's - if role?(Z_ROLENAME_ADMIN) && role?('Agent') && (params[:organization_ids] || params[:organizations]) - user.param_set_associations({ organization_ids: params[:organization_ids], organizations: params[:organizations] }) - end - - if params[:expand] - user = User.find(user.id).attributes_with_relation_names - render json: user, status: :ok - return - end - - # get new data - user_new = User.find(user.id).attributes_with_associations - user_new.delete('password') - render json: user_new, status: :ok - rescue => e - render json: { error: e.message }, status: :unprocessable_entity + # only allow Admin's and Agent's + if role?(Z_ROLENAME_ADMIN) && role?('Agent') && (params[:role_ids] || params[:roles]) + user.role_ids = params[:role_ids] + user.param_set_associations({ role_ids: params[:role_ids], roles: params[:roles] }) end + + # only allow Admin's + if role?(Z_ROLENAME_ADMIN) && (params[:group_ids] || params[:groups]) + user.group_ids = params[:group_ids] + user.param_set_associations({ group_ids: params[:group_ids], groups: params[:groups] }) + end + + # only allow Admin's and Agent's + if role?(Z_ROLENAME_ADMIN) && role?('Agent') && (params[:organization_ids] || params[:organizations]) + user.param_set_associations({ organization_ids: params[:organization_ids], organizations: params[:organizations] }) + end + + if params[:expand] + user = User.find(user.id).attributes_with_relation_names + render json: user, status: :ok + return + end + + # get new data + user_new = User.find(user.id).attributes_with_associations + user_new.delete('password') + render json: user_new, status: :ok end # @path [DELETE] /users/{id} @@ -300,8 +285,8 @@ class UsersController < ApplicationController # @response_message 200 User successfully deleted. # @response_message 401 Invalid session. def destroy - return if deny_if_not_role(Z_ROLENAME_ADMIN) - return if model_references_check(User, params) + deny_if_not_role(Z_ROLENAME_ADMIN) + model_references_check(User, params) model_destory_render(User, params) end @@ -507,16 +492,10 @@ curl http://localhost/api/v1/users/email_verify.json -v -u #{login}:#{password} =end def email_verify - if !params[:token] - render json: { message: 'No token!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No token!' if !params[:token] user = User.signup_verify_via_token(params[:token], current_user) - if !user - render json: { message: 'Invalid token!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'Invalid token!' if !user render json: { message: 'ok', user_email: user.email }, status: :ok end @@ -543,17 +522,11 @@ curl http://localhost/api/v1/users/email_verify_send.json -v -u #{login}:#{passw def email_verify_send - if !params[:email] - render json: { message: 'No email!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email] # check is verify is possible to send user = User.find_by(email: params[:email].downcase) - if !user - render json: { error: 'No such user!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No such user!' if !user #if user.verified == true # render json: { error: 'Already verified!' }, status: :unprocessable_entity @@ -609,10 +582,7 @@ curl http://localhost/api/v1/users/password_reset.json -v -u #{login}:#{password def password_reset_send # check if feature is enabled - if !Setting.get('user_lost_password') - render json: { error: 'Feature not enabled!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'Feature not enabled!' if !Setting.get('user_lost_password') result = User.password_reset_new_token(params[:username]) if result && result[:token] @@ -779,10 +749,8 @@ curl http://localhost/api/v1/users/preferences.json -v -u #{login}:#{password} - =end def preferences - if !current_user - render json: { message: 'No current user!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user + if params[:user] user = User.find(current_user.id) params[:user].each {|key, value| @@ -815,20 +783,11 @@ curl http://localhost/api/v1/users/account.json -v -u #{login}:#{password} -H "C =end def account_remove - if !current_user - render json: { message: 'No current user!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user # provider + uid to remove - if !params[:provider] - render json: { message: 'provider needed!' }, status: :unprocessable_entity - return - end - if !params[:uid] - render json: { message: 'uid needed!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider] + raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid] # remove from database record = Authorization.where( @@ -836,10 +795,8 @@ curl http://localhost/api/v1/users/account.json -v -u #{login}:#{password} -H "C provider: params[:provider], uid: params[:uid], ) - if !record.first - render json: { message: 'No record found!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No record found!' if !record.first + record.destroy_all render json: { message: 'ok' }, status: :ok end @@ -938,10 +895,7 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content return if !valid_session_with_user # get & validate image - if !params[:id] - render json: { message: 'No id of avatar!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id] # set as default avatar = Avatar.set_default('User', current_user.id, params[:id]) @@ -957,10 +911,7 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content return if !valid_session_with_user # get & validate image - if !params[:id] - render json: { message: 'No id of avatar!' }, status: :unprocessable_entity - return - end + raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id] # remove avatar Avatar.remove_one('User', current_user.id, params[:id]) @@ -1006,15 +957,13 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content params[:role_ids].each {|role_id| role_local = Role.lookup(id: role_id) if !role_local - render json: { error: 'Invalid role_ids!' }, status: :unauthorized logger.info "Invalid role_ids for current_user_id: #{current_user.id} role_ids #{role_id}" - return false + raise Exceptions::NotAuthorized, 'Invalid role_ids!' end role_name = role_local.name next if role_name != 'Admin' && role_name != 'Agent' - render json: { error: 'This role assignment is only allowed by admin!' }, status: :unauthorized logger.info "This role assignment is only allowed by admin! current_user_id: #{current_user.id} assigned to #{role_name}" - return false + raise Exceptions::NotAuthorized, 'This role assignment is only allowed by admin!' } end @@ -1023,9 +972,8 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content params[:group_ids] = [params[:group_ids]] end if !params[:group_ids].empty? - render json: { error: 'Group relation is only allowed by admin!' }, status: :unauthorized logger.info "Group relation is only allowed by admin! current_user_id: #{current_user.id} group_ids #{params[:group_ids].inspect}" - return false + raise Exceptions::NotAuthorized, 'Group relation is only allowed by admin!' end end diff --git a/config/routes.rb b/config/routes.rb index 217366e7c..dd7fbc34c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -18,4 +18,6 @@ Rails.application.routes.draw do end } + match '*a', to: 'errors#routing', via: [:get, :post, :put, :delete] + end diff --git a/config/routes/test.rb b/config/routes/test.rb index 639adf2d1..56730879f 100644 --- a/config/routes/test.rb +++ b/config/routes/test.rb @@ -1,20 +1,25 @@ Zammad::Application.routes.draw do - match '/tests_core', to: 'tests#core', via: :get - match '/tests_ui', to: 'tests#ui', via: :get - match '/tests_model', to: 'tests#model', via: :get - match '/tests_model_ui', to: 'tests#model_ui', via: :get - match '/tests_form', to: 'tests#form', via: :get - match '/tests_form_find', to: 'tests#form_find', via: :get - match '/tests_form_trim', to: 'tests#form_trim', via: :get - match '/tests_form_extended', to: 'tests#form_extended', via: :get - match '/tests_form_timer', to: 'tests#form_timer', via: :get - match '/tests_form_validation', to: 'tests#form_validation', via: :get - match '/tests_form_column_select', to: 'tests#form_column_select', via: :get - match '/tests_form_searchable_select', to: 'tests#form_searchable_select', via: :get - match '/tests_table', to: 'tests#table', via: :get - match '/tests_html_utils', to: 'tests#html_utils', via: :get - match '/tests_taskbar', to: 'tests#taskbar', via: :get - match '/tests/wait/:sec', to: 'tests#wait', via: :get + match '/tests_core', to: 'tests#core', via: :get + match '/tests_ui', to: 'tests#ui', via: :get + match '/tests_model', to: 'tests#model', via: :get + match '/tests_model_ui', to: 'tests#model_ui', via: :get + match '/tests_form', to: 'tests#form', via: :get + match '/tests_form_find', to: 'tests#form_find', via: :get + match '/tests_form_trim', to: 'tests#form_trim', via: :get + match '/tests_form_extended', to: 'tests#form_extended', via: :get + match '/tests_form_timer', to: 'tests#form_timer', via: :get + match '/tests_form_validation', to: 'tests#form_validation', via: :get + match '/tests_form_column_select', to: 'tests#form_column_select', via: :get + match '/tests_form_searchable_select', to: 'tests#form_searchable_select', via: :get + match '/tests_table', to: 'tests#table', via: :get + match '/tests_html_utils', to: 'tests#html_utils', via: :get + match '/tests_taskbar', to: 'tests#taskbar', via: :get + match '/tests/wait/:sec', to: 'tests#wait', via: :get + match '/tests/unprocessable_entity', to: 'tests#error_unprocessable_entity', via: :get + match '/tests/not_authorized', to: 'tests#error_not_authorized', via: :get + match '/tests/ar_not_found', to: 'tests#error_ar_not_found', via: :get + match '/tests/standard_error', to: 'tests#error_standard_error', via: :get + match '/tests/argument_error', to: 'tests#error_argument_error', via: :get end diff --git a/lib/exceptions.rb b/lib/exceptions.rb new file mode 100644 index 000000000..3951068e4 --- /dev/null +++ b/lib/exceptions.rb @@ -0,0 +1,6 @@ +module Exceptions + + class NotAuthorized < StandardError; end + class UnprocessableEntity < StandardError; end + +end diff --git a/public/401.html b/public/401.html new file mode 100644 index 000000000..64c1d5368 --- /dev/null +++ b/public/401.html @@ -0,0 +1,21 @@ + + + +401: Unauthorized + +class="error-message"<% end %>> +

401: Unauthorized

+<% if !@traceback %> +
+

Sorry, but you're not allowed to access this page. If you're registered please log in and refresh this page.

+<% else %> +
<%= @exception.message %>
+ <% if @exception.backtrace %> +
Traceback:
+ <% @exception.backtrace.each {|row| %> + <%= row %>
+ <% } %> + <% end %> +<% end %> + + \ No newline at end of file diff --git a/public/404.html b/public/404.html index 653716afa..a072faae7 100644 --- a/public/404.html +++ b/public/404.html @@ -3,8 +3,19 @@ 404: Not Found - -

404: Requested Page was not found.

-
-

Sorry, but the Phoenix is not able to find your page. Try checking the URL for errors.

+class="error-message"<% end %>> +

404: Requested Ressource was not found.

+<% if !@traceback %> +
+

Sorry, but the Phoenix is not able to find your ressource. Try checking the URL for errors.

+<% else %> +
<%= @exception.message %>
+ <% if @exception.backtrace %> +
Traceback:
+ <% @exception.backtrace.each {|row| %> + <%= row %>
+ <% } %> + <% end %> +<% end %> + \ No newline at end of file diff --git a/public/422.html b/public/422.html index 42db85126..2b0688b74 100644 --- a/public/422.html +++ b/public/422.html @@ -1,10 +1,20 @@ -422: Not Found +422: Unprocessable Entity - -

422: The change you wanted was rejected.

-
-

Maybe you tried to change something you didn't have access to.

+class="error-message"<% end %>> +

422: The change you wanted was rejected.

+<% if !@traceback %> +
+

Maybe you tried to change something you didn't have access to.

+<% else %> +
<%= @exception.message %>
+ <% if @exception.backtrace %> +
Traceback:
+ <% @exception.backtrace.each {|row| %> + <%= row %>
+ <% } %> + <% end %> +<% end %> \ No newline at end of file diff --git a/public/500.html b/public/500.html index a07e0040c..2d4d0c249 100644 --- a/public/500.html +++ b/public/500.html @@ -3,8 +3,19 @@ 500: Something went wrong - +class="error-message"<% end %>>

500: We're sorry, but something went wrong.

-
-

We're sorry, but something went wrong.

+<% if !@traceback %> +
+

We're sorry, but something went wrong.

+<% else %> +
<%= @exception.message %>
+ <% if @exception.backtrace %> +
Traceback:
+ <% @exception.backtrace.each {|row| %> + <%= row %>
+ <% } %> + <% end %> +<% end %> + \ No newline at end of file diff --git a/public/assets/error/style.css b/public/assets/error/style.css index 1149427d4..c4f893445 100644 --- a/public/assets/error/style.css +++ b/public/assets/error/style.css @@ -43,6 +43,10 @@ body { overflow-x: hidden; } +body.error-message { + height: auto; +} + h1 { margin: 0; color: #444a4f; diff --git a/test/controllers/basic_controller_test.rb b/test/controllers/basic_controller_test.rb new file mode 100644 index 000000000..789058286 --- /dev/null +++ b/test/controllers/basic_controller_test.rb @@ -0,0 +1,121 @@ +# encoding: utf-8 +require 'test_helper' + +class BasicControllerTest < ActionDispatch::IntegrationTest + + test 'json requests' do + + @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } + + # 404 + get '/not_existing_url', {}, @headers + assert_response(404) + result = JSON.parse(@response.body) + assert_equal(result.class, Hash) + assert(result['error'], 'No route matches [GET] /not_existing_url') + + # 401 + get '/api/v1/organizations', {}, @headers + assert_response(401) + result = JSON.parse(@response.body) + assert_equal(result.class, Hash) + assert(result['error'], 'authentication failed') + + # 422 + get '/tests/unprocessable_entity', {}, @headers + assert_response(422) + result = JSON.parse(@response.body) + assert_equal(result.class, Hash) + assert(result['error'], 'some error message') + + # 401 + get '/tests/not_authorized', {}, @headers + assert_response(401) + result = JSON.parse(@response.body) + assert_equal(result.class, Hash) + assert(result['error'], 'some error message') + + # 401 + get '/tests/ar_not_found', {}, @headers + assert_response(404) + result = JSON.parse(@response.body) + assert_equal(result.class, Hash) + assert(result['error'], 'some error message') + + # 500 + get '/tests/standard_error', {}, @headers + assert_response(500) + result = JSON.parse(@response.body) + assert_equal(result.class, Hash) + assert(result['error'], 'some error message') + + # 422 + get '/tests/argument_error', {}, @headers + assert_response(422) + result = JSON.parse(@response.body) + assert_equal(result.class, Hash) + assert(result['error'], 'some error message') + + end + + test 'html requests' do + + # 404 + get '/not_existing_url', {}, @headers + assert_response(404) + assert_match(/404: Not Found}, @response.body) + assert_match(%r{

404: Requested Ressource was not found.

}, @response.body) + assert_match(%r{No route matches \[GET\] /not_existing_url}, @response.body) + + # 401 + get '/api/v1/organizations', {}, @headers + assert_response(401) + assert_match(/401: Unauthorized}, @response.body) + assert_match(%r{

401: Unauthorized

}, @response.body) + assert_match(/authentication failed/, @response.body) + + # 422 + get '/tests/unprocessable_entity', {}, @headers + assert_response(422) + assert_match(/422: Unprocessable Entity}, @response.body) + assert_match(%r{

422: The change you wanted was rejected.

}, @response.body) + assert_match(/some error message/, @response.body) + + # 401 + get '/tests/not_authorized', {}, @headers + assert_response(401) + assert_match(/401: Unauthorized}, @response.body) + assert_match(%r{

401: Unauthorized

}, @response.body) + assert_match(/some error message/, @response.body) + + # 401 + get '/tests/ar_not_found', {}, @headers + assert_response(404) + assert_match(/404: Not Found}, @response.body) + assert_match(%r{

404: Requested Ressource was not found.

}, @response.body) + assert_match(/some error message/, @response.body) + + # 500 + get '/tests/standard_error', {}, @headers + assert_response(500) + assert_match(/500: Something went wrong}, @response.body) + assert_match(%r{

500: We're sorry, but something went wrong.

}, @response.body) + assert_match(/some error message/, @response.body) + + # 422 + get '/tests/argument_error', {}, @headers + assert_response(422) + assert_match(/422: Unprocessable Entity}, @response.body) + assert_match(%r{

422: The change you wanted was rejected.

}, @response.body) + assert_match(/some error message/, @response.body) + + end + +end diff --git a/test/controllers/packages_controller_test.rb b/test/controllers/packages_controller_test.rb index 4992801d5..84fd39122 100644 --- a/test/controllers/packages_controller_test.rb +++ b/test/controllers/packages_controller_test.rb @@ -8,7 +8,7 @@ class PackagesControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where( name: %w(Admin Agent) ) + roles = Role.where(name: %w(Admin Agent)) groups = Group.all UserInfo.current_user_id = 1 @@ -24,7 +24,7 @@ class PackagesControllerTest < ActionDispatch::IntegrationTest ) # create agent - roles = Role.where( name: 'Agent' ) + roles = Role.where(name: 'Agent') @agent = User.create_or_update( login: 'packages-agent@example.com', firstname: 'Rest', @@ -37,7 +37,7 @@ class PackagesControllerTest < ActionDispatch::IntegrationTest ) # create customer without org - roles = Role.where( name: 'Customer' ) + roles = Role.where(name: 'Customer') @customer_without_org = User.create_or_update( login: 'packages-customer1@example.com', firstname: 'Packages', @@ -53,7 +53,7 @@ class PackagesControllerTest < ActionDispatch::IntegrationTest test 'packages index with nobody' do # index - get '/api/v1/packages' + get '/api/v1/packages', {}, @headers assert_response(401) result = JSON.parse(@response.body) assert_equal(result.class, Hash) diff --git a/test/controllers/settings_controller_test.rb b/test/controllers/settings_controller_test.rb index 9ff63a560..bdb6ccb4e 100644 --- a/test/controllers/settings_controller_test.rb +++ b/test/controllers/settings_controller_test.rb @@ -8,7 +8,7 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where( name: %w(Admin Agent) ) + roles = Role.where(name: %w(Admin Agent)) groups = Group.all UserInfo.current_user_id = 1 @@ -24,7 +24,7 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest ) # create agent - roles = Role.where( name: 'Agent' ) + roles = Role.where(name: 'Agent') @agent = User.create_or_update( login: 'packages-agent@example.com', firstname: 'Rest', @@ -37,7 +37,7 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest ) # create customer without org - roles = Role.where( name: 'Customer' ) + roles = Role.where(name: 'Customer') @customer_without_org = User.create_or_update( login: 'packages-customer1@example.com', firstname: 'Packages', @@ -53,7 +53,7 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest test 'settings index with nobody' do # index - get '/api/v1/settings' + get '/api/v1/settings', {}, @headers assert_response(401) result = JSON.parse(@response.body) assert_equal(result.class, Hash) diff --git a/test/controllers/user_organization_controller_test.rb b/test/controllers/user_organization_controller_test.rb index 20b3f264c..5a288941b 100644 --- a/test/controllers/user_organization_controller_test.rb +++ b/test/controllers/user_organization_controller_test.rb @@ -8,7 +8,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest @headers = { 'ACCEPT' => 'application/json', 'CONTENT_TYPE' => 'application/json' } # create agent - roles = Role.where( name: %w(Admin Agent) ) + roles = Role.where(name: %w(Admin Agent)) groups = Group.all UserInfo.current_user_id = 1 @@ -24,7 +24,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest ) # create agent - roles = Role.where( name: 'Agent' ) + roles = Role.where(name: 'Agent') @agent = User.create_or_update( login: 'rest-agent@example.com', firstname: 'Rest', @@ -37,7 +37,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest ) # create customer without org - roles = Role.where( name: 'Customer' ) + roles = Role.where(name: 'Customer') @customer_without_org = User.create_or_update( login: 'rest-customer1@example.com', firstname: 'Rest', @@ -217,7 +217,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest assert_equal(result.class, Hash) assert_equal(result['email'], 'rest-agent@example.com') - get "/api/v1/users/#{@customer_without_org.id}", {}, 'Authorization' => credentials + get "/api/v1/users/#{@customer_without_org.id}", {}, @headers.merge('Authorization' => credentials) assert_response(200) result = JSON.parse(@response.body) assert(result) @@ -320,7 +320,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest assert_response(401) result = JSON.parse(@response.body) assert_equal(result.class, Hash) - assert(result.empty?) + assert(result['error']) # create user with admin role role = Role.lookup(name: 'Admin') @@ -356,10 +356,9 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest get "/api/v1/users/#{@customer_without_org.id}", {}, @headers.merge('Authorization' => credentials) assert_response(401) - #puts @response.body result = JSON.parse(@response.body) assert_equal(result.class, Hash) - assert(result.empty?) + assert(result['error']) end