Sha256: e2bc32f363c8ce05763bc1945428bb0e8bc6e41e2b41ccdf1a5c0b333afc8d51

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

require 'sinatra/base'
require 'rubypitaya/core/parameters'

module RubyPitaya

  class HttpRoutes < Sinatra::Base

    def self.auto_reload
      require 'sinatra/reloader'
      register ::Sinatra::Reloader
    end

    configure do
      set :show_exceptions, false
    end

    helpers do
      def find_template(views, name, engine, &block)
        views.each { |v| super(v, name, engine, &block) }
      end
    end

    before do
      content_type :json

      @log = settings.log
      @setup = settings.setup
      @services = settings.services
      @config = settings.config
      @session = nil
      @postman = nil

      return error_unauthorized unless authorized?(request)

      @config.clear_cache

      if request.content_type == 'application/json'
        request_body = request.body.read
        @params.merge!(JSON.parse(request_body)) if !request_body.blank?
      end

      @params = Parameters.new(@params)
      @params.permit!
    end

    after do
      ActiveRecord::Base.connection_handler.clear_active_connections!
    end

    private

    def error_unauthorized
      return halt(401, 'Unauthorized')
    end

    def authorized?(request)
      return true unless http_auth_enabled?

      auth_token = request.env['HTTP_AUTHORIZATION']
      return auth_token == get_http_auth
    end

    def http_auth_enabled?
      return @setup.fetch('rubypitaya.http.auth.enabled') { 'false' } == 'true'
    end

    def get_http_auth
      user = @setup.fetch('rubypitaya.http.auth.user') { '' }
      pass = @setup.fetch('rubypitaya.http.auth.pass') { '' }

      auth_token = ::Base64.strict_encode64("#{user}:#{pass}")

      return "Basic #{auth_token}"
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rubypitaya-3.17.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.17.0 ./lib/rubypitaya/core/http_routes.rb