【问题标题】:Ruby on Rails Devise Confirmation Token is nilRuby on Rails 设计确认令牌为零
【发布时间】:2016-02-20 19:27:03
【问题描述】:

我有一个用户模型(由$ rails g devise User 创建),它被设置为使用可确认(在模型和迁移中)。

创建用户时,未设置确认令牌(并且未发送确认电子邮件)。

这里是app/models/user.rb

class User < ActiveRecord::Base     
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable

  def password_required?
    super if confirmed?
  end

  def password_match?
    self.errors[:password] << "can't be blank" if password.blank?
    self.errors[:password_confirmation] << "can't be blank" if password_confirmation.blank?
    self.errors[:password_confirmation] << "does not match password" if password != password_confirmation
    password == password_confirmation && !password.blank?
  end

  # new function to set the password without knowing the current 
  # password used in our confirmation controller. 
  def attempt_set_password(params)
    p = {}
    p[:password] = params[:password]
    p[:password_confirmation] = params[:password_confirmation]
    update_attributes(p)
  end

  # new function to return whether a password has been set
  def has_no_password?
    self.encrypted_password.blank?
  end

  # Devise::Models:unless_confirmed` method doesn't exist in Devise 2.0.0 anymore. 
  # Instead you should use `pending_any_confirmation`.  
  def only_if_unconfirmed
    pending_any_confirmation {yield}
  end

    protected
    def confirmation_required?
      false
    end    
end

有什么想法吗?

【问题讨论】:

  • 您能展示您的user.rb 内容吗?还有助于了解您正在使用哪个 ORM(Mongoid、ActiveRecord)
  • 我已经添加了user.rb的内容。我正在使用 ActiveRecord。

标签: ruby-on-rails ruby devise devise-confirmable


【解决方案1】:

那是因为您要覆盖 confirmation_required? 以始终返回 false。

看看this

before_create :generate_confirmation_token, if: :confirmation_required?

仅当该方法返回 true 时才会生成令牌。

confirmation_required? 的默认行为是在记录未被确认时返回 true。

def confirmation_required?
  !confirmed?
end

【讨论】:

    【解决方案2】:

    为了补充@nbermudezs 的答案,添加了这个confirmation_required? 方法以防万一您想绕过某些用户的确认(例如具有特殊促销代码的用户或其他)

    如果您不希望有任何异常,我建议您只需删除这些代码行或注释它们,这样您就可以返回 devise_confirmable 的默认行为,这是您似乎想要的行为(也是由@nbermudezs)

    # def confirmation_required?
    #   false
    # end  
    

    【讨论】:

    • 谢谢西里尔。我完全删除了该方法,我的所有测试仍然通过 - 我认为没有必要。它在那里允许未经确认的访问;但是,我通过config/initializers/devise.rb 实现了这一点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多