在 Rails 5 上使用 Ruby,如果未授权相同的 stored_location_for() Devise 使用,我如何让 Pundit 重定向回来?
With Ruby on Rails 5, how can I have Pundit redirect back when not authorized to the same stored_location_for() Devise uses?
我已经按照Devise wiki如何设置了store_user_location! sign_in/sign_out 后重定向回上一页的方法,并希望在触发 user_not_authorized 后使用相同的方法与 Pundit 重定向,但我不确定为 [=18= 提供什么].通常这是 Devise 在其回调中提供的内容 (after_sign_in_path_for(resource_or_scope)
)。是否可以对 Pundit 使用相同的方法,我提供什么作为 resource_or_scope?
def user_not_authorized
flash[:error] = "You are not authorized to perform this action."
stored_location_for(what_goes_here?)
end
试试下面的方法,我通常是这样处理的:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# ...
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
private
# Redirects the browser to the page that issued the request (the referrer) if possible,
# otherwise redirects to the root location.
def user_not_authorized
redirect_back(fallback_location: root_path)
end
end
希望对您有所帮助!
我找到了我要找的东西 "what_goes_here" 的答案是“:user”,这是我从链接的 wiki 的函数中得到的:
def store_user_location
# :user is the scope we are authenticating
store_location_for(:user, request.fullpath)
end
不幸的是,这并没有像我希望的那样工作,因为我的 before_action :store_user_location!, if: :storable_location?
存储了在获得授权之前尝试访问的位置,如果用户最终未获得授权,它只会重定向回相同的 URL 他们没有被授权,并且随之而来的是无限重定向循环。
我也尝试了 redirect_back fallback: root_path
选项,但无论出于何种原因,它总是让我回到 root_path,从可用性的角度来看,我不喜欢它。
我现在正在研究其他选项,但看起来它最终只会在未经授权时显示 401/404 错误页面,用户只能使用浏览器的后退按钮。
我已经按照Devise wiki如何设置了store_user_location! sign_in/sign_out 后重定向回上一页的方法,并希望在触发 user_not_authorized 后使用相同的方法与 Pundit 重定向,但我不确定为 [=18= 提供什么].通常这是 Devise 在其回调中提供的内容 (after_sign_in_path_for(resource_or_scope)
)。是否可以对 Pundit 使用相同的方法,我提供什么作为 resource_or_scope?
def user_not_authorized
flash[:error] = "You are not authorized to perform this action."
stored_location_for(what_goes_here?)
end
试试下面的方法,我通常是这样处理的:
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# ...
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
private
# Redirects the browser to the page that issued the request (the referrer) if possible,
# otherwise redirects to the root location.
def user_not_authorized
redirect_back(fallback_location: root_path)
end
end
希望对您有所帮助!
我找到了我要找的东西 "what_goes_here" 的答案是“:user”,这是我从链接的 wiki 的函数中得到的:
def store_user_location
# :user is the scope we are authenticating
store_location_for(:user, request.fullpath)
end
不幸的是,这并没有像我希望的那样工作,因为我的 before_action :store_user_location!, if: :storable_location?
存储了在获得授权之前尝试访问的位置,如果用户最终未获得授权,它只会重定向回相同的 URL 他们没有被授权,并且随之而来的是无限重定向循环。
我也尝试了 redirect_back fallback: root_path
选项,但无论出于何种原因,它总是让我回到 root_path,从可用性的角度来看,我不喜欢它。
我现在正在研究其他选项,但看起来它最终只会在未经授权时显示 401/404 错误页面,用户只能使用浏览器的后退按钮。