Class: Clerk::Rack::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/clerk/rack_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



10
11
12
13
14
15
# File 'lib/clerk/rack_middleware.rb', line 10

def initialize(app, options = {})
  @app = app

  Clerk.configuration.update(options) if options
  @excluded_routes, @excluded_routes_wildcards = Clerk::Utils.filter_routes(Clerk.configuration.excluded_routes)
end

Instance Method Details

#call(env) ⇒ Object



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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/clerk/rack_middleware.rb', line 17

def call(env)
  env["clerk.initialized"] = true

  req = ::Rack::Request.new(env)

  if @excluded_routes[req.path]
    env["clerk.excluded_route"] = true
    return @app.call(env)
  end

  @excluded_routes_wildcards.each do |route|
    if req.path.start_with?(route)
      env["clerk.excluded_route"] = true
      return @app.call(env)
    end
  end

  env["clerk"] = Clerk::Proxy.new

  auth_context = AuthenticateContext.new(req, Clerk.configuration)
  auth_request = AuthenticateRequest.new(auth_context)

  status, auth_request_headers, body = auth_request.resolve(env)

  return [status, auth_request_headers, body] if status

  status, headers, body = @app.call(env)

  unless auth_request_headers.empty?
    # Remove them to avoid overriding existing cookies set in headers by other middlewares
    auth_request_cookies = auth_request_headers.delete(SET_COOKIE_HEADER.downcase)
    # merge non-cookie related headers into response headers
    headers.merge!(auth_request_headers)

    set_cookie_headers!(headers, auth_request_cookies) if auth_request_cookies
  end

  [status, headers, body]
end