【发布时间】:2015-11-26 08:43:03
【问题描述】:
我有两个布局 Admin 和 Domain。而且我不需要在管理布局中进行任何额外的配置。但如果用户尝试访问 Domain 布局,则他们必须在其有效域中。
这意味着,我需要自定义我的所有 Domain 策略以包括 current_user 和 current_domain。我发现这可以用UserContext 和pundit_user 来完成...所以这就是我所做的:
application_controller.rb
class ApplicationController < ActionController::Base
include Pundit
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def pundit_user
UserContext.new(current_user, current_domain)
end
def after_sign_out_path_for(resource)
root_path
end
def current_domain
@current_domain ||= Domain.where(name: requested_domain).first
end
helper_method :current_domain
private
def requested_domain
return request.env["SERVER_NAME"]
end
def user_not_authorized
# reset_session
flash[:alert] = "You are not authorized to perform this action"
redirect_to(request.referrer || root_path)
end
end
请注意,当我访问Admin 布局时,current_domain 将为nil,如果我访问Domain 布局的任何路由,则current_domain 将设置为当前访问域。
user_context.rb
class UserContext
attr_reader :current_user, :current_domain
def initialize(current_user, current_domain)
@current_user = current_user
@current_domain = current_domain
end
end
问题
假设我有这个政策:
user_policy.rb
class UserPolicy < ApplicationPolicy
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def index?
binding.pry # debugging
current_user.admin? ||
current_user.domain == current_domain
end
private
def current_user
# return user.is_a?(User) ? user : user.current_user
user.current_user
end
def current_domain
# return user.is_a?(User) ? nil : user.current_domain
user.current_domain
end
end
当应用程序运行时,current_user 和 current_domain 必须根据文档在 UserPolicy 中可用 (https://github.com/elabs/pundit#additional-context)。
但我得到了
undefined method `current_user' for #<User:0x007fcefbc2b150>
也就是说,我仍然有用户对象,而不是 user.current_user 和 user.current_domain
如果您需要进一步的描述,请告诉我。我在这里错过了什么?
【问题讨论】:
-
您使用的是哪个版本的 Pundit?
-
它是
pundit (1.0.1)
标签: ruby-on-rails ruby ruby-on-rails-4 devise pundit