Question

I'm using Devise for the first time with my Rails 4 project and I am trying to figure out how to lock down ownership of models to certain users.

For example, if a user creates a model only that user should be able to do the following to it,

  • list all models belonging to the user
  • view
  • edit
  • update
  • delete

So basically all crud actions should be restricted to the user who owns the model.

How would you you go about implementing ownership in a DRY idiomatic manner? It seems like I could do a check in the controller to see if the user owns the current object, but then if the object is used by another controller or used as part of a nested update I have to reimplement the logic, but it doesn't seem right for the model to have access to the current user.

Was it helpful?

Solution

I would check out the gem cancan, it assigns permissions to users, so if a user has a role of an owner is has the permissions for all the CRUD actions

RailsApp has an example, albeit in rails 3.2, https://github.com/RailsApps/rails3-bootstrap-devise-cancan, that uses devise and cancan

Hope this helps

OTHER TIPS

i wrote this link https://github.com/x1wins/tutorial-rails-rest-api#authorize

    class ApplicationController < ActionController::API
      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
    end
    
    # How to Use
    class PostsController < ApplicationController
        before_action only: [:update, :destroy, :destroy_attached] do
          is_owner_object @post ##your object
        end
    end        
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top