2013-03-18 77 views
0

我已經添加了一個過濾器和def檢查權限的用戶控制器。假設設置爲只有管理員可以查看/編輯所有配置文件,並且只有創建的用戶才能查看他們自己的配置文件。和以前人一樣可以查看/編輯配置文件。我嘗試了一些方法,但都沒有成功。當我以管理員或甚至普通用戶的身份查看個人資料時,我收到「未經授權」的消息。未授權顯示的管理員

任何幫助,將不勝感激。

users_controller:

before_filter :check_privileges, :only => [:edit, :update] 

    def check_privileges 
    unless current_user.admin? || current_user.id == params[:id] 
     flash[:warning] = 'not authorized!' 
     redirect_to root_path 
    end 
    end 

的index.html:

<%= link_to user.name, user %> 
    <% if (current_user.admin? || current_user) == @user %> 
     <%= link_to "Edit #{user} profile", user %> 
     | <%= link_to "delete", user, method: :delete, 
             data: { confirm: "You sure?"} %> 
    <% end %> 
+0

我以前試過這種方法,只是C&P你的。同樣的問題。我一直在頭腦風暴,但是我想到的任何東西都不起作用 – pwz2000 2013-03-18 17:50:54

回答

1

我有我的應用程序類似的方法,嘗試是這樣的:

def check_privileges 
return if current_user.admin? # this user is an admin, if is not the case do: 
flash[:warning] = 'not authorized!' 
redirect_to root_path 
end 

更新1

再次,嘗試改變,如果條件爲遵循

if (condition || condition) 

if ((condition) || (condition)) 

的問題是,Ruby的解析器在第一條件停止,如果不explicited聲明。

更新2

我認爲有在你index.html.erb括號錯誤,請嘗試以下操作:

<%= link_to user.name, user %> 
    <% if (current_user.admin? || (current_user == @user)) %> 
     <%= link_to "Edit #{user} profile", user %> 
     | <%= link_to "delete", user, method: :delete, 
             data: { confirm: "You sure?"} %> 
    <% end %> 
+0

顯示未被授權的代碼。 – pwz2000 2013-03-18 17:55:27

+0

@ pwz2000如果你是一個普通用戶,閃光燈會顯示(在我的例子中),如果你不是管理員(我已經在我的應用上測試過) – damoiser 2013-03-18 18:00:13

+0

它顯示我是否是管理員。即使它顯示給用戶,它也不會保存信息。重定向到根,並說我沒有被授權。以前如果我更新了個人資料,它會保留在個人資料頁面上。只有在未經授權的情況下才會重定向到根網址。所以現在我不授權,不管我有什麼作用,也不是保存(由於沒有被授權)。我添加了index.html,以便您可以看到if條件如何與您的方法一起查看。 – pwz2000 2013-03-18 18:03:16

0

深思,也許你可以這樣做這個:

def correct_user 
    @user = User.find(params[:id]) 
    if current_user.role? :administrator 
     #Allow admin to access everyone account 
    else 
     access_denied unless current_user?(@user) 
    end 
    end 

然後在你的視圖中你的視圖做if statement。或者,我最好的建議是像CanCan這樣的東西。像這樣的東西可以讓你很容易地設置角色認證。如果你看看它,你可以在你的ability.rb中設置一定數量的規則,然後你可以在視圖上執行。

如果你去與慘慘的方法,你可以做這樣的事情在你的ability.rb

def initialize(user) 
    user ||= User.new # guest user 
    # raise user.role?(:administrator).inspect 
    if user.role? :administrator 

     can :manage, :all 
     can :manage, User 

    elsif user.role? :employee 
     can :read, :all 

    end 

以上是一個例子....所以,在你的views您可以實施此通過做類似的規則

<%= link_to user.name, user %> 
    <% if can? :manage, @user %> 
     <%= link_to "Edit #{user} profile", user %> 
     | <%= link_to "delete", user, method: :delete, 
             data: { confirm: "You sure?"} %> 
    <% end %> 

這樣的事情應該工作。你的選擇是有希望這有助於:)

相關問題