Sha256: f5ba05f93d071804f9a58b324d3f606e8b3eb695f9be8bd8da99b30dd6306f72

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

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] = options.key?(:fields) ? serialize(data, include: options[:fields]) : serialize(data)

        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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
comee_core-0.2.53 app/controllers/comee/core/application_controller.rb