Class: AgentCode::Middleware::ResolveOrganizationFromRoute

Inherits:
Object
  • Object
show all
Defined in:
lib/agentcode/middleware/resolve_organization_from_route.rb

Overview

Rack middleware that extracts the organization from the route parameter. Mirrors the Laravel ResolveOrganizationFromRoute middleware.

For route-prefix multi-tenancy: /api/organization/posts

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ ResolveOrganizationFromRoute

Returns a new instance of ResolveOrganizationFromRoute.



10
11
12
# File 'lib/agentcode/middleware/resolve_organization_from_route.rb', line 10

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/agentcode/middleware/resolve_organization_from_route.rb', line 14

def call(env)
  request = ActionDispatch::Request.new(env)

  # Extract organization identifier from route params
  org_identifier = request.path_parameters[:organization]

  if org_identifier.present?
    organization = find_organization(org_identifier)

    unless organization
      return [404, { "Content-Type" => "application/json" }, ['{"message":"Organization not found"}']]
    end

    # Check if authenticated user belongs to this organization
    user = resolve_user(request)
    if user && !user_belongs_to_organization?(user, organization)
      return [404, { "Content-Type" => "application/json" }, ['{"message":"Organization not found"}']]
    end

    env["agentcode.organization"] = organization

    if defined?(RequestStore)
      RequestStore.store[:agentcode_organization] = organization
    end
  end

  @app.call(env)
end