anemaria20
anemaria20

Reputation: 1728

Before filter in Sinatra causing a redirect loop

I have this simple code:

require 'sinatra'

before  do
  redirect '/login'
end

get '/login' do
  'hello'
end

get '/test' do
  'should not show'
end

This simple app is supposed to redirect every route, including /test to the login route. Instead, I'm getting a redirect loop.

I use the latest version of Sinatra 2.0.5.

Upvotes: 0

Views: 299

Answers (2)

ian
ian

Reputation: 12251

A solution is offered above but the explanation is that redirect triggers browser redirect so the process will begin again at the start every time. To use a server side redirect use call. From the docs:

Triggering Another Route

Sometimes pass is not what you want, instead you would like to get the result of calling another route. Simply use call to achieve this:

get '/foo' do
  status, headers, body = call env.merge("PATH_INFO" => '/bar')
  [status, headers, body.map(&:upcase)]
end

get '/bar' do
  "bar"
end

Note that in the example above, you would ease testing and increase performance by simply moving "bar" into a helper used by both /foo and /bar.

If you want the request to be sent to the same application instance rather than a duplicate, use call! instead of call.

Check out the Rack specification if you want to learn more about call.

Hence, you probably want a helper (or more likely, a condition, if you're checking for auth).

Upvotes: 0

Vasilisa
Vasilisa

Reputation: 4640

You need to exclude /login route from before_filter

before do
  redirect '/login' if request.path_info != "/login"
end

Upvotes: 2

Related Questions