Authentication & Authorisation

Using acts_as_authenticated

  1. Install acts_as_authenticated
  2. script/plugin source http://svn.techno-weenie.net/projects/plugins
    script/plugin install acts_as_authenticated
    

  3. Create a model for storing user accounts
  4. script/generate authenticated user account
    rake db:migrate
    
    BTW: created_at / updated_at

  5. Edit the controllers
  6. replace the include directive

    in app/controllers/account_controller.rb comment out the lines:
    include AuthenticatedSystem
    before_filter :login_from_cookie
    
    in app/controllers/application.rb add the lines (this goes inside ApplicationController body):
    include AuthenticatedSystem
    before_filter :login_from_cookie
    

    adjust redirect

    in app/controllers/account_controller.rb edit the index action:
    
    def index
      redirect_to(:action => 'signup') and return unless logged_in? || User.count > 0
      redirect_to :controller => 'coffee_house'
    end
    
    delete the dummy index: app/views/account/index.rhtml

  7. Edit the views
  8. Add a logout link

    in app/views/layouts/coffeehouse.rhtml
    
    <% if logged_in? -%>
      <%= link_to "Logout: #{current_user.login}", :controller => 'account', :action => 'logout' %>
    <% else -%>
      <%= link_to "Login", :controller => 'account', :action => 'login' %>
    <% end -%>
    

    Add a 'remember me' checkbox

    open app/views/account/login.rhtml and uncomment the checkbox code

  9. Restrict access
  10. logged in users can do anything others can only list coffee houses and view their details
    1. restrict everything -- add this line to app/controllers/application.rb, AFTER the cookie line (before_filter :login_from_cookie):
      before_filter :login_required
    2. allow login and signup -- add this line to app/controllers/account_controller.rb:
      skip_before_filter :login_required, :only => ['login', 'signup']
    3. allow index, list and show -- add this line to app/controllers/coffee_house_controller.rb:
      skip_before_filter :login_required, :only => ['index', 'list', 'show']