Improved error handling for json requests.

This commit is contained in:
Martin Edenhofer 2016-06-30 10:24:03 +02:00
parent 977c05204c
commit 9fe709f9b7
48 changed files with 656 additions and 519 deletions

View file

@ -1,4 +1,5 @@
# Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/ # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
require 'exceptions'
class ApplicationController < ActionController::Base class ApplicationController < ActionController::Base
# http_basic_authenticate_with :name => "test", :password => "ttt" # 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 before_action :set_user, :session_update, :user_device_check, :cors_preflight_check
after_action :trigger_events, :http_log, :set_access_control_headers 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. # For all responses in this controller, return the CORS access control headers.
def set_access_control_headers def set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Origin'] = '*'
@ -192,8 +200,7 @@ class ApplicationController < ActionController::Base
# for sessions we need the fingperprint # for sessions we need the fingperprint
if type == 'session' if type == 'session'
if !session[:user_device_updated_at] && !params[:fingerprint] && !session[:user_device_fingerprint] if !session[:user_device_updated_at] && !params[:fingerprint] && !session[:user_device_fingerprint]
render json: { error: 'Need fingerprint param!' }, status: :unprocessable_entity raise Exceptions::UnprocessableEntity, 'Need fingerprint param!'
return false
end end
if params[:fingerprint] if params[:fingerprint]
session[:user_device_fingerprint] = params[:fingerprint] session[:user_device_fingerprint] = params[:fingerprint]
@ -310,13 +317,7 @@ class ApplicationController < ActionController::Base
# return auth not ok # return auth not ok
if result[:auth] == false if result[:auth] == false
render( raise Exceptions::NotAuthorized, result[:message]
json: {
error: result[:message],
},
status: :unauthorized
)
return false
end end
# return auth ok # return auth ok
@ -330,35 +331,27 @@ class ApplicationController < ActionController::Base
def ticket_permission(ticket) def ticket_permission(ticket)
return true if ticket.permission(current_user: current_user) return true if ticket.permission(current_user: current_user)
response_access_deny raise Exceptions::NotAuthorized
false
end end
def article_permission(article) def article_permission(article)
ticket = Ticket.lookup(id: article.ticket_id) ticket = Ticket.lookup(id: article.ticket_id)
return true if ticket.permission(current_user: current_user) return true if ticket.permission(current_user: current_user)
response_access_deny raise Exceptions::NotAuthorized
false
end end
def deny_if_not_role(role_name) def deny_if_not_role(role_name)
return false if role?(role_name) return false if role?(role_name)
response_access_deny raise Exceptions::NotAuthorized
true
end end
def valid_session_with_user def valid_session_with_user
return true if current_user return true if current_user
render json: { message: 'No session user!' }, status: :unprocessable_entity raise Exceptions::UnprocessableEntity, 'No session user!'
false
end end
def response_access_deny def response_access_deny
render( raise Exceptions::NotAuthorized
json: {},
status: :unauthorized
)
false
end end
def config_frontend def config_frontend
@ -401,10 +394,6 @@ class ApplicationController < ActionController::Base
end end
model_create_render_item(generic_object) 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 end
def model_create_render_item(generic_object) def model_create_render_item(generic_object)
@ -431,10 +420,6 @@ class ApplicationController < ActionController::Base
end end
model_update_render_item(generic_object) 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 end
def model_update_render_item(generic_object) def model_update_render_item(generic_object)
@ -445,10 +430,6 @@ class ApplicationController < ActionController::Base
generic_object = object.find(params[:id]) generic_object = object.find(params[:id])
generic_object.destroy generic_object.destroy
model_destory_render_item() 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 end
def model_destory_render_item () def model_destory_render_item ()
@ -471,10 +452,6 @@ class ApplicationController < ActionController::Base
generic_object = object.find(params[:id]) generic_object = object.find(params[:id])
model_show_render_item(generic_object) 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 end
def model_show_render_item(generic_object) def model_show_render_item(generic_object)
@ -522,10 +499,6 @@ class ApplicationController < ActionController::Base
generic_objects_with_associations.push item.attributes_with_associations generic_objects_with_associations.push item.attributes_with_associations
} }
model_index_render_result(generic_objects_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 end
def model_index_render_result(generic_objects) def model_index_render_result(generic_objects)
@ -546,18 +519,62 @@ class ApplicationController < ActionController::Base
generic_object = object.find(params[:id]) generic_object = object.find(params[:id])
result = Models.references(object, generic_object.id) result = Models.references(object, generic_object.id)
return false if result.empty? return false if result.empty?
render json: { error: 'Can\'t delete, object has references.' }, status: :unprocessable_entity raise Exceptions::UnprocessableEntity, 'Can\'t delete, object has references.'
true
rescue => e rescue => e
logger.error e.message raise Exceptions::UnprocessableEntity, e
logger.error e.backtrace.inspect
render json: model_match_error(e.message), status: :unprocessable_entity
end end
def not_found(e) def not_found(e)
logger.error e.message
logger.error e.backtrace.inspect
respond_to do |format| respond_to do |format|
format.json { render json: { error: e.message }, status: :not_found } format.json { render json: model_match_error(e.message), status: :not_found }
format.any { render text: "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
end end
@ -571,8 +588,7 @@ class ApplicationController < ActionController::Base
def check_maintenance(user) def check_maintenance(user)
return false if !check_maintenance_only(user) return false if !check_maintenance_only(user)
render json: { error: 'Maintenance mode enabled!' }, status: :unauthorized raise Exceptions::NotAuthorized, 'Maintenance mode enabled!'
true
end end
end end

View file

@ -4,7 +4,7 @@ class CalendarsController < ApplicationController
before_action :authentication_check before_action :authentication_check
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
# calendars # calendars
assets = {} assets = {}
@ -25,22 +25,22 @@ class CalendarsController < ApplicationController
end end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Calendar, params) model_show_render(Calendar, params)
end end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Calendar, params) model_create_render(Calendar, params)
end end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Calendar, params) model_update_render(Calendar, params)
end end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Calendar, params) model_destory_render(Calendar, params)
end end
end end

View file

@ -17,8 +17,8 @@ curl http://localhost/api/v1/group/channels.json -v -u #{login}:#{password} -H "
=end =end
def group_update def group_update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
return if !check_access check_access
channel = Channel.find(params[:id]) channel = Channel.find(params[:id])
channel.group_id = params[:group_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 =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
return if !check_access check_access
model_destory_render(Channel, params) model_destory_render(Channel, params)
end end
@ -64,7 +64,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten
end end
def twitter_verify def twitter_verify
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Channel, params) model_update_render(Channel, params)
end end
@ -87,12 +87,12 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten
end end
def facebook_verify def facebook_verify
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Channel, params) model_update_render(Channel, params)
end end
def email_index 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') system_online_service = Setting.get('system_online_service')
account_channel_ids = [] account_channel_ids = []
notification_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 def email_probe
# check admin permissions # 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 # probe settings based on email and password
result = EmailHelper::Probe.full( result = EmailHelper::Probe.full(
@ -163,7 +163,7 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten
def email_outbound def email_outbound
# check admin permissions # check admin permissions
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
# verify access # verify access
return if params[:channel_id] && !check_access(params[:channel_id]) 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 def email_inbound
# check admin permissions # check admin permissions
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
# verify access # verify access
return if params[:channel_id] && !check_access(params[:channel_id]) 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 def email_verify
# check admin permissions # 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 = params[:email] || params[:meta][:email]
email = email.downcase email = email.downcase
@ -284,10 +284,10 @@ curl http://localhost/api/v1/channels.json -v -u #{login}:#{password} -H "Conten
def email_notification def email_notification
return if !check_online_service check_online_service
# check admin permissions # check admin permissions
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
adapter = params[:adapter].downcase 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 def check_online_service
return true if !Setting.get('system_online_service') return true if !Setting.get('system_online_service')
response_access_deny raise Exceptions::NotAuthorized
false
end end
def check_access(id = nil) 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) channel = Channel.find(id)
return true if channel.preferences && !channel.preferences[:online_service_disable] return true if channel.preferences && !channel.preferences[:online_service_disable]
response_access_deny raise Exceptions::NotAuthorized
false
end end
end end

View file

@ -4,7 +4,7 @@ class ChatsController < ApplicationController
before_action :authentication_check before_action :authentication_check
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
chat_ids = [] chat_ids = []
assets = {} assets = {}
Chat.order(:id).each {|chat| Chat.order(:id).each {|chat|
@ -20,22 +20,22 @@ class ChatsController < ApplicationController
end end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Chat, params) model_show_render(Chat, params)
end end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Chat, params) model_create_render(Chat, params)
end end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Chat, params) model_update_render(Chat, params)
end end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Chat, params) model_destory_render(Chat, params)
end end
end end

View file

@ -5,7 +5,7 @@ class CtiController < ApplicationController
# list current caller log # list current caller log
def index def index
return if deny_if_not_role('CTI') deny_if_not_role('CTI')
backends = [ backends = [
{ {
@ -22,7 +22,7 @@ class CtiController < ApplicationController
# set caller log to done # set caller log to done
def done def done
return if deny_if_not_role('CTI') deny_if_not_role('CTI')
log = Cti::Log.find(params['id']) log = Cti::Log.find(params['id'])
log.done = params['done'] log.done = params['done']
log.save log.save

View file

@ -97,7 +97,7 @@ curl http://localhost/api/v1/email_addresses.json -v -u #{login}:#{password} -H
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(EmailAddress, params) model_create_render(EmailAddress, params)
end end
@ -128,7 +128,7 @@ curl http://localhost/api/v1/email_addresses/#{id}.json -v -u #{login}:#{passwor
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(EmailAddress, params) model_update_render(EmailAddress, params)
end end
@ -146,7 +146,7 @@ curl http://localhost/api/v1/email_addresses/#{id}.json -v -u #{login}:#{passwor
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(EmailAddress, params) model_destory_render(EmailAddress, params)
end end
end end

View file

@ -0,0 +1,5 @@
class ErrorsController < ApplicationController
def routing
not_found(ActionController::RoutingError.new("No route matches [#{request.method}] #{request.path}"))
end
end

View file

@ -4,27 +4,27 @@ class ExternalCredentialsController < ApplicationController
before_action :authentication_check before_action :authentication_check
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(ExternalCredential, params) model_index_render(ExternalCredential, params)
end end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(ExternalCredential, params) model_show_render(ExternalCredential, params)
end end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(ExternalCredential, params) model_create_render(ExternalCredential, params)
end end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(ExternalCredential, params) model_update_render(ExternalCredential, params)
end end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(ExternalCredential, params) model_destory_render(ExternalCredential, params)
end end
@ -37,7 +37,7 @@ class ExternalCredentialsController < ApplicationController
end end
def link_account def link_account
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
provider = params[:provider].downcase provider = params[:provider].downcase
attributes = ExternalCredential.request_account_to_link(provider) attributes = ExternalCredential.request_account_to_link(provider)
session[:request_token] = attributes[:request_token] session[:request_token] = attributes[:request_token]
@ -45,7 +45,7 @@ class ExternalCredentialsController < ApplicationController
end end
def callback def callback
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
provider = params[:provider].downcase provider = params[:provider].downcase
channel = ExternalCredential.link_account(provider, session[:request_token], params) channel = ExternalCredential.link_account(provider, session[:request_token], params)
session[:request_token] = nil session[:request_token] = nil

View file

@ -111,7 +111,7 @@ curl http://localhost/api/v1/getting_started -v -u #{login}:#{password}
def base def base
# check admin permissions # check admin permissions
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
# validate url # validate url
messages = {} messages = {}

View file

@ -101,7 +101,7 @@ curl http://localhost/api/v1/groups -v -u #{login}:#{password} -H "Content-Type:
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Group, params) model_create_render(Group, params)
end end
@ -133,7 +133,7 @@ curl http://localhost/api/v1/groups -v -u #{login}:#{password} -H "Content-Type:
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Group, params) model_update_render(Group, params)
end end
@ -151,7 +151,7 @@ curl http://localhost/api/v1/groups/{id} -v -u #{login}:#{password} -H "Content-
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Group, params) model_destory_render(Group, params)
end end
end end

View file

@ -5,7 +5,7 @@ class HttpLogsController < ApplicationController
# GET /http_logs/:facility # GET /http_logs/:facility
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
list = if params[:facility] list = if params[:facility]
HttpLog.where(facility: params[:facility]).order('created_at DESC').limit(params[:limit] || 50) HttpLog.where(facility: params[:facility]).order('created_at DESC').limit(params[:limit] || 50)
else else
@ -16,7 +16,7 @@ class HttpLogsController < ApplicationController
# POST /http_logs # POST /http_logs
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(HttpLog, params) model_create_render(HttpLog, params)
end end

View file

@ -4,27 +4,27 @@ class JobsController < ApplicationController
before_action :authentication_check before_action :authentication_check
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(Job, params) model_index_render(Job, params)
end end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Job, params) model_show_render(Job, params)
end end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Job, params) model_create_render(Job, params)
end end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Job, params) model_update_render(Job, params)
end end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Job, params) model_destory_render(Job, params)
end end
end end

View file

@ -57,10 +57,7 @@ class LongPollingController < ApplicationController
# check client id # check client id
client_id = client_id_verify client_id = client_id_verify
if !client_id raise Exceptions::UnprocessableEntity, 'Invalid client_id receive!' if !client_id
render json: { error: 'Invalid client_id receive!' }, status: :unprocessable_entity
return
end
# check queue to send # check queue to send
begin begin
@ -95,10 +92,7 @@ class LongPollingController < ApplicationController
end end
end end
rescue => e rescue => e
logger.error e.inspect raise Exceptions::UnprocessableEntity, 'Invalid client_id in receive loop!'
logger.error e.backtrace
render json: { error: 'Invalid client_id in receive loop!' }, status: :unprocessable_entity
return
end end
end end

View file

@ -5,7 +5,7 @@ class ObjectManagerAttributesController < ApplicationController
# GET /object_manager_attributes_list # GET /object_manager_attributes_list
def list def list
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
render json: { render json: {
objects: ObjectManager.list_frontend_objects, objects: ObjectManager.list_frontend_objects,
} }
@ -13,19 +13,19 @@ class ObjectManagerAttributesController < ApplicationController
# GET /object_manager_attributes # GET /object_manager_attributes
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
render json: ObjectManager::Attribute.list_full render json: ObjectManager::Attribute.list_full
end end
# GET /object_manager_attributes/1 # GET /object_manager_attributes/1
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(ObjectManager::Attribute, params) model_show_render(ObjectManager::Attribute, params)
end end
# POST /object_manager_attributes # POST /object_manager_attributes
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
check_params check_params
# check if attribute already exists # check if attribute already exists
@ -33,10 +33,7 @@ class ObjectManagerAttributesController < ApplicationController
object: params[:object], object: params[:object],
name: params[:name], name: params[:name],
) )
if exists raise Exceptions::UnprocessableEntity, 'already exists' if exists
render json: model_match_error('already exists'), status: :unprocessable_entity
return
end
begin begin
object_manager_attribute = ObjectManager::Attribute.add( object_manager_attribute = ObjectManager::Attribute.add(
@ -52,15 +49,13 @@ class ObjectManagerAttributesController < ApplicationController
) )
render json: object_manager_attribute.attributes_with_associations, status: :created render json: object_manager_attribute.attributes_with_associations, status: :created
rescue => e rescue => e
logger.error e.message raise Exceptions::UnprocessableEntity, e
logger.error e.backtrace.inspect
render json: model_match_error(e.message), status: :unprocessable_entity
end end
end end
# PUT /object_manager_attributes/1 # PUT /object_manager_attributes/1
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
check_params check_params
begin begin
object_manager_attribute = ObjectManager::Attribute.add( object_manager_attribute = ObjectManager::Attribute.add(
@ -76,15 +71,13 @@ class ObjectManagerAttributesController < ApplicationController
) )
render json: object_manager_attribute.attributes_with_associations, status: :ok render json: object_manager_attribute.attributes_with_associations, status: :ok
rescue => e rescue => e
logger.error e.message raise Exceptions::UnprocessableEntity, e
logger.error e.backtrace.inspect
render json: model_match_error(e.message), status: :unprocessable_entity
end end
end end
# DELETE /object_manager_attributes/1 # DELETE /object_manager_attributes/1
def destroy 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]) object_manager_attribute = ObjectManager::Attribute.find(params[:id])
ObjectManager::Attribute.remove( ObjectManager::Attribute.remove(
object_lookup_id: object_manager_attribute.object_lookup_id, object_lookup_id: object_manager_attribute.object_lookup_id,
@ -95,14 +88,14 @@ class ObjectManagerAttributesController < ApplicationController
# POST /object_manager_attributes_discard_changes # POST /object_manager_attributes_discard_changes
def 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 ObjectManager::Attribute.discard_changes
render json: {}, status: :ok render json: {}, status: :ok
end end
# POST /object_manager_attributes_execute_migrations # POST /object_manager_attributes_execute_migrations
def 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 ObjectManager::Attribute.migration_execute
render json: {}, status: :ok render json: {}, status: :ok
end end

View file

@ -116,10 +116,7 @@ curl http://localhost/api/v1/organizations/#{id} -v -u #{login}:#{password}
render json: {} render json: {}
return return
end end
if params[:id].to_i != current_user.organization_id raise Exceptions::NotAuthorized if params[:id].to_i != current_user.organization_id
response_access_deny
return
end
end end
if params[:expand] if params[:expand]
@ -163,7 +160,7 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password} -H "Conten
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_AGENT) deny_if_not_role(Z_ROLENAME_AGENT)
model_create_render(Organization, params) model_create_render(Organization, params)
end end
@ -194,7 +191,7 @@ curl http://localhost/api/v1/organizations -v -u #{login}:#{password} -H "Conten
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_AGENT) deny_if_not_role(Z_ROLENAME_AGENT)
model_update_render(Organization, params) model_update_render(Organization, params)
end end
@ -212,8 +209,8 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_AGENT) deny_if_not_role(Z_ROLENAME_AGENT)
return if model_references_check(Organization, params) model_references_check(Organization, params)
model_destory_render(Organization, params) model_destory_render(Organization, params)
end end
@ -221,8 +218,7 @@ curl http://localhost/api/v1/organization/{id} -v -u #{login}:#{password} -H "Co
def search def search
if role?(Z_ROLENAME_CUSTOMER) && !role?(Z_ROLENAME_ADMIN) && !role?(Z_ROLENAME_AGENT) if role?(Z_ROLENAME_CUSTOMER) && !role?(Z_ROLENAME_ADMIN) && !role?(Z_ROLENAME_AGENT)
response_access_deny raise Exceptions::NotAuthorized
return
end end
# set limit for pagination if needed # 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 # permission check
if !role?(Z_ROLENAME_ADMIN) && !role?(Z_ROLENAME_AGENT) if !role?(Z_ROLENAME_ADMIN) && !role?(Z_ROLENAME_AGENT)
response_access_deny raise Exceptions::NotAuthorized
return
end end
# get organization data # get organization data

View file

@ -52,7 +52,7 @@ curl http://localhost/api/v1/overviews.json -v -u #{login}:#{password}
=end =end
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(Overview, params) model_index_render(Overview, params)
end end
@ -74,7 +74,7 @@ curl http://localhost/api/v1/overviews/#{id}.json -v -u #{login}:#{password}
=end =end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Overview, params) model_show_render(Overview, params)
end end
@ -108,7 +108,7 @@ curl http://localhost/api/v1/overviews.json -v -u #{login}:#{password} -H "Conte
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Overview, params) model_create_render(Overview, params)
end end
@ -142,7 +142,7 @@ curl http://localhost/api/v1/overviews.json -v -u #{login}:#{password} -H "Conte
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Overview, params) model_update_render(Overview, params)
end end
@ -160,7 +160,7 @@ curl http://localhost/api/v1/overviews/#{id}.json -v -u #{login}:#{password} -H
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Overview, params) model_destory_render(Overview, params)
end end
end end

View file

@ -5,7 +5,7 @@ class PackagesController < ApplicationController
# GET /api/v1/packages # GET /api/v1/packages
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
packages = Package.all().order('name') packages = Package.all().order('name')
render json: { render json: {
packages: packages packages: packages
@ -14,7 +14,7 @@ class PackagesController < ApplicationController
# POST /api/v1/packages # POST /api/v1/packages
def install 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)
@ -23,7 +23,7 @@ class PackagesController < ApplicationController
# DELETE /api/v1/packages # DELETE /api/v1/packages
def uninstall 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])

View file

@ -54,7 +54,7 @@ curl http://localhost/api/v1/postmaster_filters.json -v -u #{login}:#{password}
=end =end
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(PostmasterFilter, params) model_index_render(PostmasterFilter, params)
end end
@ -76,7 +76,7 @@ curl http://localhost/api/v1/postmaster_filters/#{id}.json -v -u #{login}:#{pass
=end =end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(PostmasterFilter, params) model_show_render(PostmasterFilter, params)
end end
@ -121,7 +121,7 @@ curl http://localhost/api/v1/postmaster_filters.json -v -u #{login}:#{password}
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(PostmasterFilter, params) model_create_render(PostmasterFilter, params)
end end
@ -164,7 +164,7 @@ curl http://localhost/api/v1/postmaster_filters.json -v -u #{login}:#{password}
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(PostmasterFilter, params) model_update_render(PostmasterFilter, params)
end end
@ -179,7 +179,7 @@ Test:
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(PostmasterFilter, params) model_destory_render(PostmasterFilter, params)
end end
end end

View file

@ -7,7 +7,7 @@ class ReportsController < ApplicationController
# GET /api/reports/config # GET /api/reports/config
def reporting_config def reporting_config
return if deny_if_not_role('Report') deny_if_not_role('Report')
render json: { render json: {
config: Report.config, config: Report.config,
profiles: Report::Profile.list, profiles: Report::Profile.list,
@ -16,7 +16,7 @@ class ReportsController < ApplicationController
# GET /api/reports/generate # GET /api/reports/generate
def generate def generate
return if deny_if_not_role('Report') deny_if_not_role('Report')
get_params = params_all get_params = params_all
return if !get_params return if !get_params
@ -61,7 +61,7 @@ class ReportsController < ApplicationController
# GET /api/reports/sets # GET /api/reports/sets
def sets def sets
return if deny_if_not_role('Report') deny_if_not_role('Report')
get_params = params_all get_params = params_all
return if !get_params return if !get_params
@ -111,10 +111,7 @@ class ReportsController < ApplicationController
def params_all def params_all
profile = nil profile = nil
if !params[:profiles] && !params[:profile_id] if !params[:profiles] && !params[:profile_id]
render json: { raise Exceptions::UnprocessableEntity, 'No such profiles param'
error: 'No such profiles param',
}, status: :unprocessable_entity
return
end end
if params[:profile_id] if params[:profile_id]
profile = Report::Profile.find(params[:profile_id]) profile = Report::Profile.find(params[:profile_id])
@ -125,18 +122,12 @@ class ReportsController < ApplicationController
} }
end end
if !profile if !profile
render json: { raise Exceptions::UnprocessableEntity, 'No such active profile'
error: 'No such active profile',
}, status: :unprocessable_entity
return
end end
local_config = Report.config local_config = Report.config
if !local_config || !local_config[:metric] || !local_config[:metric][params[:metric].to_sym] if !local_config || !local_config[:metric] || !local_config[:metric][params[:metric].to_sym]
render json: { raise Exceptions::UnprocessableEntity, "No such metric #{params[:metric]}"
error: "No such metric #{params[:metric]}"
}, status: :unprocessable_entity
return
end end
metric = local_config[:metric][params[:metric].to_sym] metric = local_config[:metric][params[:metric].to_sym]

View file

@ -95,7 +95,7 @@ curl http://localhost/api/v1/roles.json -v -u #{login}:#{password} -H "Content-T
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Role, params) model_create_render(Role, params)
end end
@ -124,7 +124,7 @@ curl http://localhost/api/v1/roles.json -v -u #{login}:#{password} -H "Content-T
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Role, params) model_update_render(Role, params)
end end
@ -139,7 +139,7 @@ Test:
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Role, params) model_destory_render(Role, params)
end end
end end

View file

@ -20,10 +20,7 @@ curl http://localhost/api/v1/rss_fetch.json -v -u #{login}:#{password} -H "Conte
def fetch def fetch
items = Rss.fetch(params[:url], params[:limit]) items = Rss.fetch(params[:url], params[:limit])
if items.nil? raise Exceptions::UnprocessableEntity, "failed to fetch #{params[:url]}" if items.nil?
render json: { message: "failed to fetch #{params[:url]}", status: :unprocessable_entity }
return
end
render json: { items: items } render json: { items: items }
end end

View file

@ -15,10 +15,7 @@ class SessionsController < ApplicationController
return if check_maintenance(user) return if check_maintenance(user)
# auth failed # auth failed
if !user raise Exceptions::NotAuthorized, 'Wrong Username and Password combination.' if !user
render json: { error: 'Wrong Username and Password combination.' }, status: :unauthorized
return
end
# remember me - set session cookie to expire later # remember me - set session cookie to expire later
request.env['rack.session.options'][:expire_after] = if params[:remember_me] request.env['rack.session.options'][:expire_after] = if params[:remember_me]
@ -198,7 +195,7 @@ class SessionsController < ApplicationController
# "switch" to user # "switch" to user
def 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 # check user
if !params[:id] if !params[:id]
@ -280,7 +277,7 @@ class SessionsController < ApplicationController
end end
def list def list
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
assets = {} assets = {}
sessions_clean = [] sessions_clean = []
SessionHelper.list.each {|session| SessionHelper.list.each {|session|
@ -298,7 +295,7 @@ class SessionsController < ApplicationController
end end
def delete def delete
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
SessionHelper.destroy(params[:id]) SessionHelper.destroy(params[:id])
render json: {} render json: {}
end end

View file

@ -5,32 +5,32 @@ class SettingsController < ApplicationController
# GET /settings # GET /settings
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(Setting, params) model_index_render(Setting, params)
end end
# GET /settings/1 # GET /settings/1
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Setting, params) model_show_render(Setting, params)
end end
# POST /settings # POST /settings
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Setting, params) model_create_render(Setting, params)
end end
# PUT /settings/1 # PUT /settings/1
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
return if !check_access check_access
model_update_render(Setting, params) model_update_render(Setting, params)
end end
# PUT /settings/image/:id # PUT /settings/image/:id
def update_image def update_image
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
if !params[:logo] if !params[:logo]
render json: { render json: {
@ -82,8 +82,8 @@ class SettingsController < ApplicationController
# DELETE /settings/1 # DELETE /settings/1
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
return if !check_access check_access
model_destory_render(Setting, params) model_destory_render(Setting, params)
end end
@ -91,11 +91,8 @@ class SettingsController < ApplicationController
def check_access def check_access
return true if !Setting.get('system_online_service') return true if !Setting.get('system_online_service')
setting = Setting.find(params[:id]) setting = Setting.find(params[:id])
return true if setting.preferences && !setting.preferences[:online_service_disable] return true if setting.preferences && !setting.preferences[:online_service_disable]
raise Exceptions::NotAuthorized
response_access_deny
false
end end
end end

View file

@ -96,7 +96,7 @@ curl http://localhost/api/v1/signatures.json -v -u #{login}:#{password} -H "Cont
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Signature, params) model_create_render(Signature, params)
end end
@ -125,7 +125,7 @@ curl http://localhost/api/v1/signatures.json -v -u #{login}:#{password} -H "Cont
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Signature, params) model_update_render(Signature, params)
end end
@ -140,7 +140,7 @@ Test:
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Signature, params) model_destory_render(Signature, params)
end end
end end

View file

@ -47,7 +47,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password}
=end =end
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
if params[:full] if params[:full]
@ -92,7 +92,7 @@ curl http://localhost/api/v1/slas/#{id}.json -v -u #{login}:#{password}
=end =end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Sla, params) model_show_render(Sla, params)
end end
@ -121,7 +121,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} -H "Content-Ty
=end =end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Sla, params) model_create_render(Sla, params)
end end
@ -150,7 +150,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} -H "Content-Ty
=end =end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Sla, params) model_update_render(Sla, params)
end end
@ -168,7 +168,7 @@ curl http://localhost/api/v1/slas.json -v -u #{login}:#{password} -H "Content-Ty
=end =end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Sla, params) model_destory_render(Sla, params)
end end
end end

View file

@ -75,14 +75,14 @@ class TagsController < ApplicationController
# POST /api/v1/tag_list # POST /api/v1/tag_list
def admin_create def admin_create
return if deny_if_not_role('Admin') deny_if_not_role('Admin')
Tag::Item.lookup_by_name_and_create(params[:name]) Tag::Item.lookup_by_name_and_create(params[:name])
render json: {} render json: {}
end end
# PUT /api/v1/tag_list/:id # PUT /api/v1/tag_list/:id
def admin_rename def admin_rename
return if deny_if_not_role('Admin') deny_if_not_role('Admin')
Tag::Item.rename( Tag::Item.rename(
id: params[:id], id: params[:id],
name: params[:name], name: params[:name],
@ -92,7 +92,7 @@ class TagsController < ApplicationController
# DELETE /api/v1/tag_list/:id # DELETE /api/v1/tag_list/:id
def admin_delete def admin_delete
return if deny_if_not_role('Admin') deny_if_not_role('Admin')
Tag::Item.remove(params[:id]) Tag::Item.remove(params[:id])
render json: {} render json: {}
end end

View file

@ -12,7 +12,7 @@ class TaskbarController < ApplicationController
def show def show
taskbar = Taskbar.find(params[:id]) taskbar = Taskbar.find(params[:id])
return if !access(taskbar) access(taskbar)
model_show_render_item(taskbar) model_show_render_item(taskbar)
end end
@ -23,7 +23,7 @@ class TaskbarController < ApplicationController
def update def update
taskbar = Taskbar.find(params[:id]) taskbar = Taskbar.find(params[:id])
return if !access(taskbar) access(taskbar)
taskbar.update_attributes!(Taskbar.param_cleanup(params)) taskbar.update_attributes!(Taskbar.param_cleanup(params))
model_update_render_item(taskbar) model_update_render_item(taskbar)
@ -31,7 +31,7 @@ class TaskbarController < ApplicationController
def destroy def destroy
taskbar = Taskbar.find(params[:id]) taskbar = Taskbar.find(params[:id])
return if !access(taskbar) access(taskbar)
taskbar.destroy taskbar.destroy
model_destory_render_item() model_destory_render_item()
@ -40,10 +40,6 @@ class TaskbarController < ApplicationController
private private
def access(taskbar) def access(taskbar)
if taskbar.user_id != current_user.id raise Exceptions::UnprocessableEntity, 'Not allowed to access this task.' if taskbar.user_id != current_user.id
render json: { error: 'Not allowed to access this task.' }, status: :unprocessable_entity
return false
end
true
end end
end end

View file

@ -47,7 +47,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password}
=end =end
def index def index
return if deny_if_not_role('Agent') deny_if_not_role('Agent')
model_index_render(Template, params) model_index_render(Template, params)
end end
@ -69,7 +69,7 @@ curl http://localhost/api/v1/templates/#{id}.json -v -u #{login}:#{password}
=end =end
def show def show
return if deny_if_not_role('Agent') deny_if_not_role('Agent')
model_show_render(Template, params) model_show_render(Template, params)
end end
@ -97,7 +97,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password} -H "Conte
=end =end
def create def create
return if deny_if_not_role('Agent') deny_if_not_role('Agent')
model_create_render(Template, params) model_create_render(Template, params)
end end
@ -125,7 +125,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password} -H "Conte
=end =end
def update def update
return if deny_if_not_role('Agent') deny_if_not_role('Agent')
model_update_render(Template, params) model_update_render(Template, params)
end end
@ -143,7 +143,7 @@ curl http://localhost/api/v1/templates.json -v -u #{login}:#{password} -H "Conte
=end =end
def destroy def destroy
return if deny_if_not_role('Agent') deny_if_not_role('Agent')
model_destory_render(Template, params) model_destory_render(Template, params)
end end
end end

View file

@ -9,4 +9,29 @@ class TestsController < ApplicationController
render json: result render json: result
end 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 end

View file

@ -5,7 +5,7 @@ class TicketArticlesController < ApplicationController
# GET /articles # GET /articles
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(Ticket::Article, params) model_index_render(Ticket::Article, params)
end end
@ -14,7 +14,7 @@ class TicketArticlesController < ApplicationController
# permission check # permission check
article = Ticket::Article.find(params[:id]) article = Ticket::Article.find(params[:id])
return if !article_permission(article) article_permission(article)
if params[:expand] if params[:expand]
result = article.attributes_with_relation_names result = article.attributes_with_relation_names
@ -40,7 +40,7 @@ class TicketArticlesController < ApplicationController
# permission check # permission check
ticket = Ticket.find(params[:id]) ticket = Ticket.find(params[:id])
return if !ticket_permission(ticket) ticket_permission(ticket)
articles = [] articles = []
@ -98,7 +98,7 @@ class TicketArticlesController < ApplicationController
article = Ticket::Article.new(clean_params) article = Ticket::Article.new(clean_params)
# permission check # permission check
return if !article_permission(article) article_permission(article)
# find attachments in upload cache # find attachments in upload cache
if form_id if form_id
@ -127,7 +127,7 @@ class TicketArticlesController < ApplicationController
# permission check # permission check
article = Ticket::Article.find(params[:id]) 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_association_lookup(params)
clean_params = Ticket::Article.param_cleanup(clean_params, true) clean_params = Ticket::Article.param_cleanup(clean_params, true)
@ -142,7 +142,7 @@ class TicketArticlesController < ApplicationController
# DELETE /articles/1 # DELETE /articles/1
def destroy def destroy
article = Ticket::Article.find(params[:id]) article = Ticket::Article.find(params[:id])
return if !article_permission(article) article_permission(article)
article.destroy article.destroy
head :ok head :ok
@ -211,13 +211,11 @@ class TicketArticlesController < ApplicationController
# permission check # permission check
ticket = Ticket.lookup(id: params[:ticket_id]) ticket = Ticket.lookup(id: params[:ticket_id])
if !ticket_permission(ticket) if !ticket_permission(ticket)
render json: 'No such ticket.', status: :unauthorized raise Exceptions::NotAuthorized, 'No such ticket.'
return
end end
article = Ticket::Article.find(params[:article_id]) article = Ticket::Article.find(params[:article_id])
if ticket.id != article.ticket_id if ticket.id != article.ticket_id
render json: 'No access, article_id/ticket_id is not matching.', status: :unauthorized raise Exceptions::NotAuthorized, 'No access, article_id/ticket_id is not matching.'
return
end end
list = article.attachments || [] list = article.attachments || []
@ -227,10 +225,7 @@ class TicketArticlesController < ApplicationController
access = true access = true
end end
} }
if !access raise Exceptions::NotAuthorized, 'Requested file id is not linked with article_id.' if !access
render json: 'Requested file id is not linked with article_id.', status: :unauthorized
return
end
# find file # find file
file = Store.find(params[:id]) file = Store.find(params[:id])
@ -247,7 +242,7 @@ class TicketArticlesController < ApplicationController
# permission check # permission check
article = Ticket::Article.find(params[:id]) article = Ticket::Article.find(params[:id])
return if !article_permission(article) article_permission(article)
list = Store.list( list = Store.list(
object: 'Ticket::Article::Mail', object: 'Ticket::Article::Mail',

View file

@ -15,20 +15,20 @@ class TicketPrioritiesController < ApplicationController
# POST /ticket_priorities # POST /ticket_priorities
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Ticket::Priority, params) model_create_render(Ticket::Priority, params)
end end
# PUT /ticket_priorities/1 # PUT /ticket_priorities/1
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Ticket::Priority, params) model_update_render(Ticket::Priority, params)
end end
# DELETE /ticket_priorities/1 # DELETE /ticket_priorities/1
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
return if model_references_check(Ticket::Priority, params) model_references_check(Ticket::Priority, params)
model_destory_render(Ticket::Priority, params) model_destory_render(Ticket::Priority, params)
end end
end end

View file

@ -15,19 +15,19 @@ class TicketStatesController < ApplicationController
# POST /ticket_states # POST /ticket_states
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Ticket::State, params) model_create_render(Ticket::State, params)
end end
# PUT /ticket_states/1 # PUT /ticket_states/1
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Ticket::State, params) model_update_render(Ticket::State, params)
end end
# DELETE /ticket_states/1 # DELETE /ticket_states/1
def destroy 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) return if model_references_check(Ticket::State, params)
model_destory_render(Ticket::State, params) model_destory_render(Ticket::State, params)
end end

View file

@ -47,7 +47,7 @@ class TicketsController < ApplicationController
# permission check # permission check
ticket = Ticket.find(params[:id]) ticket = Ticket.find(params[:id])
return if !ticket_permission(ticket) ticket_permission(ticket)
if params[:expand] if params[:expand]
result = ticket.attributes_with_relation_names result = ticket.attributes_with_relation_names
@ -119,7 +119,7 @@ class TicketsController < ApplicationController
# permission check # permission check
ticket = Ticket.find(params[:id]) ticket = Ticket.find(params[:id])
return if !ticket_permission(ticket) ticket_permission(ticket)
clean_params = Ticket.param_association_lookup(params) clean_params = Ticket.param_association_lookup(params)
clean_params = Ticket.param_cleanup(clean_params, true) clean_params = Ticket.param_cleanup(clean_params, true)
@ -147,7 +147,7 @@ class TicketsController < ApplicationController
# permission check # permission check
ticket = Ticket.find(params[:id]) ticket = Ticket.find(params[:id])
return if !ticket_permission(ticket) ticket_permission(ticket)
ticket.destroy ticket.destroy
@ -173,7 +173,7 @@ class TicketsController < ApplicationController
ticket = Ticket.find(params[:id]) ticket = Ticket.find(params[:id])
# permission check # permission check
return if !ticket_permission(ticket) ticket_permission(ticket)
# get history of ticket # get history of ticket
history = ticket.history_get(true) history = ticket.history_get(true)
@ -251,7 +251,7 @@ class TicketsController < ApplicationController
end end
# permission check # permission check
return if !ticket_permission(ticket_master) ticket_permission(ticket_master)
# check slave ticket # check slave ticket
ticket_slave = Ticket.find_by(id: params[:slave_ticket_id]) ticket_slave = Ticket.find_by(id: params[:slave_ticket_id])
@ -264,7 +264,7 @@ class TicketsController < ApplicationController
end end
# permission check # permission check
return if !ticket_permission(ticket_slave) ticket_permission(ticket_slave)
# check diffetent ticket ids # check diffetent ticket ids
if ticket_slave.id == ticket_master.id if ticket_slave.id == ticket_master.id
@ -294,7 +294,7 @@ class TicketsController < ApplicationController
# permission check # permission check
ticket = Ticket.find(params[:ticket_id]) ticket = Ticket.find(params[:ticket_id])
return if !ticket_permission(ticket) ticket_permission(ticket)
assets = ticket.assets({}) assets = ticket.assets({})
# get related articles # get related articles
@ -356,7 +356,7 @@ class TicketsController < ApplicationController
# GET /api/v1/tickets/selector # GET /api/v1/tickets/selector
def 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) ticket_count, tickets = Ticket.selectors(params[:condition], 6)
@ -385,7 +385,7 @@ class TicketsController < ApplicationController
end end
# permission check # permission check
#return if !ticket_permission(ticket) #ticket_permission(ticket)
# lookup open user tickets # lookup open user tickets
limit = 100 limit = 100

View file

@ -10,7 +10,7 @@ class TranslationsController < ApplicationController
# PUT /translations/push # PUT /translations/push
def push def push
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
start = Time.zone.now start = Time.zone.now
Translation.push(params[:locale]) Translation.push(params[:locale])
if start > Time.zone.now - 5.seconds if start > Time.zone.now - 5.seconds
@ -21,51 +21,51 @@ class TranslationsController < ApplicationController
# POST /translations/sync/:locale # POST /translations/sync/:locale
def sync def sync
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
Translation.load(params[:locale]) Translation.load(params[:locale])
render json: { message: 'ok' }, status: :ok render json: { message: 'ok' }, status: :ok
end end
# POST /translations/reset # POST /translations/reset
def reset def reset
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
Translation.reset(params[:locale]) Translation.reset(params[:locale])
render json: { message: 'ok' }, status: :ok render json: { message: 'ok' }, status: :ok
end end
# GET /translations/admin/lang/:locale # GET /translations/admin/lang/:locale
def admin 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) render json: Translation.lang(params[:locale], true)
end end
# GET /translations # GET /translations
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(Translation, params) model_index_render(Translation, params)
end end
# GET /translations/1 # GET /translations/1
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Translation, params) model_show_render(Translation, params)
end end
# POST /translations # POST /translations
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Translation, params) model_create_render(Translation, params)
end end
# PUT /translations/1 # PUT /translations/1
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Translation, params) model_update_render(Translation, params)
end end
# DELETE /translations/1 # DELETE /translations/1
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Translation, params) model_destory_render(Translation, params)
end end
end end

View file

@ -4,27 +4,27 @@ class TriggersController < ApplicationController
before_action :authentication_check before_action :authentication_check
def index def index
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_index_render(Trigger, params) model_index_render(Trigger, params)
end end
def show def show
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_show_render(Trigger, params) model_show_render(Trigger, params)
end end
def create def create
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_create_render(Trigger, params) model_create_render(Trigger, params)
end end
def update def update
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_update_render(Trigger, params) model_update_render(Trigger, params)
end end
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
model_destory_render(Trigger, params) model_destory_render(Trigger, params)
end end
end end

View file

@ -110,8 +110,6 @@ class UsersController < ApplicationController
user = User.new(clean_params) user = User.new(clean_params)
user.param_set_associations(params) user.param_set_associations(params)
begin
# check if it's first user, tje admin user # check if it's first user, tje admin user
# inital admin account # inital admin account
count = User.all.count() count = User.all.count()
@ -125,14 +123,12 @@ class UsersController < ApplicationController
# check if feature is enabled # check if feature is enabled
if admin_account_exists && !Setting.get('user_create_account') if admin_account_exists && !Setting.get('user_create_account')
render json: { error: 'Feature not enabled!' }, status: :unprocessable_entity raise Exceptions::UnprocessableEntity, 'Feature not enabled!'
return
end end
# check signup option only after admin account is created # check signup option only after admin account is created
if admin_account_exists && !params[:signup] if admin_account_exists && !params[:signup]
render json: { error: 'Only signup with not authenticate user possible!' }, status: :unprocessable_entity raise Exceptions::UnprocessableEntity, 'Only signup with not authenticate user possible!'
return
end end
user.updated_by_id = 1 user.updated_by_id = 1
user.created_by_id = 1 user.created_by_id = 1
@ -165,7 +161,7 @@ class UsersController < ApplicationController
else else
# permission check by role # permission check by role
return if !permission_check_by_role(params) permission_check_by_role(params)
if params[:role_ids] if params[:role_ids]
user.role_ids = params[:role_ids] user.role_ids = params[:role_ids]
@ -178,10 +174,7 @@ class UsersController < ApplicationController
# check if user already exists # check if user already exists
if user.email if user.email
exists = User.where(email: user.email.downcase).first exists = User.where(email: user.email.downcase).first
if exists raise Exceptions::UnprocessableEntity, 'User already exists!' if exists
render json: { error: 'User already exists!' }, status: :unprocessable_entity
return
end
end end
user.save! user.save!
@ -228,9 +221,6 @@ class UsersController < ApplicationController
user_new = User.find(user.id).attributes_with_associations user_new = User.find(user.id).attributes_with_associations
user_new.delete('password') user_new.delete('password')
render json: user_new, status: :created render json: user_new, status: :created
rescue => e
render json: model_match_error(e.message), status: :unprocessable_entity
end
end end
# @path [PUT] /users/{id} # @path [PUT] /users/{id}
@ -252,10 +242,8 @@ class UsersController < ApplicationController
clean_params = User.param_association_lookup(params) clean_params = User.param_association_lookup(params)
clean_params = User.param_cleanup(clean_params, true) clean_params = User.param_cleanup(clean_params, true)
begin
# permission check by role # permission check by role
return if !permission_check_by_role(params) permission_check_by_role(params)
user.update_attributes(clean_params) user.update_attributes(clean_params)
# only allow Admin's and Agent's # only allow Admin's and Agent's
@ -285,9 +273,6 @@ class UsersController < ApplicationController
user_new = User.find(user.id).attributes_with_associations user_new = User.find(user.id).attributes_with_associations
user_new.delete('password') user_new.delete('password')
render json: user_new, status: :ok render json: user_new, status: :ok
rescue => e
render json: { error: e.message }, status: :unprocessable_entity
end
end end
# @path [DELETE] /users/{id} # @path [DELETE] /users/{id}
@ -300,8 +285,8 @@ class UsersController < ApplicationController
# @response_message 200 User successfully deleted. # @response_message 200 User successfully deleted.
# @response_message 401 Invalid session. # @response_message 401 Invalid session.
def destroy def destroy
return if deny_if_not_role(Z_ROLENAME_ADMIN) deny_if_not_role(Z_ROLENAME_ADMIN)
return if model_references_check(User, params) model_references_check(User, params)
model_destory_render(User, params) model_destory_render(User, params)
end end
@ -507,16 +492,10 @@ curl http://localhost/api/v1/users/email_verify.json -v -u #{login}:#{password}
=end =end
def email_verify def email_verify
if !params[:token] raise Exceptions::UnprocessableEntity, 'No token!' if !params[:token]
render json: { message: 'No token!' }, status: :unprocessable_entity
return
end
user = User.signup_verify_via_token(params[:token], current_user) user = User.signup_verify_via_token(params[:token], current_user)
if !user raise Exceptions::UnprocessableEntity, 'Invalid token!' if !user
render json: { message: 'Invalid token!' }, status: :unprocessable_entity
return
end
render json: { message: 'ok', user_email: user.email }, status: :ok render json: { message: 'ok', user_email: user.email }, status: :ok
end end
@ -543,17 +522,11 @@ curl http://localhost/api/v1/users/email_verify_send.json -v -u #{login}:#{passw
def email_verify_send def email_verify_send
if !params[:email] raise Exceptions::UnprocessableEntity, 'No email!' if !params[:email]
render json: { message: 'No email!' }, status: :unprocessable_entity
return
end
# check is verify is possible to send # check is verify is possible to send
user = User.find_by(email: params[:email].downcase) user = User.find_by(email: params[:email].downcase)
if !user raise Exceptions::UnprocessableEntity, 'No such user!' if !user
render json: { error: 'No such user!' }, status: :unprocessable_entity
return
end
#if user.verified == true #if user.verified == true
# render json: { error: 'Already verified!' }, status: :unprocessable_entity # 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 def password_reset_send
# check if feature is enabled # check if feature is enabled
if !Setting.get('user_lost_password') raise Exceptions::UnprocessableEntity, 'Feature not enabled!' if !Setting.get('user_lost_password')
render json: { error: 'Feature not enabled!' }, status: :unprocessable_entity
return
end
result = User.password_reset_new_token(params[:username]) result = User.password_reset_new_token(params[:username])
if result && result[:token] if result && result[:token]
@ -779,10 +749,8 @@ curl http://localhost/api/v1/users/preferences.json -v -u #{login}:#{password} -
=end =end
def preferences def preferences
if !current_user raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
render json: { message: 'No current user!' }, status: :unprocessable_entity
return
end
if params[:user] if params[:user]
user = User.find(current_user.id) user = User.find(current_user.id)
params[:user].each {|key, value| params[:user].each {|key, value|
@ -815,20 +783,11 @@ curl http://localhost/api/v1/users/account.json -v -u #{login}:#{password} -H "C
=end =end
def account_remove def account_remove
if !current_user raise Exceptions::UnprocessableEntity, 'No current user!' if !current_user
render json: { message: 'No current user!' }, status: :unprocessable_entity
return
end
# provider + uid to remove # provider + uid to remove
if !params[:provider] raise Exceptions::UnprocessableEntity, 'provider needed!' if !params[:provider]
render json: { message: 'provider needed!' }, status: :unprocessable_entity raise Exceptions::UnprocessableEntity, 'uid needed!' if !params[:uid]
return
end
if !params[:uid]
render json: { message: 'uid needed!' }, status: :unprocessable_entity
return
end
# remove from database # remove from database
record = Authorization.where( record = Authorization.where(
@ -836,10 +795,8 @@ curl http://localhost/api/v1/users/account.json -v -u #{login}:#{password} -H "C
provider: params[:provider], provider: params[:provider],
uid: params[:uid], uid: params[:uid],
) )
if !record.first raise Exceptions::UnprocessableEntity, 'No record found!' if !record.first
render json: { message: 'No record found!' }, status: :unprocessable_entity
return
end
record.destroy_all record.destroy_all
render json: { message: 'ok' }, status: :ok render json: { message: 'ok' }, status: :ok
end end
@ -938,10 +895,7 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content
return if !valid_session_with_user return if !valid_session_with_user
# get & validate image # get & validate image
if !params[:id] raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id]
render json: { message: 'No id of avatar!' }, status: :unprocessable_entity
return
end
# set as default # set as default
avatar = Avatar.set_default('User', current_user.id, params[:id]) 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 return if !valid_session_with_user
# get & validate image # get & validate image
if !params[:id] raise Exceptions::UnprocessableEntity, 'No id of avatar!' if !params[:id]
render json: { message: 'No id of avatar!' }, status: :unprocessable_entity
return
end
# remove avatar # remove avatar
Avatar.remove_one('User', current_user.id, params[:id]) 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| params[:role_ids].each {|role_id|
role_local = Role.lookup(id: role_id) role_local = Role.lookup(id: role_id)
if !role_local 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}" 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 end
role_name = role_local.name role_name = role_local.name
next if role_name != 'Admin' && role_name != 'Agent' 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}" 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 end
@ -1023,9 +972,8 @@ curl http://localhost/api/v1/users/avatar -v -u #{login}:#{password} -H "Content
params[:group_ids] = [params[:group_ids]] params[:group_ids] = [params[:group_ids]]
end end
if !params[:group_ids].empty? 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}" 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
end end

View file

@ -18,4 +18,6 @@ Rails.application.routes.draw do
end end
} }
match '*a', to: 'errors#routing', via: [:get, :post, :put, :delete]
end end

View file

@ -16,5 +16,10 @@ Zammad::Application.routes.draw do
match '/tests_html_utils', to: 'tests#html_utils', via: :get match '/tests_html_utils', to: 'tests#html_utils', via: :get
match '/tests_taskbar', to: 'tests#taskbar', via: :get match '/tests_taskbar', to: 'tests#taskbar', via: :get
match '/tests/wait/:sec', to: 'tests#wait', 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 end

6
lib/exceptions.rb Normal file
View file

@ -0,0 +1,6 @@
module Exceptions
class NotAuthorized < StandardError; end
class UnprocessableEntity < StandardError; end
end

21
public/401.html Normal file
View file

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html class="dark">
<meta charset="utf-8">
<title>401: Unauthorized</title>
<link rel="stylesheet" href="/assets/error/style.css">
<body <% if @traceback %>class="error-message"<% end %>>
<h1>401: Unauthorized</h1>
<% if !@traceback %>
<div class="error-image" style="background-image: url(/assets/error/error-1.svg)"></div>
<p>Sorry, but you're not allowed to access this page. If you're registered please log in and refresh this page.</p>
<% else %>
<div><%= @exception.message %></div>
<% if @exception.backtrace %>
<div>Traceback:</div>
<% @exception.backtrace.each {|row| %>
<%= row %><br>
<% } %>
<% end %>
<% end %>
</body>
</html>

View file

@ -3,8 +3,19 @@
<meta charset="utf-8"> <meta charset="utf-8">
<title>404: Not Found</title> <title>404: Not Found</title>
<link rel="stylesheet" href="/assets/error/style.css"> <link rel="stylesheet" href="/assets/error/style.css">
<body <% if @traceback %>class="error-message"<% end %>>
<h1>404: Requested Page was not found.</h1> <h1>404: Requested Ressource was not found.</h1>
<% if !@traceback %>
<div class="error-image" style="background-image: url(/assets/error/error-2.svg)"></div> <div class="error-image" style="background-image: url(/assets/error/error-2.svg)"></div>
<p>Sorry, but the Phoenix is not able to find your page. Try checking the URL for errors.</p> <p>Sorry, but the Phoenix is not able to find your ressource. Try checking the URL for errors.</p>
<% else %>
<div><%= @exception.message %></div>
<% if @exception.backtrace %>
<div>Traceback:</div>
<% @exception.backtrace.each {|row| %>
<%= row %><br>
<% } %>
<% end %>
<% end %>
</body>
</html> </html>

View file

@ -1,10 +1,20 @@
<!DOCTYPE html> <!DOCTYPE html>
<html class="dark"> <html class="dark">
<meta charset="utf-8"> <meta charset="utf-8">
<title>422: Not Found</title> <title>422: Unprocessable Entity</title>
<link rel="stylesheet" href="/assets/error/style.css"> <link rel="stylesheet" href="/assets/error/style.css">
<body <% if @traceback %>class="error-message"<% end %>>
<h1>422: The change you wanted was rejected.</h1> <h1>422: The change you wanted was rejected.</h1>
<% if !@traceback %>
<div class="error-image" style="background-image: url(/assets/error/error-1.svg)"></div> <div class="error-image" style="background-image: url(/assets/error/error-1.svg)"></div>
<p>Maybe you tried to change something you didn't have access to.</p> <p>Maybe you tried to change something you didn't have access to.</p>
<% else %>
<div><%= @exception.message %></div>
<% if @exception.backtrace %>
<div>Traceback:</div>
<% @exception.backtrace.each {|row| %>
<%= row %><br>
<% } %>
<% end %>
<% end %>
</html> </html>

View file

@ -3,8 +3,19 @@
<meta charset="utf-8"> <meta charset="utf-8">
<title>500: Something went wrong</title> <title>500: Something went wrong</title>
<link rel="stylesheet" href="/assets/error/style.css"> <link rel="stylesheet" href="/assets/error/style.css">
<body <% if @traceback %>class="error-message"<% end %>>
<h1>500: We're sorry, but something went wrong.</h1> <h1>500: We're sorry, but something went wrong.</h1>
<% if !@traceback %>
<div class="error-image" style="background-image: url(/assets/error/error-2.svg)"></div> <div class="error-image" style="background-image: url(/assets/error/error-2.svg)"></div>
<p>We're sorry, but something went wrong.</p> <p>We're sorry, but something went wrong.</p>
<% else %>
<div><%= @exception.message %></div>
<% if @exception.backtrace %>
<div>Traceback:</div>
<% @exception.backtrace.each {|row| %>
<%= row %><br>
<% } %>
<% end %>
<% end %>
</body>
</html> </html>

View file

@ -43,6 +43,10 @@ body {
overflow-x: hidden; overflow-x: hidden;
} }
body.error-message {
height: auto;
}
h1 { h1 {
margin: 0; margin: 0;
color: #444a4f; color: #444a4f;

View file

@ -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(/<html/, @response.body)
assert_match(%r{<title>404: Not Found</title>}, @response.body)
assert_match(%r{<h1>404: Requested Ressource was not found.</h1>}, @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(/<html/, @response.body)
assert_match(%r{<title>401: Unauthorized</title>}, @response.body)
assert_match(%r{<h1>401: Unauthorized</h1>}, @response.body)
assert_match(/authentication failed/, @response.body)
# 422
get '/tests/unprocessable_entity', {}, @headers
assert_response(422)
assert_match(/<html/, @response.body)
assert_match(%r{<title>422: Unprocessable Entity</title>}, @response.body)
assert_match(%r{<h1>422: The change you wanted was rejected.</h1>}, @response.body)
assert_match(/some error message/, @response.body)
# 401
get '/tests/not_authorized', {}, @headers
assert_response(401)
assert_match(/<html/, @response.body)
assert_match(%r{<title>401: Unauthorized</title>}, @response.body)
assert_match(%r{<h1>401: Unauthorized</h1>}, @response.body)
assert_match(/some error message/, @response.body)
# 401
get '/tests/ar_not_found', {}, @headers
assert_response(404)
assert_match(/<html/, @response.body)
assert_match(%r{<title>404: Not Found</title>}, @response.body)
assert_match(%r{<h1>404: Requested Ressource was not found.</h1>}, @response.body)
assert_match(/some error message/, @response.body)
# 500
get '/tests/standard_error', {}, @headers
assert_response(500)
assert_match(/<html/, @response.body)
assert_match(%r{<title>500: Something went wrong</title>}, @response.body)
assert_match(%r{<h1>500: We're sorry, but something went wrong.</h1>}, @response.body)
assert_match(/some error message/, @response.body)
# 422
get '/tests/argument_error', {}, @headers
assert_response(422)
assert_match(/<html/, @response.body)
assert_match(%r{<title>422: Unprocessable Entity</title>}, @response.body)
assert_match(%r{<h1>422: The change you wanted was rejected.</h1>}, @response.body)
assert_match(/some error message/, @response.body)
end
end

View file

@ -53,7 +53,7 @@ class PackagesControllerTest < ActionDispatch::IntegrationTest
test 'packages index with nobody' do test 'packages index with nobody' do
# index # index
get '/api/v1/packages' get '/api/v1/packages', {}, @headers
assert_response(401) assert_response(401)
result = JSON.parse(@response.body) result = JSON.parse(@response.body)
assert_equal(result.class, Hash) assert_equal(result.class, Hash)

View file

@ -53,7 +53,7 @@ class SettingsControllerTest < ActionDispatch::IntegrationTest
test 'settings index with nobody' do test 'settings index with nobody' do
# index # index
get '/api/v1/settings' get '/api/v1/settings', {}, @headers
assert_response(401) assert_response(401)
result = JSON.parse(@response.body) result = JSON.parse(@response.body)
assert_equal(result.class, Hash) assert_equal(result.class, Hash)

View file

@ -217,7 +217,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest
assert_equal(result.class, Hash) assert_equal(result.class, Hash)
assert_equal(result['email'], 'rest-agent@example.com') 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) assert_response(200)
result = JSON.parse(@response.body) result = JSON.parse(@response.body)
assert(result) assert(result)
@ -320,7 +320,7 @@ class UserOrganizationControllerTest < ActionDispatch::IntegrationTest
assert_response(401) assert_response(401)
result = JSON.parse(@response.body) result = JSON.parse(@response.body)
assert_equal(result.class, Hash) assert_equal(result.class, Hash)
assert(result.empty?) assert(result['error'])
# create user with admin role # create user with admin role
role = Role.lookup(name: 'Admin') 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) get "/api/v1/users/#{@customer_without_org.id}", {}, @headers.merge('Authorization' => credentials)
assert_response(401) assert_response(401)
#puts @response.body
result = JSON.parse(@response.body) result = JSON.parse(@response.body)
assert_equal(result.class, Hash) assert_equal(result.class, Hash)
assert(result.empty?) assert(result['error'])
end end