代码之家  ›  专栏  ›  技术社区  ›  BeeZee

Sinatra:如何在阻止访问Sinatra应用程序其余部分的同时提供对登录窗体的访问?

  •  2
  • BeeZee  · 技术社区  · 16 年前

    我最近创建了一个带有登录表单(没有基本身份验证)的Sinatra应用程序。为了防止访问应用程序,除非用户登录,我把一个前块到位

    before do
      unless request.path_info == '/login'
        authenticated?
      end
    end
    

    before do
      unless request.path_info == '/login' || request.path_info == "/stylesheets/master.css" || request.path_info == "/images/logo.png"
        authenticated?
      end
    end
    

    如果我需要大量的资源来提供这种方法的例外,那么它们很快就会变得势不可挡。有什么更好的方法来编写代码,这样我就可以为公共目录甚至它的特定子目录和文件创建例外,比如 /stylesheets , /images , /images/bg.png /secret /secret/eyes-only.pdf ?

    或者。。。有没有一种完全不同的最佳实践来处理这种情况,即除了与登录相关的东西(处理程序、视图、资源)之外,所有东西都被锁定?

    2 回复  |  直到 16 年前
        1
  •  1
  •   Konstantin Haase    16 年前

    您可以将登录逻辑提取到它自己的机架中间件(可以是Sinatra应用程序)中。

    require 'sinatra'
    
    class Authentication < Sinatra::Base
      def logged_in?
        # your login logic goes here
      end
    
      get '/login' do
        # login formular and logic here
      end
    
      get(//) do
        pass if logged_in?
        redirect '/login'
      end
    end
    
    configure { |c| c.use Authenitcation }
    
    get('/') { ... }
    
        2
  •  0
  •   James A. Rosen    16 年前

    与其直接将授权信息放入Sinatra应用程序中,不如使用 Rack::Auth :

    # my_app.ru
    
    
    
    app = Rack::Builder.new do
      use Rack::Static, :urls => /^(stylesheets|javascripts|images|fonts)\//
    
      map '/login' do
        run MyApplication
      end
    
      map '/' do
        use Rack::Auth::Basic do |username, password|
          # check the username and password sent via HTTP Basic auth
        end
        run MyApplication
      end
    end
    
    推荐文章