Dominic Goulet
Dominic Goulet

Reputation: 8113

Rails security validations in controller?

I'm wondering if there is a best way to achieve this the rail way in my controller :

def show
  @article = Article.find(params[:id])
  # you can only view a public article or your own articles.
  @article = nil unless @article.public? || @article.owner?(current_user)
end

def edit
  @article = Article.find(params[:id])
  # you can only edit your own articles
  @article = nil unless @article.owner?(current_user)
end

I have a couple validations like this in my application and I can clearly see it's easy to miss one and give access to something that you should not!

Thanks

Upvotes: 1

Views: 107

Answers (2)

pcg79
pcg79

Reputation: 1283

Honestly, I'd use CanCan.

can :read, Article, public: true
can :manage, Article, owner_id: user.id

Upvotes: 1

Anatoly
Anatoly

Reputation: 15530

it is not the Rails way. one of the rails principles is take all the object manipulation on Model layer. Controllers mostly cares about overall authorizations/authentication/cache invalidation/cookie and sessions settings.

you can use associations and scope

class ArticlesControllers << ApplicationsController

  def show
    @article = current_user.articles.public.find(params[:id])
  end

end

class Article < ActiveRecord::Base
  scope :public, :where('public').is('true')

end

Upvotes: 1

Related Questions