什么是Sinatra/Rack的非常简单的身份验证方案 [英] What is a very simple authentication scheme for Sinatra/Rack

查看:129
本文介绍了什么是Sinatra/Rack的非常简单的身份验证方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正忙于将一个非常小的Web应用程序从ASP.NET MVC 2移植到Ruby/Sinatra.

I am busy porting a very small web app from ASP.NET MVC 2 to Ruby/Sinatra.

在MVC应用程序中,当针对数据库正确验证了用户登录时,正在使用FormsAuthentication.SetAuthCookie设置持久性cookie.

In the MVC app, FormsAuthentication.SetAuthCookie was being used to set a persistent cookie when the users login was validated correctly against the database.

我想知道Sinatra中的表单身份验证会是什么?所有的身份验证框架似乎都很庞大,而不是我真正想要的.

I was wondering what the equivalent of Forms Authentication would be in Sinatra? All the authentication frameworks seem very bulky and not really what I'm looking for.

推荐答案

这是Sinatra的一种非常简单的身份验证方案.

Here is a very simple authentication scheme for Sinatra.

我将在下面解释其工作原理.

I’ll explain how it works below.

class App < Sinatra::Base
  set :sessions => true

  register do
    def auth (type)
      condition do
        redirect "/login" unless send("is_#{type}?")
      end
    end
  end

  helpers do
    def is_user?
      @user != nil
    end
  end

  before do
    @user = User.get(session[:user_id])
  end

  get "/" do
    "Hello, anonymous."
  end

  get "/protected", :auth => :user do
    "Hello, #{@user.name}."
  end

  post "/login" do
    session[:user_id] = User.authenticate(params).id
  end

  get "/logout" do
    session[:user_id] = nil
  end
end

对于要保护的任何路由,请向其添加:auth => :user条件,如上面的/protected示例所示.这将调用auth方法,该方法通过condition向路由添加条件.

For any route you want to protect, add the :auth => :user condition to it, as in the /protected example above. That will call the auth method, which adds a condition to the route via condition.

该条件调用is_user?方法,该方法已定义为辅助方法.该方法应返回true或false,具体取决于会话是否包含有效的帐户ID. (通过这样动态地调用帮助程序,可以轻松地添加具有不同特权的其他类型的用户.)

The condition calls the is_user? method, which has been defined as a helper. The method should return true or false depending on whether the session contains a valid account id. (Calling helpers dynamically like this makes it simple to add other types of users with different privileges.)

最后,before处理程序为每个请求的每个请求设置一个@user实例变量,例如在每页顶部显示用户名.您还可以在视图中使用is_user?帮助器来确定用户是否已登录.

Finally, the before handler sets up a @user instance variable for every request for things like displaying the user’s name at the top of each page. You can also use the is_user? helper in your views to determine if the user is logged in.

这篇关于什么是Sinatra/Rack的非常简单的身份验证方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆