Approach to limit the visibility of data
-
20-09-2019 - |
Question
Ok, suppose to have this db schema (relation):
|User | (1-->n) |Customer | (1-->n) |Car | (1-->n) |Support |
|--------| |---------| |-----| |-----------|
|id | | user_id | |Brand| |Description|
|username| |lastname | |PS | |Cost |
|password| |firstname| |seats| |hours |
|... | |.. | |... | |... |
The table User is generated by Authlogic.
I have 2 registred users, each one has his customers, etc. . With Authlogic I'm able to allow only authenticated users to reach controllers/views. That's fine, that's what Authlogic is made for.
Now I need to be sure that the user#1 will never reach informations belonging to customers of user#2.
In other words: if the user#1 goes to http://myapp.com/cars he will see the list of cars belonging to customers of user#1
if the car with the id=131 belongs to the customer of user#1, only user#1 have to be able to reach this information (http://myapp.com/car/1). If the user#2 insert in the browser the same link he doesn't have to be able to see this information.
Some people suggested me to create a relation between the user and each db table in order to check if a record is associated to the current_user.
What do you think? What is the best approach/solution?
Solution
So you have 2 things:
- In index page of cars controller only cars which belong to the current user should be shown.
- You want to restrict show pages to the owner.
As for the index i suggest something like:
def index
# find logic
@cars = Car.find(:all,:conditions=>{:customer_id => current_user.customers.collect(&:id)})
# whatever else
# ...
end
And the show page:
def show
# .....
# after the find logic
redirect_to :index unless current_user.customers.collect(&:id).include? @car.customer_id
# whatever else
# ...
end
This approach is ok for most of the cases, however a better approach for performance is to add a user_id column to the costumers table, this is called denormalization but it's acceptable for performance wise.