Before filter on condition

眉间皱痕 提交于 2019-12-12 10:17:37

问题


I have a Sinatra app where all routes require a user login by default. Something like this:

before do 
  env['warden'].authenticate!
end

get :index do
  render :index
end

Now I would like to use a custom Sinatra condition to make exceptions, but I cannot find a way to read if the condition is true/false/nil

def self.public(enable)
  condition {
    if enable 
      puts 'yes'
    else
      puts 'no'
    end
  }
end

before do 
  # unless public?
  env['warden'].authenticate!
end

get :index do
  render :index
end

get :foo, :public => true do
  render :index
end

Since the authentication check must be done even if the condition is not defined, I guess I still must use a before filter, but I am not sure how to access my custom condition.


回答1:


I was able to solve this using Sinatra's helpers and some digging into Sinatra's internals. I think this should work for you:

helpers do
  def skip_authentication?
    possible_routes = self.class.routes[request.request_method]

    possible_routes.any? do |pattern, _, conditions, _|
      pattern.match(request.path_info) &&
        conditions.any? {|c| c.name == :authentication }
    end
  end
end

before do
  skip_authentication? || env['warden'].authenticate!
end

set(:authentication) do |enabled|
  condition(:authentication) { true } unless enabled
end

get :index do
  render :index
end

get :foo, authentication: false do
  render :index
end


来源:https://stackoverflow.com/questions/22380342/before-filter-on-condition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!