Sha256: d67df0634bc84390228c70ac4c64795b9209c6540534ce1a56f11b232007bd59

Contents?: true

Size: 1.68 KB

Versions: 7

Compression:

Stored size: 1.68 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
      @objects = settings.objects
      @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.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

7 entries across 7 versions & 1 rubygems

Version Path
rubypitaya-3.11.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.10.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.9.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.8.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.8.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.7.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.6.0 ./lib/rubypitaya/core/http_routes.rb