public
Rubygem
Description: A Ruby on Rails plugin that provides fine grained access control to RESTful resources in a Ruby on Rails 2.0+ project.
Home | Edit | New

RESTful_Authentication_example

Basic RESTful_Authentication / RESTful_ACL example start to finish.

Install RESTful_Authentication and RESTful_ACL plugins

cd vendor/plugins/
git clone git://github.com/technoweenie/restful-authentication.git
sudo gem install mdarby-restful_acl
Generate, migrate, start server

script/generate authenticated user sessions
rake db:migrate
script/server

Go to http://localhost:3000/users/new

generate a resource named ‘Page’ as an example object:

script/generate resource Page title:string
rake db:migrate
add to your app/controllers/application.rb controller file.

include AuthenticatedSystem
Add the following routes to the top of config/route.rb

  # For RESTful_Authentication
  map.activate '/activate/:activation_code', :controller => 'users', :action => 'activate', :activation_code => nil
  map.signup '/signup', :controller => 'users', :action => 'new'
  map.login '/login', :controller => 'sessions', :action => 'new'
  map.logout '/logout', :controller => 'sessions', :action => 'destroy'
  # For RESTful_ACL
  map.error '/error', :controller => 'sessions', :action => 'error'
  map.denied '/denied', :controller => 'sessions', :action => 'denied'
Example: app/views/sessions/error.html.erb

<h1 style='color:red'>ERROR!!!</h1>
Example: app/views/sessions/denied.html.erb

<h1 style='color:red'>Access Denied!</h1>
Add the following to application.html.erb:

<p style="color: green"><%= flash[:notice] %></p>
<p style="color: red"><%= flash[:error] %></p>
<% if logged_in? %>
  Currently logged in: <%= current_user.login unless current_user.blank? %><br />
  <%= link_to 'Log Out', logout_url %>
<% else %>
  <%= link_to 'Log In', login_url %>
<% end %>
Add these RESTful_ACL methods to your app/models/page.rb file:

#Please note that the contents of these methods are completely arbitrary.
#So long as they return a boolean true/false, they may contain anything you wish

belongs_to :author, :foreign_key => 'created_by_id', :class_name => 'User'

def is_updatable_by(user)
    user.eql?(author)
end

def is_deletable_by(user)
  user.eql?(author)
end

def self.is_readable_by(user, object = nil)
  true
end

def self.is_creatable_by(user)
   user.logged_in?
end

Add the below two lines into app/controllers/pages_controller.rb. The first line forces a user to login before editing, creating, or deleting a Page. The second line tells RESTful_ACL to check permission when doing these restricted actions:


before_filter :login_required, :except => ["index", "show"]
before_filter :has_permission?, :except => ["index", "show"]

Now your application is ready to test. A non logged in user cannot create a new Page, and editing/deleting an existing Page can only be done by the author of the Page.

Last edited by mdarby, Thu Nov 27 07:43:31 -0800 2008
Home | Edit | New
Versions: