使用设计确认页面显示用户密码

我试图在Devise邮件程序发送的确认页面中显示用户密码。 确认页面是默认页面

Welcome test0@test.com! You can confirm your account email through the link below: Confirm my account 

但是,我希望有

 Welcome test0@test.com! Your password is currently DASADSADS You can confirm your account email through the link below: Confirm my account 

如何在视图中访问用户对象? 我是否需要使用自定义控制器覆盖邮件控制器? 如果是这样,我如何判断当前邮件的方法是什么(尝试查看文档但找不到任何线索)?

我注意到在视图中使用了@email和@resource。 我可以使用其中任何一种以未散列的forms访问当前密码吗?

请注意,我使用user.find(1).send_confirmation_instructions手动发送此电子邮件

虽然可以做到这一点,但我会强烈反对这样做。 专门使用散列密码,因此无法轻松重新创建密码。 将原始密码传回给用户将导致它以纯文本forms发送回来,这会破坏整个目的。 此外,用户不应该已经知道他们的密码(毕竟他们输入了两次)?!?

为此,您需要在注册create操作中捕获原始(未散列)密码,并在该点发送电子邮件(传递密码)。 您可以通过覆盖sign_up方法来执行此操作 – 您可以在初始化程序中执行此操作:

 class Devise::RegistrationsController < DeviseController def sign_up(resource_name, resource) sign_in(resource_name, resource) resource.unhashed_password = resource_params[:password] resource.send_confirmation_instructions end end 

或者,你可以从Devise::RegistrationsController派生一个新的控制器并在那里放置这个覆盖代码(推荐的方法 - 但是,然后再次,并不是真的推荐这个整个操作)。 您需要为此工作添加unhashed_password访问器:

 class User < ActiveRecord::Base attr_accessor :unhashed_password end 

然后您可以更新您的确认视图(在app/views/devise/mailer/confirmation_instructions.html.erb )以包含以下内容:

 

Your password is currently <%= @resource.unhashed_password %>

以加密forms设计保存密码:您可以使用以下方式解密密码:

生成新迁移:

 $ rails g migration AddLegacyPasswordToUser legacy_password:boolean invoke active_record create db/migrate/20120508083355_add_legacy_password_to_users.rb $ rake db:migrate 

在以下代码中使用legacy_password方法,您可以解密密码:

 class User < ActiveRecord::Base ... def valid_password?(password) if self.legacy_password? # Use Devise's secure_compare to avoid timing attacks if Devise.secure_compare(self.encrypted_password, User.legacy_password(password)) self.password = password self.password_confirmation = password self.legacy_password = false self.save! else return false end end super(password) end # Put your legacy password hashing method here def self.legacy_password(password) return Digest::MD5.hexdigest("#{password}-salty-herring"); end end 

您可以使用request.request_parameters [:user] [:password]来获取创建或更新操作的纯文本密码。