Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop soft deleted user's login with Devise

I currently use Devise for user registration/authentication in a Rails project. When a user wants to cancel their account, the user object is soft deleted in a way like the following.

How to "soft delete" user with Devise

My implmenetation has a small difference this way. User model has an attribute 'deleted_flag'. And, soft_delete method executes "update_attribtue(:deleted_flag, true)"

But, I have to implment sign_in action. In my implmenetation is the following.

class SessionsController < Devise::SessionsController
  def create
    resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")    

    if resource.deleted_flag
      p "deleted account : " + resource.deleted_flag.to_s
      sign_out(resource)
      render :controller => :users, :action => :index
    else
      if is_navigational_format?
        if resource.sign_in_count == 1
          set_flash_message(:notice, :signed_in_first_time)
        else
          set_flash_message(:notice, :signed_in)
        end
      end
      sign_in(resource_name, resource)
      respond_with resource, :location => redirect_location(resource_name, resource)
    end
  end
end

I think this code has strange points.

If deleted user tries to sing in, the system permit logging and make log out immediately. And, the system cann't display flash[:alert] message...

I want to know two points.

  1. How do I implement to prohibit deleted users to login?
  2. How do I implement to display flash[:alert] when deleted user tries to login?
like image 861
tbl Avatar asked Jun 23 '11 12:06

tbl


2 Answers

To stop a user that has been 'soft deleted', the best way is to overwrite the find_for_authentication class method on the user model. Such as:

Class User < ActiveRecord::Base
  def self.find_for_authentication(conditions)
    super(conditions.merge(:deleted_flag => false))
  end

This will generate a invalid email or password flash message by devise (because it cannot find the user to authenticate)

As far as your second question though, you'll need some for of method in your controller to add a particular flash message. However, in my opinion you should treat users that are 'soft' deleted the same as if they didn't exist in the database at all. Thus if they tried to log in, they should just get an valid email or password message.

like image 158
Kyle d'Oliveira Avatar answered Sep 19 '22 10:09

Kyle d'Oliveira


See my solution here: https://stackoverflow.com/a/24365051/556388 Basically you need to override the active_for_authentication? method on the devise model (User).

like image 29
iwiznia Avatar answered Sep 21 '22 10:09

iwiznia