我正在学习Rails,如果用户没有登录并且只允许他们查看登录和注册页面,我会尝试限制对页面的访问。
目前,我的代码在用户登录时创建会话,并在用户注销时清除它。我有一个Sessions助手,以便我可以检查用户是否已登录,但我不确定如果他/她未登录,如何在整个应用程序中重定向用户。
更新:
当我发布问题时,我设法使用before_filter。我应该使用before_action还是before_filter?
我是否需要在我想限制访问权限的所有控制器中复制相同的方法?
CODE:
/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
/controllers/sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out
redirect_to root_url
end
end
/helpers/sessions_helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out the current user.
def log_out
session.delete(:user_id)
@current_user = nil
end
end
答案 0 :(得分:5)
您可以使用before_action
。 rails guide有一个很好的section,上面有一个例子:
class ApplicationController < ActionController::Base
before_action :require_login
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url # halts request cycle
end
end
end