我正在參加一門讓我創建一個基本wiki的課程。我絕對是新來的。我需要限制用戶只需輸入他們希望直接在URL中查看的wiki ID(例如:wiki/5)。唯一能夠查看wiki的人應該是wiki所有者,管理員或該wiki上的協作者。如何限制用戶查看他們無權訪問的頁面?
我已成功限制索引視圖,以便登錄用戶只能看到他們自己的wiki,公共維基或他們協作的wiki。
我試圖在我的WikiPolicy中實現類似的代碼,但它不工作,我似乎無法找到解決方案。我現在的代碼只是顯示wiki,如果用戶登錄。我知道我的邏輯是好的,因爲我可以用params [:id]替換爲「5」的值,並且它按預期工作。
wikis_controller.rb
def show
@wiki = Wiki.find(params[:id])
authorize @wiki
end
wiki_policy.rb
def show?
scope.where(:id => record.id).exists?
current_wiki = Wiki.find(params[:id])
collaborations = Collaboration.where(:user_id => user)
collab_wikis = Wiki.where(id: collaborations.pluck(:wiki_id))
collab_wikis.include?(current_wiki)
end
下面是我在wiki_policy.rb用於返回一組特定用戶被授權查看維基的代碼。我相信這是有效的,因爲它正在查看所有wiki,而不是依賴於用戶試圖查看的特定wiki。
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
wikis = []
if user.role?(:admin)
wikis = scope.all # if the user is an admin, show them all the wikis
elsif user.role?(:premium)
collaborations = Collaboration.where(:user_id => user)
collab_wikis = Wiki.where(id: collaborations.pluck(:wiki_id))
all_wikis = scope.all
all_wikis.each do |wiki|
if !wiki.is_private || wiki.user_id == user.id || collab_wikis.include?(wiki)
wikis << wiki # if the user is premium, only show them public wikis, or that private wikis they created, or private wikis they are a collaborator on
end
end
else # this is the lowly standard user
collaborations = Collaboration.where(:user_id => user)
collab_wikis = Wiki.where(id: collaborations.pluck(:wiki_id))
all_wikis = scope.all
wikis = []
all_wikis.each do |wiki|
if !wiki.is_private? || wiki.user_id == user.id || collab_wikis.include?(wiki)
wikis << wiki # only show standard users public wikis and private wikis they are a collaborator on
end
end
end
wikis # return the wikis array we've built up
end
end
謝謝!這是完美的,幫助我理解我想要做得更好。 – Tyler