Controlling Information Access with the Rails Action Controller
(Page 1 of 5 )
In this conclusion to a four-part series on the Rails Action Controller, you will learn how to restrict access to controller methods, use filters for authentication, and more. This article is excerpted from chapter four of the
Rails Cookbook, written by Rob Orsini (O'Reilly, 2007; ISBN: 0596527314). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
4.12 Restricting Access to Controller Methods
Problem
By default, all public methods in your controller can be accessed via a URL. You have a method in your controller that is used by other methods in that controller or by subclasses of that controller. For security reasons, you would like to prevent public requests from accessing that method.
Solution
Use Ruby’s private or protected methods to restrict public access to controller methods that should not be accessible from outside the class:
app/controllers/controllers/employee_controller.rb:
class EmployeeController
< ApplicationController
def add_accolade
@employee = Employee.find(params[:id])
@employee.accolade += 1
double_bonus if @employee.accolade > 5
end
private
def double_bonus
@employee.bonus *= 2
end
end
Discussion
Ruby has three levels of class method access control. They are specified with the following methods: public, private, and protected. Public methods can be called by any other object or class. Protected methods can be invoked by other objects of the same class and its subclasses, but not objects of other classes. Private methods can be invoked only by an object on itself.
By default, all class methods are public unless otherwise specified. Rails defines actions as public methods of a controller class. So by default, all of a controller’s class methods are actions and available via publicly routed requests.
The solution shows a situation in which you might not want all class methods publicly accessible. The double_bonus method is defined after a call to the private method, making the method unavailable to other classes. Therefore, double_bonus is no longer an action and is available only to other methods in the Employee controller or its subclasses. As a result, a web application user can’t create a URL that directly invokes double_bonus.
Likewise, to make some of your class’s methods protected, call the protected method before defining them. private and protected (and, for that matter, public) remain in effect until the end of the class definition, or until you call one of the other access modifiers.
See Also
Next: 4.13 Sending Files or Data Streams to the Browser >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the Rails Cookbook, written by Rob Orsini (O'Reilly, 2007; ISBN: 0596527314). Check it out at your favorite bookstore. Buy this book now.
|
|