Rails 3 - authenticate and: before_filter

I am new to Rails. I am trying to create a simple authentication system, application_controller . I put the 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 one action - in this action I check if the user is logged in or not. And if the user logs in, so I will display one template, and if not, then I will do the second. It looks like this:

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

And here's the problem - it doesn't work for me. At least ... well - if I do not log in, the template_for_not_login_user template will be displayed, and if so, template_for_login_user . It is right.

But if I log in and I am in template_for_login_user , but I am 15min idle => the session has expired => I need to redirect to the login form. But here is the problem: I am idle for 15 minutes and refreshing this page, so I am still in the action of template_for_login_user - and this is the problem ...

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

+2
source share
1 answer

In your ApplicationController application, you added this line:

 before_filter :check_session 

If any controller action does not require user authentication, you can add this:

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

in this example, it will skip your before_filter: check_session by action: index and search. So you have a global behavior that always checks the session for user login. But you can skip this in a specific controller, where some actions do not need user authentication

+5
source

Source: https://habr.com/ru/post/1493046/


All Articles