Question

I want to design an API in Rails that requires actions like Create, Update and Delete to be readonly for certain controllers, and open to the public for others (eg, comments on an article should be open but editing that article should require API authentication)

I know how to do the authentication part, what I don't know how to do is the "read only" part or the "you have permission to create a comment but not delete it" part.

Does any one have any resources, tips, tricks or github repositories that do this or something similar to this?

Was it helpful?

Solution

You are needing to do authorization. Look at Pundit for a scalable solution https://github.com/elabs/pundit

I had an app for a while that only needed a little bit of control as there were only a few methods on 2 controllers that were limited. For those i just created a before_filter and method to control the authorization.

The code below would allow everyone to do index and only allow users with a role attribute that has a value of "admin" to do any other action in the controller. You can also opt to raise an unauthorized error or raise an error message instead of redirecting. There are articles (probably books) written on the security side of the house for whether you should give users notice if they are not authorized to do something (which means they can infer that there is something there that someone can do at the uri)

SomeController < ApplicationController
  before_filter check_authorized, except [:index]

  def index
    ....stuff that everyone can do
  end

  def delete
    ....stuff only admin can do
  end

  private

  def check_authorized
    redirect_to root_path unless current_user.admin?
  end
end

Of course you will need devise or a current_user method and a method on user that checks admin

class User < ActiveRecord::Base
  def admin?
    if self.role == "admin"
      true
    else
      false
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top