Class: KeycloakRack::AuthorizeResource

Inherits:
Object
  • Object
show all
Extended by:
Dry::Initializer
Defined in:
lib/keycloak_rack/authorize_resource.rb

Overview

A service that allows someone to check if the current token has a resource-level role.

It is instantiated in keycloak:authorize_resource after the middleware runs.

This can greatly simplify access control for rack services (for instance, to gate modifications to a certain type of resource).

Examples:

class WidgetCombobulator
  def initialize(app)
    @app = app
  end

  def call(env)
    env["keycloak.authorize_resource"].call("widgets", "recombobulate") do |m|
      m.success do
        # allow the user to recombobulate the widget
      end

      m.failure do
        # return forbidden, log the attempt, etc
      end
    end
  end
end

Instance Method Summary collapse

Instance Method Details

#call(resource_name, role_name) ⇒ Dry::Monads::Success(:authorized, String), ...

Check that the current session has a certain resource role.

Parameters:

  • resource_name (String)
  • role_name (String)

Returns:

  • (Dry::Monads::Success(:authorized, String))
  • (Dry::Monads::Failure(:unauthorized, String))
  • (Dry::Monads::Failure(:unauthenticated, String))

See Also:


44
45
46
47
48
49
50
51
52
# File 'lib/keycloak_rack/authorize_resource.rb', line 44

def call(resource_name, role_name)
  if session.has_resource_role?(resource_name, role_name)
    Success[:authorized, resource_name, role_name]
  elsif session.authenticated?
    Failure[:unauthorized, "You do not have #{role_name.to_s.inspect} access on #{resource_name.to_s.inspect}"]
  else
    Failure[:unauthenticated, "You are not authenticated"]
  end
end