Question

We have an existing user base and are adding email confirmation. Confirmation is optional, but will allow additional features. Users are not required to confirm. I've added the confirmable module and ran migrations. Confirmation works as advertised.

But, users cannot login since they are not confirmed. All current users have nil confirmation values, which is what we want (users can go back and confirm their email at any time). I've followed all the Devise wiki articles and set allow_unconfirmed_access_for in the initializer:

config.allow_unconfirmed_access_for = 10.years 

I've also tried setting it in our user model as well:

devise :confirmable, allow_unconfirmed_access_for: 10.years

I've also tried using other values (1.year, 500.days, etc.)

My SessionsController, which does not differ much from Devise's method (here on github)

class Users::SessionsController < Devise::SessionsController
  respond_to :json

  def new
    redirect_to "/#login"
  end

  def create
    resource = warden.authenticate(auth_options)
    if !resource
      render json: {error: "Invalid email or password" }, status: 401 and return
    end

    sign_in(resource_name, resource)
    render "sign_in", formats: [:json], locals: { object: resource }
  end
end

Devise's response:

{"error":"You have to confirm your account before continuing."}

Devise 2.1.2 with Rails 3.2.9.

Was it helpful?

Solution

The Devise team have released a version (2.2.4) that supports nil as a valid value for allow_unconfirmed_access_for, meaning no limit. Issue: https://github.com/plataformatec/devise/issues/2275

You can now do:

config.allow_unconfirmed_access_for = nil 

OTHER TIPS

I simply needed to do this in my User model, instead of using allow_unconfirmed_access_for:

  protected
    def confirmation_required?
      false
    end

I've got the same issue: after turning on devise confirmations previously created accounts are unable to login.

The reason is here:

def confirmation_period_valid?
  self.class.allow_unconfirmed_access_for.nil? || (confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago)
end

Old accounts have confirmation_sent_at set to nil, that's why they are unable to log in.

One solution is to force confirmation_sent_at like that:

update users set confirmation_sent_at=created_at where confirmation_sent_at is NULL;

You can do it manually, or create a migration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top