Reputation: 23
I have just begun Rails 3. I have generated the below code using the scaffold from Rails 3 on a table called "Logs".
The 'index' function below provides only the records associated with the current_user.id (from the session stored in the session table). The users records are only presented with the following route logged in as user = 3 (see index code below)
localhost:3000/logs
Problem: As a user, I can view a record which is not my record (being user=3) by editing the url manually to show any other record:
localhost:3000/logs/5 'this was entered by user.id=2'
Seeking Solution: How do I prevent manually hacking of the url to prevent a user viewing other user records?
class LogsController < ApplicationController
before_filter :login_required
def index @logs = Log.where(:user_id => current_user) respond_to do |format| format.html # index.html.erb format.xml { render :xml => @logs } end
Please ignore that the new function is missing from the create function below. The code below is to merely demonstrate how I put the user_id into the "Logs" table
def create @log = Log.new(params[:log]) @log.user_id = current_user.id respond_to do |format| if @log.save format.html { redirect_to(@log)} format.xml { render :xml => @log, :status => :created, :location => @log } else format.html { render :action => "new" } format.xml { render :xml => @log.errors, :status => :unprocessable_entity } end end
Upvotes: 2
Views: 1090
Reputation: 6711
The simplest solution would be to check in the show method if the Log to display really belongs to the logged in user:
def show
@log = Log.find(params[:id])
unless @log.user_id == current_user.id
flash[:error] = "unauthorized"
redirect_to :index
end
end
But you will soon have some more things you want to restrict access to, so you should look for an authentication plugin which allows to define the access rights in a declarative manner. Maybe this one: https://github.com/be9/acl9
Upvotes: 4