簡體   English   中英

Rails Devise:設置密碼重置令牌並重定向用戶

[英]Rails Devise: Set password reset token and redirect user

在我的某個用例的應用程序中,我創建了一個新用戶(以編程方式設置密碼)並向他們發送確認 email。

我希望他們能夠在確認后立即更改密碼(無需進入系統生成的我不想發送給他們的密碼)

實際上我想
1) 系統使用生成的密碼創建一個新的用戶帳戶。
2) 系統發送確認 email。
3)用戶點擊確認並被重定向輸入他們的密碼(有效地將他們發送到URL,如下所示)

<a href="http://localhost:3000/users/password/edit?reset_password_token=v5Q3oQGbsyqAUUxyqLtb">Change my password</a>

任何幫助/指針都會很棒。

一種簡單的方法,用戶只需一步即可使用您建議的鏈接確認 email 地址並設置初始密碼...

發送一個您的應用生成的 email,包括一個 reset_password_token,並考慮用戶擁有該令牌確認該 email 地址的有效性。

在系統帳戶生成代碼中,假設用戶 model 設置為:recoverable 和:database_authenticable Devise 模塊...

acct = User.new
acct.password = User.reset_password_token #won't actually be used...  
acct.reset_password_token = User.reset_password_token 
acct.email = "user@usercompany.com" #assuming users will identify themselves with this field
#set other acct fields you may need
acct.save

使用戶在設置初始密碼時更清楚地看到 devise 重置密碼視圖。

意見/設計/密碼/edit.html.erb

...
<%= "true" == params[:initial] ? "Set your password" : "Reset your password" %>
...  

生成的 Email

Hi <%= @user.name %>
An account has been generated for you.
Please visit www.oursite.com/users/password/edit?initial=true&reset_password_token=<%= @user.reset_password_token %> to set your password.

無需在您的用戶 model 中包含可確認的 Devise 模塊,因為如果沒有 email 中的 reset_password_token,您的應用創建的帳戶將無法訪問。

Devise 將處理提交並清除 reset_password_token 字段。

有關reset_password_token方法和朋友的詳細信息,請參見devise_gem_folder/lib/devise/models/recoverable.rbdatabase_authenticatable.rb

如果您想使用 Devise :confirmable模塊而不是這種方法,請參閱Devise wiki 頁面

在 Rails 4.1 中,對 Anatortoise House 的回復進行了以下修改:

user = User.new
user.password = SecureRandom.hex #some random unguessable string
raw_token, hashed_token = Devise.token_generator.generate(User, :reset_password_token)
user.reset_password_token = hashed_token
user.reset_password_sent_at = Time.now.utc
user.email = 'user@usercompany.com'
user.save!
# Use a mailer you've written, such as:
AccountMailer.set_password_notice(user, raw_token).deliver

email 視圖有這個鏈接:

www.oursite.com/users/password/edit?initial=true&reset_password_token=<%= @raw_token %>

你可以打電話

user.send(:set_reset_password_token)

它可能不穩定,因為它是一種受保護的方法,但它可以適用於您的情況。 只需用測試覆蓋它。

(在 Devise v. 3.4 上測試)

這是我的郵件預覽片段

class Devise::MailerPreview < ActionMailer::Preview
  def reset_password_instructions
    user = User.last
    token = user.send(:set_reset_password_token)
    Devise::Mailer.reset_password_instructions(user, token)
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM