67 lines
2.6 KiB
Ruby
67 lines
2.6 KiB
Ruby
module Suppliers
|
|
class ApplicationController < ::ApplicationController
|
|
before_action :setup_employee_and_supplier!
|
|
#load_and_authorize_resource
|
|
if Rails.env.development?
|
|
skip_before_action :setup_employee_and_supplier!, only: :employee_and_supplier
|
|
end
|
|
attr_reader :current_supplier
|
|
helper_method :current_supplier
|
|
layout 'supplier/app'
|
|
|
|
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: {errors: "403 Forbidden", ok: false}, status: :forbidden }
|
|
end
|
|
end
|
|
|
|
# GET
|
|
#NOTE: temporary solution for development, if I am in production something is wrong
|
|
def employee_and_supplier
|
|
employee = current_employee || Employee.find_by_email('bterkuile@gmail.com')
|
|
raise CanCan::AccessDenied unless employee.present?
|
|
supplier = current_supplier || employee.suppliers.first
|
|
employee.enrich_with_settings supplier.settings_for(employee)
|
|
FlatKeys.as_nested_structure(Supplier::PRELOAD_INCLUDES).last.each do |relation_name, includes|
|
|
relation_result = supplier.public_send(relation_name)
|
|
relation_result.include_relations(includes) if relation_result.is_a?(Array)
|
|
end
|
|
render json: {
|
|
employee: JSONAPI::Serializer.serialize(employee, serializer: Suppliers::EmployeeSerializer),
|
|
supplier: JSONAPI::Serializer.serialize(supplier, serializer: Suppliers::SupplierSerializer, include: Supplier::PRELOAD_INCLUDES),
|
|
auth_token: employee.authentication_token,
|
|
}
|
|
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 = Suppliers::Ability.new( current_employee )
|
|
run_after_authentication_hooks!
|
|
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
|