Sha256: edf40af8cddcbd5fdb92b55ff63354d29b3fffaa382a8e7ca8ed7dbb5eee7464

Contents?: true

Size: 1.7 KB

Versions: 16

Compression:

Stored size: 1.7 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
      @mongo = settings.mongo
      @setup = settings.setup
      @redis = settings.redis
      @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

16 entries across 16 versions & 1 rubygems

Version Path
rubypitaya-3.4.2 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.4.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.4.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.7 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.6 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.5 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.4 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.3 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.2 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.3.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.2.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.1.1 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.1.0 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.0.3 ./lib/rubypitaya/core/http_routes.rb
rubypitaya-3.0.2 ./lib/rubypitaya/core/http_routes.rb