Is a good idea create validators that checks if logged in user.id is the same of my row user_id?

StackOverflow https://stackoverflow.com/questions/13947146

Pregunta

I'm just unsure about the approach. Actually I've this situation:

User belongs_to Organization
Organization has_many User

Organization has_many MembershipCard
MembershipCard belongs_to Organization

Now, the User is allowed to create a new MembershipCard only if he sets Organization = User.organization (notice that users with higher privileges do not have this limitation).

Currently I handle everything on the controller, however I were thinking about making a validator that ensures Organization == current_user.Organization (UserSession.find.user)

Is it a good idea? It looks good for me but I'm really afraid of hardly breaking MVC pattern without a good reason.

¿Fue útil?

Solución

This is a perfect time/place/example for you to think on Authorization as well not just Authentication (authlogic).
With the gem declarative_authorization its a child's play to do this. You could just simply specify rules in the authorization rules:

authorization do
  role :user do
    has_permission_on :membership_cards, :to => :create do
      if_attribute :organization => is {user.organization}
    end
  end
end

See Railscast - #188 about using these gems together.

====== After update on question information: ======

"CanCan was inspired by declarative_authorization and aegis" - from github-cancan

I looked it up how would you define such a rule with CanCan and there is a snippet on the page defining abilities for CanCan

class Ability
  def initialize(user)
    user ||= User.new # guest user (not logged in)
    can :create, MembershipCard do |card|
      card.organization.user == user
    end
  end
end

You still need to customize it for your enviorement, but it should guide you to the solution.

See Railscast - 192 about using CanCan.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top