Undelete acts_as_paranoid deleted user on devise s

2019-05-14 12:35发布

问题:

I have a Rails 3.1.3 app which uses devise for users authentication and soft-deletes them with acts_as_paranoid. I want the accounts to be undeleted upon password recreation, user sign up and user sign in, so if they provide a deleted email, I grab that account, make it live again, and then continue with the action (password recreation, or sign in).

But in the Users::SessionsController#create action, after undeletion of the user it gets an Unauthorized error (but the user should now be visible). The code is:

def create
  # Take into account acts_as_paranoid deleted users
  resource = resource_class.only_deleted.find_by_email(params[resource_name][:email])
  resource.undelete! if resource

  resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
  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

If I add a resource.reload call after the undeletion it doesn't change anything. And if I sign in again, user gets normally signed in, as it got undeleted in the previous attempt.

Why is this happening? How can I get it undeleted and signed in in a single create call?

回答1:

Solved it with following code snippet:

def create
  # Take into account acts_as_paranoid deleted users
  if (resource = resource_class.only_deleted.find_by_email(params[resource_name][:email]))
    resource.undelete!
    # Copied from Warden::Strategies database_authenticatable:
    sign_in resource if resource.valid_password?(params[resource_name][:password])
  end
  super
end