Check if current_user is the owner of a resource and allow edit/delete actions

后端 未结 9 590
鱼传尺愫
鱼传尺愫 2021-02-02 00:02

Example:

User A (id=10) has created a photo resource

photo: (id: 1 user_id = 10, url: \"http://...\")
         


        
相关标签:
9条回答
  • 2021-02-02 00:56

    So you are using gem devise.

    This gem provides the current_user for the currently logged in user.

    In your PhotosController#edit method. I'd do something like below.

    def edit
      @photo = Photo.find(params[:id])
      redirect_to root_path, notice: 'Thou Shalt Nought duuu dat :(' unless current_user.id == @photo.user_id
      ...
    end
    

    This method is cheaper because you already have 2 objects to compare instead of running a query in the comparison.

    0 讨论(0)
  • 2021-02-02 00:56

    cancan is difficult and complicate i have coding is_onwer method it's very simple, easy

    https://gist.github.com/x1wins/0d3f0058270cef37b2d3f25a56a3745d

    application controller

     def is_owner user_id
        unless user_id == current_user.id
          render json: nil, status: :forbidden
          return
        end
      end
      def is_owner_object data
        if data.nil? or data.user_id.nil?
          return render status: :not_found
        else
          is_owner data.user_id
        end
      end
    

    your controller

      before_action only: [:edit, :update, :destroy] do
        is_owner_object @article ##your object
      end
    
    0 讨论(0)
  • 2021-02-02 00:57

    Write another before_filter in application_controller:

    before_filter :has_permission?
    
    has_permission?
    controllers=["articles", "photos", "..."]
    actions=["edit", "destroy", "..."]
    id = params[:id] if (controllers.include?(params[:controller] && actions.include?(params[:action]) end
    if id && (current_user.id==(params[:controller][0...1].capitalize!+params[:controller].singularize[1...-1] + ".find(#{id}).user_id").send)
    return true
    else
    redirect_to root_url, :notice=>"no permission for this action"
    end
    
    helper_method :has_permission?
    

    And you can use it in views, not to show users link they can't follow.

    Some kind of this, of course you need to modify it to suit your needs.

    0 讨论(0)
提交回复
热议问题