Rails3, Authlogic and authenticates_many HOW TO code current_account_session helper method?

591 views Asked by At

Startup info:

  • My system don't user subdomains to get the right account!
  • I use Rails 3.0.x
  • I use authlogic 2.1.6
  • Model Account and model User
  • The cookie is present with name e.g. account_1_user_credentials and thats right!

Model Account.rb

class Account < ActiveRecord::Base
  authenticates_many :user_sessions, :scope_cookies => true
  has_many :users
end

Model User.rb

class User < ActiveRecord::Base
  acts_as_authentic do |c|
    c.validations_scope = :account_id
  end
  belongs_to :account
  ...
end

QUESTION: How can I code the application helper methods?

The documentation of Authlogic shows only the normal implementation without authenticates_many with scope_cookies:

class ApplicationController
  helper_method :current_user_session, :current_user

  private
    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.user
    end
 end

BUT how does the session_controller.rb (setting current_account_session) and application_controller.rb (implementation of def current_account_session ... end) look like?

1

There are 1 answers

0
Sébastien Grosjean - ZenCocoon On BEST ANSWER

If all your users get the same signin, you'll need to find the account based on the current_user. For this, you don't need to use authenticates_many in accounts. Just authenticate your user, then get it's account.

To setup your controller, look at the example https://github.com/binarylogic/authlogic_example/blob/master/app/controllers/user_sessions_controller.rb

Note: You can also check the views, ... for more inspiration.

That will allow you to authenticate the user and manage it's session. Once logged in, you need to be able to get his account, so you can scope other request per account.

To achieve this, add the current_account helper_method, by adding the following to your application_controller.rb

class ApplicationController
  helper_method :current_account

  private

    def current_account
      current_user.account
    end
    memoize :current_account
end

Don't forget to also add the default current_user and current_user_session helper_method.

This way, you can always find the current_account of the authenticated user, in all your controllers.