Skip to content

RESTful_Authentication_example

mdarby edited this page Sep 12, 2010 · 19 revisions

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


  1. 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’
  2. 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.

Clone this wiki locally