Sha256: d3d5f3211f87868c82882db96ac8b3abf25fbdbcc5535166ebb9df51aa7a3d15

Contents?: true

Size: 1.69 KB

Versions: 7

Compression:

Stored size: 1.69 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

      @bll = settings.bll
      @log = settings.log
      @mongo = settings.mongo
      @setup = settings.setup
      @redis = settings.redis
      @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.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.0.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.0.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-2.27.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-2.27.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-2.26.3 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-2.26.2 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-2.25.1 ./lib/rubypitaya/core/http_routes.rb