Sha256: 845925d75a8dc3093978bc2301bd1739c302f007c680325a12d6d75c1abe9e32

Contents?: true

Size: 1.43 KB

Versions: 3

Compression:

Stored size: 1.43 KB

Contents

require 'sinatra/base'
require 'sinatra/reloader' if ENV['RUBYPITAYA_ENV'] == 'development'
require 'rubypitaya/core/parameters'

module RubyPitaya

  class HttpRoutes < Sinatra::Base

    if ENV['RUBYPITAYA_ENV'] == 'development'
      register Sinatra::Reloader
    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

      return error_unauthorized unless authorized?(request)

      @bll = settings.bll
      @setup = settings.setup
      @config = settings.config

      @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)
    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 ENV.fetch("HTTP_AUTH_ENABLED") { 'false' } == 'true'
    end

    def get_http_auth
      user = ENV.fetch("HTTP_AUTH_USER") { '' }
      pass = ENV.fetch("HTTP_AUTH_PASS") { '' }

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

      return "Basic #{auth_token}"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rubypitaya-2.20.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-2.19.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-2.19.0 ./lib/rubypitaya/core/http_routes.rb