Sha256: 568c297e92c91e459da32041ddab0ac373cb2716b9234d57a44472d88dec02cc

Contents?: true

Size: 1.99 KB

Versions: 1

Compression:

Stored size: 1.99 KB

Contents

require 'rack'
require 'json'

module SoarAuthenticationToken
  class RackMiddleware
    def initialize(app, configuration, service_identifier, auditing = nil)
      @app = app
      @configuration = configuration
      @service_identifier = service_identifier
      @auditing = auditing
    end

    def call(env)
      session, params, token, flow_id, request_information, = get_request_information(env)
      token_valid, token_meta, message = validate_and_resolve_token(token, request_information, flow_id)
      if token_valid
        session['user'] = token_meta['authenticated_identifier']
        session['auth_token_meta'] = token_meta
        return @app.call env
      end
      audit_token_rejection("Token rejected due to #{message}",flow_id)
      rejection
    end

    private

    def get_request_information(env)
      request = Rack::Request.new env
      [ request.session,
        request.params,
        request.env['HTTP_AUTHORIZATION'],
        request.params['flow_identifier'],
        { 'source_address'    => request.env['REMOTE_ADDR'],
          'user_agent'        => request.env['HTTP_USER_AGENT'],
          'service'           => @service_identifier,
          'resource'          => request.env['REQUEST_PATH']
        }
      ]
    end

    def validate_and_resolve_token(authentication_token, request_information, flow_identifier)
      token_validator = SoarAuthenticationToken::TokenValidator.new(@configuration)
      token_validator.validate(authentication_token: authentication_token,
                               request_information: request_information,
                               flow_identifier: flow_identifier)
    end

    def audit_token_rejection(message, flow_id)
      @auditing.warn(message,flow_id) if @auditing
    end

    def rejection
      [ 401,
        { 'Content-Type' => 'application/json'},
        [ {
          'status' => 'fail',
          'data' => {
            'notifications' => ['Not authenticated']
          }
        }.to_json ]
      ]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
soar_authentication_token-6.0.7 lib/soar_authentication_token/rack_middleware.rb