我从头开始从here滚动R Bates身份验证,我想在应用程序控制器中调用authorize方法。基本上我想要锁定整个应用程序。这是app控制器......
class ApplicationController < ActionController::Base
before_filter :authorize
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def authorize
redirect_to login_url, alert: "Not authorized" if current_user.nil?
end
end
但可能是我的URL调用中出现了无限循环。我该怎么办呢?
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Email or password is invalid"
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, notice: "Logged out!"
end
end
答案 0 :(得分:0)
循环是因为redirect_to login_url...
。
您应跳过将authorize
操作定义为的控制器中的login
过滤器:
class SessionsController < ApplicationController
skip_before_filter :authorize, only: :login
def login
...
end
...
end
或者要跳过authorize
过滤所有操作,请使用skip_before_filter :authenticate
而不使用only
选项。
答案 1 :(得分:0)
对于before_filter
的某些操作,您可以跳过SessionsController
(例如@vee回答):
skip_before_filter :authorize, only: [:new, :create]
或者,您可以修改authorize
方法以避免在某些情况下重定向:
def authorize
return if skip_authorization?("#{controller_name}##{action_name}")
redirect_to login_url, alert: "Not authorized" if current_user.nil?
end
def skip_authorization?(location)
%w(sessions#new sessions#create).include?(location)
end