Squadrons
Squadrons

Reputation: 2557

Rails routes and limiting authentication by association

I have a group of scoped resources.

scope '/:org_name', :as => 'organization' do
  resources :users
end

An organization has many users.

What I'd like is for my routes to look like this:

http://www.mysite.com/<organization-name>/users/1

This currently works fine.

The problem is that I can change the 'organization-name' part to anything I'd like, and it does not affect anything. If I put any string in there, I am still authenticated as that user.

what am I missing?

Upvotes: 0

Views: 68

Answers (1)

Novae
Novae

Reputation: 1171

As Deefour mentioned you will need to do this manually. The problem you're explaining here is authorization not authentication, take a look at a gem like CanCan

To explain it with an example. You would have to ensure the user is a member of the given organization. This could look something like this(given you have an current_user which represents the logged in user):

Controller:

class UsersController < ApplicationController
  before_filter :find_organization, :ensure_organization_membership, :only => :show

  def show
    @user = @organization.users.find(params[:id])
  end

  def find_organization
    @organization = Organization.find_by_name(params[:org_name])
  end

  def ensure_organization_membership
    # Make sure the current_user(Logged in user) is a member of the company before showing the user profile
    @organization.include(:users).member_of?(current_user)
  end
end

And in the model

class Organization
....
  def member_of?(user)
    users.includes?(user)
  end
...
end

Hope that helps.

Upvotes: 1

Related Questions