簡體   English   中英

如何允許用戶刪除或更新僅具有自己資源的非用戶資源?

[英]How to allow users to delete or update non-user resources and only there own?

我的應用程序中的非用戶無法刪除或更新用戶的評論,而用戶只能更新或刪除自己的評論或非用戶的評論。 我遇到的問題是正確,安全地編寫此代碼。

這是我創建新注釋的方式,並且可以在不訪問user_id的情況下運行,但是我不確定如何處理update和delete方法。 目前,他們只允許當前用戶刪除或更新評論

評論控制器

def new
  @post = Post.find(params[:post_id])
  @comment = Comment.new
end

def edit
  @post = Post.find(params[:post_id])
  @comment = Comment.find(params[:id])
end

def create
  @post = Post.find(params[:post_id])

  if signed_in?
    @comment = current_user.comments.build(comment_params)  
  else
    @comment = Comment.create(comment_params)
  end
  if @comment.save.....
end

def update
  @post = Post.find(params[:post_id])
  @comment = current_user.comments.find(params[:id])
  if @comment.update(comment_params)..........
end

def destroy
  @comment = current_user.comments.find(params[:id])
  @comment.destroy
end

private

def comment_params
  params.require(:comment).permit(:body, :post_id)
end

我認為一定要如何到達@ comment.user字段,但是如果必須先找到評論,該怎么辦? 或者,如果這不是正確的方法,該怎么辦?

回答

這就是我最終要做的事情:

def update
  @post = Post.find(params[:post_id])
  @comment = Comment.find(params[:id])
  if @comment.user == current_user
    if @comment.update(comment_params)
      redirect_to @comment
    else
      render action: 'edit'
    end
  elsif @comment.user.blank?
    if @comment.update(comment_params)
      redirect_to @comment
    else
      render action: 'edit'
    end
  else
    redirect_to @comment, notice: "An Error occured"
  end
end

假設來賓用戶創建的評論的user_id字段設置為nil,則可以執行以下操作

class Post < ActiveRecord::Base
  ...
  scope :comments_editable_by, ->(user_id) { where('user_id is null or user_id = ?', user_id) }
  ...
end

並在updatedestroy操作中使用此作用域代替comments

我認為最好的方法是使用一個授權系統,如declarative_authorizationpunditcancancan 它們還提供了視圖幫助器,可讓您向無法更新特定評論的用戶隱藏更新鏈接。

盡管如果這是您唯一需要授權的地方,那么按照您的建議編寫自己的解決方案可能是一個更好的選擇。 您可以執行以下操作:

def CommentsController < ApplicationController
  ...
  def update
    @comment.update comment_params
    if @comment.authorized_update!(current_user)
      redirect_to @comment, status: :accepted
    else
      redirect_to @comment, status: :unauthorized
    end
  end
end

然后在您的模型中:

def Comment < ActiveRecord::Base
  ...
  def authorized_update!(current_user)
    if user == current_user
      self.save
    else
      errors[:base] << "Unauthorized"
      false
    end
  end
end

您可能必須對其進行調整以滿足您的需求,但是您明白了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM