【发布时间】:2017-05-25 13:06:39
【问题描述】:
我想这样做,以便必须存在会话才能使用网站。如果不是,则重定向到根路径,以便用户可以选择是否以访客身份浏览站点、登录或注册。我正在使用基于 Railscast 的从头开始的基本身份验证。
在应用控制器中
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :set_artists
before_filter :check_session
helper_method :current_user
private
def set_artists
@artists = Artist.all
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def check_session
unless current_user
redirect_to root
end
end
end
我有一个访客用户登录,然后通过 Rails 控制台清除了所有访客用户:User.where(guest: true).destroy_all。我有一个 rake 任务可以清除 1 天前的访客会话,所以这将是一个非常典型的情况。之后尝试重新加载,错误出现:Couldn't find User with 'id'=8
【问题讨论】:
-
您需要使您的 cookie 无效或从浏览器中删除。您可以通过更改 the secret key base 来使所有现有 cookie 失效。
-
您可能还想阅读how sessions work in Rails,因为“需要会话”的整个概念是错误的。 Rails 应用程序的每个访问者都会获得一个会话——但只有那些允许 cookie 的访问者才能在初次访问后“回收”一个会话。您可能的意思是使身份验证成为强制性的。 (访客用户也是一种身份验证形式)。
-
有什么好的方法可以确保作为访客身份验证在时间到来时被清除,用户不会因为他们的 cookie 而遇到这样的崩溃?
标签: ruby-on-rails session authentication