Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if user is active before allowing user to sign in with devise (rails)

I am using devise and created a User field called :active which is either true or false. I have to manually make the user active (true) before the user is allowed to log in. At least that is the intent. I have tried this...

class SessionsController < Devise::SessionsController
  # POST /resource/sign_in
  def create
    "resource/signin CREATE"
    self.resource = warden.authenticate!(auth_options)
    unless resource.active?
      sign_out
      redirect_to :sorry_not_active_url
      return
    end
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)
    respond_with resource, :location => after_sign_in_path_for(resource)
  end  
end

However this does not catch all the places where a user can log in, for example, when a user changes their password, the site automatically logs them in automatically after. However, if the user is not active, I do not want them to be allowed to log in, but rather be redirected to a sorry_not_active_url.

What would be the best way to prevent the user from signing in if the user is not active?

Thank you.

like image 949
user2012677 Avatar asked Apr 07 '13 16:04

user2012677


2 Answers

Add these two methods to your user model, devise should pick them up automatically - you should NOT need to extend Devise::SessionsController

def active_for_authentication?
  super && self.your_method_for_checking_active # i.e. super && self.is_active
end

def inactive_message
  "Sorry, this account has been deactivated."
end
like image 90
house9 Avatar answered Oct 22 '22 09:10

house9


Devise (If you have devise 3.2+) now support block parameter in (session) create

# assuming this is your session controller

class SessionsController < Devise::SessionsController

def create
  super do |resource|
     unless resource.active?
      sign_out
      # you can set flash message as well.
      redirect_to :sorry_not_active_url
      return
    end
  end
end
like image 7
Viren Avatar answered Oct 22 '22 09:10

Viren