轨道3 - 验证和:的before_filter [英] Rails 3 - authenticate and :before_filter

查看:110
本文介绍了轨道3 - 验证和:的before_filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails的一个新手。我试图建立一个简单的身份验证系统,为 application_controller 我把下面几行:

I am a newbie in Rails. I try to build a simple authenticate system, to application_controller I put following lines:

  def check_session
    if session[:user]
      if session[:expiry_time] < 10.minutes.ago
        reset_session
      flash[:warning] = 'You was logout.' 
        redirect_to root_url
      else
        session[:expiry_time] = Time.now
      end
    else
      #... authenticate
      session[:expiry_time] = Time.now
      flash[:warning] = 'You was logout.' 
      redirect_to root_url
    end
  end  

我的问题是在一个动作 - 在这个动作我检查,如果用户是登录与否。如果用户登录,所以我会呈现一个模板,如果没有,那么我将使得第二个。它看起来像:

My problem is in one action - in this action I check, if the user is log in or not. And if the user is log in, so I will render one template, and if not, so I will render the second one. It looks like:

<% unless session[:user].nil? %>
  <%= render :template => 'template_for_login_user' %>
<% else %>
  <%= render :template => 'template_for_not_login_user' %>
<% end %>

和这里的问题是 - 这不工作的我。至少......嗯 - 如果我无法登录,所以会呈现模板的 template_for_not_login_user ,如果我是,所以 template_for_login_user 。这是对的。

And here is the problem - this doesn't works me. At least... well - if I am not log in, so will be render the template template_for_not_login_user and if I am, so template_for_login_user. This is right.

但是,如果我登录,我的 template_for_login_user ,但我15分钟空闲=>会话将过期=>我应该重定向到登录表单。但现在的问题是 - 我15连接空闲,我刷新此页面,所以我还是行动上的 template_for_login_user - 这是问题...

But if I am log in and I am on the template_for_login_user, but I am 15min idle => the session will be expired => I should be redirect to login form. But here is the problem - I am 15 minutes idle and I refresh this page, so I am still on the action template_for_login_user - and this is the problem...

我想问你 - 你能不能帮我请,这里可能是一个问题?我做错了吗?

I would like to ask you - can you help me please, where could be a problem? What I'm doing wrong?

推荐答案

在你的ApplicationController,你添加一行:

In your ApplicationController, did you add a line like this :

before_filter :check_session

如果要进行身份验证的一些控制器动作不需要的用户,可以补充一点:

if some controller action don't need the user to be authenticated, you can add this:

skip_before_filter :check_session, :only=> [:index, :search, etc..]

在这个例子中,这将跳过你的before_filter:索引和搜索:行动check_session。这样,你有一个全球性的行为总是检查用户会话登录。但是你可以在特定的控制器跳过这有些行动并不需要用户进行身份验证

in this example, this would skip your before_filter :check_session on action : index and search. This way you have a global behavior that always check the session for a user logged on. But you can skip this in particular controller where some actions don't need the user to be authenticated

这篇关于轨道3 - 验证和:的before_filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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