Filtering users who can log in using

I have a Rails application using Devise for authentication. Users are owned by dealers, and I want to prevent users who are disabled from logging in.

Is there an easy way to extend the authentication tool so that it does not include users from remote dealers? Perhaps using a named scope on a user?

Greetings

Tristan

+7
ruby-on-rails devise
source share
2 answers

It turns out that all I had to do was override the find_for_authentication method for my model:

class User < ActiveRecord::Base ... # Intercept Devise to check if DealershipUser Dealership is active def self.find_for_authentication(conditions) user = super return nil if user.is_a?(DealershipUser) && user.dealership.deleted? user end ... end 
  • Find the user in the usual way by calling super.
  • I use STI, so I check that the user is a DealershipUser, and then checks if the dealership (act_as_paranoid) has been deleted.
  • Return user.

This is a very specific solution for my scenario, but you can override find_for_authentication, but you like it if you return the user again.

+15
source share

A search of Stackoverflow.com gave me this question / answer: Custom authentication strategy for development

Basically, you should implement your own authentication strategy at the Warden level (which is the foundation of Devise). For my project, I did the following:

In config/initializers/devise.rb :

 Devise.setup do |config| config.warden do |manager| manager.default_strategies(:scope => :user).unshift :user_has_login_access end end Warden::Strategies.add(:user_has_login_access) do def valid? # pass the commit parameter as 'login' or something like that, so that this strategy only activates when the user is trying to login params[:commit] == 'login' end def authenticate! u = User.find_by_email(params[:user][:email]) if u.can_login? # retrieves boolean value stored in the User model, set wherever success! u else fail! "Account does not have login privilages." end end end 

You can read more about Warden custom strategies here: https://github.com/hassox/warden/wiki/Strategies

Hope this helps!

+4
source share

All Articles