module Comee module Core class ApplicationController < ActionController::API include Pagination before_action :authenticate def render_content(data, options = {}) result = {success: true} if params[:page] total = data.count data = data.then(&paginate) result[:page] = params[:page].to_i result[:total] = total end result[:data] = if options.key?(:fields) && options.key?(:serializer) serialize(data, {include: options[:fields], serializer: options[:serializer]}) elsif options.key?(:fields) && options.key?(:each_serializer) serialize(data, {include: options[:fields], each_serializer: options[:each_serializer]}) elsif options.key?(:fields) serialize(data, {include: options[:fields]}) else serialize(data) end render json: result end def render_error(error) render json: {success: false, error: error.message}, status: :unprocessable_entity end def current_user return if token.nil? user = User.find(auth["id"]) @current_user ||= user end def application_code code = Rails.application.config.application_code raise(StandardError, "Code is not set for the current application.") unless code code end def current_application app_code = application_code return ApplicationModule.find_by(code: app_code) if app_code nil end def authenticate render json: {error: "Unauthorized"}, status: 401 if current_user.nil? end # In case we want to disable bullet for specific controller actions def skip_bullet previous_value = Bullet.enable? Bullet.enable = false yield ensure Bullet.enable = previous_value end private def serialize(data, options = {}) ActiveModelSerializers::SerializableResource.new(data, options) end def token return nil if request.env["HTTP_AUTHORIZATION"].nil? request.env["HTTP_AUTHORIZATION"].scan(/Bearer (.*)$/).flatten.last end def auth TokenService.decode(token) end end end end