Class: Clerk::RackMiddlewareV2

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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ RackMiddlewareV2

Returns a new instance of RackMiddlewareV2.



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/clerk/rack_middleware_v2.rb', line 93

def initialize(app)
  @app = app
  @excluded_routes = {}
  @excluded_routes_wildcards = []

  Clerk.configuration.excluded_routes.each do |route|
    route = route.strip

    if route.ends_with?("/*")
      @excluded_routes_wildcards << route[0..-2]
    else
      @excluded_routes[route] = true
    end
  end

  @excluded_routes_wildcards.uniq!
end

Instance Method Details

#call(env) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/clerk/rack_middleware_v2.rb', line 111

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

  if @excluded_routes[req.path]
    return @app.call(env)
  end

  @excluded_routes_wildcards.each do |route|
    return @app.call(env) if req.path.starts_with?(route)
  end

  env["clerk"] = Clerk::ProxyV2.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)

  if !auth_request_headers.empty?
    # Remove them to avoid overriding existing cookies set in headers by other middlewares
    auth_request_cookies = auth_request_headers.delete(COOKIE_HEADER)
    # 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