Search code examples
ruby-on-railsrubyruby-on-rails-4cancan

rails 4 user authentication


I'm using devise with my rails 4 app to handle the authentication, and no problems there. However, I want to make sure a logged in user can only view / edit (via the show and update actions) the items that his user owns (that are linked to his user_id).

I think I could hack something to make this all work by checking the current_user.id, but many users in Stackoverflow and other places say to use cancan-- however it appears cancan is dead and gone, and there's a replacement called cancancan, which may be ok, but I don't know.

Is there a standard way to do this in Rails 4, or is the best route to still use a third party gem like cancancan? Is there a better gem?


Solution

  • I've been using Pundit instead of Cancan for the last few projects I've done. It is lightweight, flexible and easy to use. Here's the link: https://github.com/elabs/pundit

    In regards to your question, you will create policies for each model. For each action you define a method. It's super simple and explained on the link I've attached. Here as an example you have update in your model (models/post.rb):

    def update
      @post = Post.find(params[:id])
      authorize @post
       if @post.update(post_params)
         redirect_to @post
       else
         render :edit
       end
    end
    

    Call authorize to define permissions.

    In your policies/post.rb:

    class PostPolicy < Struct.new(:user, :post)
      def update?
       user.admin? or not post.published?
      end
    end
    

    That returns true or false. In your case if you want to check if the user is a owner you can place the following if statement:

     if user.admin? || user.owner_of?(post)
    

    You get the idea. You can also define scopes, etc.