Files
mozo-backend/app/controllers/suppliers/application_controller.rb
T
2015-02-27 11:09:16 +01:00

55 lines
1.8 KiB
Ruby

module Suppliers
class ApplicationController < ::ApplicationController
before_action :setup_employee_and_supplier!
load_and_authorize_resource
attr_reader :current_supplier
helper_method :current_supplier
layout 'supplier/app'
class_attribute :after_authentication_hooks
rescue_from 'RestClient::Conflict' do |e|
#binding.pry
end
rescue_from CanCan::AccessDenied do |exception|
respond_to do |format|
format.html { redirect_to root_path, alert: 'Action forbidden'}
format.json { render json: {}, status: :forbidden }
end
end
def self.after_authentication(options, &blk)
self.after_authentication_hooks ||= []
after_authentication_hooks << {options: options, block: blk}
end
def setup_employee_and_supplier!
authenticate_employee!
find_current_supplier!
return unless current_supplier.present?
current_employee.enrich_with_settings current_supplier.settings_for(current_employee)
raise CanCan::AccessDenied unless current_employee.active?
@current_ability = ::Ability.new( current_employee )
Array.wrap(after_authentication_hooks).each do |hook|
next if hook[:options][:only].present? && !Array.wrap(hook[:options][:only]).include?(action_name.to_sym)
instance_eval &hook[:block]
end
end
def find_current_supplier!
return current_supplier if current_supplier.present?
if session[:supplier_id]
supplier = Supplier.find(session[:supplier_id])
if supplier.employee_ids.include?(current_employee.id)
@current_supplier = supplier
else
render nothing: true, status: :unauthorized
end
else
@current_supplier = current_employee.suppliers.first
session[:supplier_id] = @current_supplier.try(:id)
end
end
end
end