0

ユーザー コントローラーに before フィルターと def check priv を追加しました。管理者だけがすべてのプロフィールを閲覧・編集でき、作成したユーザーだけが自分のプロフィールを閲覧できるように設定されているとします。以前と同様に、誰でもプロファイルを表示/編集できました。私はいくつかの方法を試しましたが、どれもうまくいきません。管理者または通常のユーザーとしてプロファイルを表示すると、「承認されていません」というメッセージが表示されます。

どんな助けでも大歓迎です。

ユーザーコントローラー:

  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 %>
4

2 に答える 2

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 条件を変更してみてください

if (condition || condition)

また

if ((condition) || (condition))

問題は、明示的に宣言されていない場合、Ruby パーサーが最初の条件で停止することです。

更新 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 %>
于 2013-03-18T17:53:46.967 に答える
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、ビューに適用できる一定量のルールを設定できます。

CanCan のメソッドを使用する場合は、このようなことを自分の能力で行うことができます.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 %>

このようなものがうまくいくはずです。あなたのオプションは、これが役立つことを願っています:)

于 2013-03-18T19:44:16.160 に答える