using authentication with acts_as_authenticated

Problem
You want to use the easiest authentication method, in order to add users/permissions to your application.

Solution

  1. Install the act_as_authenticated plugin:
    script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_authenticated
  2. Generate controllers, models and migration:
    script/generate authenticated user account
  3. Add necessary user foreign keys in appropriate tables (ie customer in xxx_create_users.rb), plus other fields you may want to use in your user table (ie role):
    create table "users", :force => true do |t|
      t.column :login, :string
      ...
      t.column :role, :string, :default => 'C'
      ...
      end
      add_column :customers, :user_id, :integer
      ...
      def self.down
        ...
        remove_column :customers, :user_id
      end
  4. Run the migration:
    rake db:migrate VERSION=xxx
  5. Comment out from app/controllers/account_controller.rb the following:
    include AuthenticatedSystem
  6. Add it in the app/controllers/application.rb just under the class declaration.
  7. Add in application.rb (same as above) the following just after the session section:
    before_filter :login_required, :except => [:login, :signup, :logout]
  8. Comment out the default redirection after login and put your own (ie customers): in the account_controller.rb, just before
    the flash[:notice] = “Logged in successfully”.
    Also add the else for the the invalid login:

      redirect_back_or_default(:controller => 'customers', :action => 'list')
      flash[:notice] = "Logged in successfully"
    else
      flash[:notice] = "Invalid Login/Password!"
  9. Change the action in the signup and logout functions in the account_controller.rb file from index to login
  10. Add (optionally) more fields (role) in the signup page (app/views/account/signup.rhtml):
    
    
    
    <%= f.select :role, ['A','R','C'] %>
  11. Add restrictions for displaying records depending on user logged in, by using the conditions_for_collection of the activescaffold plugin in app/controllers/customers_controller.rb:
    def conditions_for_collection
      ['customers.user_id = (?)', current_user.id]
    end
  12. Add a menu page layout in app/views/layouts/_menu.rhtml:
  13. Add the call to the menu partial in the app/views/layouts/application.rhtml, just before the div with id=main :
    <%= render :partial => "layouts/menu"%>