nicoolas25
11/13/2012 - 1:40 PM

Allow only one connection before confirmation with Devise.

Allow only one connection before confirmation with Devise.

module OneConnectionBeforeConfirm
  extend ActiveSupport::Concern

  included do
    before_create :generate_confirmation_token
    after_create  :send_on_create_confirmation_instructions
  end

  # This actions are not properly trigerred because of the rest of our modifications.
  before_create :generate_confirmation_token
  after_create  :send_on_create_confirmation_instructions

  # Alias the original devise's confirmed? method
  alias :strictly_confirmed? :confirmed?

  # Override the confirmed? method, this will allow an unconfirmed user to sign in
  # just after sign up.
  def confirmed?
    sign_in_count < 2 || strictly_confirmed?
  end

  protected

  # Must use the strictly_confirmed? method here to avoid confirmation issues.
  def pending_any_confirmation
    if (!strictly_confirmed? || pending_reconfirmation?)
      yield
    else
      self.errors.add(:email, :already_confirmed)
      false
    end
  end
end

class User
  include Mongoid::Document
  devise [...], :confirmable
  include OneConnectionBeforeConfirm
end