Search code examples
ruby-on-railsrubydevise

Devise Log in using field from different table - Related to User


I have my log in set up with 3 fields, organization (string identificator), email and password.

My User model, has a column named organization_id, that identifies which organization he belongs.

I can already login, using the company id, on the log in form. However, I need to allow users to log in using the organization name. Information that belongs to the Organization model.

Is there anyway, that I can intercept the input from the user before it authenticates, So I can search the database using the organization name input, and replace it with the organization id, so it authenticates in a more friendly way?


Solution

  • What you want is probably modifying the find_for_database_authentication method that's included to the User when you use Devise.

    This is where the method is used when we try to find the resource and authenticate it -> https://github.com/plataformatec/devise/blob/master/lib/devise/strategies/database_authenticatable.rb#L10

    When we go and check it further we see that it actually uses find_for_authentication method from the Authenticatable module.

    Which in turn uses the find_first_by_auth_conditions method.

    All those calls pass the same keys which are used to find the resource.

    In the most straightforward scenario it's the :email key that is passed in the request params, but we can change it

    Let's modify the find_for_database_authentication method so that we first check the params and if :organization_name key (im assuming that't how the parameter is called) was passed then we will use this info to find the resource.

    def find_for_database_authnetication(conditions)
      if !condition[:organization_name].blank?
        org = Organization.find_by(name: conditions[:organization_name])
        org.users.find_by(conditions[:email])
      else
        super
      end
    end
    

    I'm writing that without actually testing it so take it with a grain of salt but you should have the general idea of how you can approach your problem.