Sha256: bc6b5527e69bb44a343f6748153551067bd9bde48aebf9e94d2fcf2ef35b139b

Contents?: true

Size: 1.79 KB

Versions: 3

Compression:

Stored size: 1.79 KB

Contents

# frozen_string_literal: true

require 'proxes/request'
require 'proxes/policies/request_policy'
require 'ditty/services/logger'
require 'ditty/helpers/pundit'
require 'ditty/helpers/authentication'

module ProxES
  module Middleware
    class Security
      attr_reader :env, :logger

      include Ditty::Helpers::Authentication
      include Ditty::Helpers::Pundit

      def initialize(app, logger = nil)
        @app = app
        @logger = logger || ::Ditty::Services::Logger.instance
      end

      def call(env)
        @env = env
        request = ProxES::Request.from_env(env)
        log(request, 'BEFORE')

        check_basic request
        authorize request

        request.index = policy_scope(request) if request.indices?
        log(request, 'AFTER')

        @app.call env
      end

      def check_basic(request)
        auth = Rack::Auth::Basic::Request.new(request.env)
        return false unless auth.provided? && auth.basic?

        identity = ::Ditty::Identity.find(username: auth.credentials[0])
        identity ||= ::Ditty::Identity.find(username: CGI.unescape(auth.credentials[0]))
        return false unless identity && identity.authenticate(auth.credentials[1])
        request.env['rack.session'] ||= {}
        request.env['rack.session']['user_id'] = identity.user_id
      end

      def authorize(request)
        Pundit.authorize(request.user, request, request.request_method.downcase + '?')
      end

      def log(request, stage)
        logger.debug '============' + stage.ljust(56) + '============'
        logger.debug '= ' + "Request: #{request.detail}".ljust(76) + ' ='
        logger.debug '= ' + "Endpoint: #{request.endpoint}".ljust(76) + ' ='
        logger.debug '================================================================================'
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
proxes-0.9.12 lib/proxes/middleware/security.rb
proxes-0.9.9 lib/proxes/middleware/security.rb
proxes-0.9.7 lib/proxes/middleware/security.rb