我正在嘗試爲更改用戶密碼創建一個單獨的視圖,我不知道該怎麼做。當我開始時,我意識到它需要不同的方法,並且可能會在模型中進行一些驗證。 我需要幫助,我該如何做到這一點。我不知道,我需要包含在控制器,模型和視圖中。 我也在執行「輸入舊密碼來創建新密碼」。Ruby on Rails身份驗證
-1
A
回答
0
我建議你遵循RESTful原則。
在您的項目中使用edit
和update
動作創建PasswordsController
。
然後用密碼更改的表單創建edit.html.erb
視圖。
模型中的驗證取決於您的要求。
以下是這上面的例子:
控制器:
class PasswordsController < ApplicationController
before_action :set_user
before_action :check_current_password, only: :update
def edit
end
def update
if @user.update password_params
flash[:success] = 'Password changed'
redirect_to user_path # Your user's profile for example
else
flash[:danger] = 'Error'
render :edit
end
end
private
def password_params
params.require(:user).permit(:password, :password_confirmation)
end
def set_user
@user = current_user # Your current user
end
def check_current_password
unless @user.authenticate(params[:current_password])
raise # I would recommend you to work with exceptions here because you interrupt the process.
# You can make it also a bit more specific if you define an exception class and just catch them.
end
rescue
flash[:danger] = 'Current password incorrect!'
redirect_to password_path(current_user) # Redirect back to the change page
end
end
查看:
<!-- HTML skeleton is in application.html.erb -->
<%= form_for @user, url: password_path, method: :patch do |f| %>
<%= text_field_tag :current_password %>
<%= f.text_field :password %>
<%= f.text_field :password_confirmation %>
<%= f.submit 'Change password' %>
<% end %>
假設你已經安裝了bcrypt
寶石和用戶模式有一個字段password_digest
,你的模型應該是這樣的。
型號:
class User < ApplicationRecord
has_secure_password
end
這是一個非常簡單的實現密碼更改的。我沒有測試過它,但它只是在這裏給你一個想法是如何工作的。
欲瞭解更多信息,請參閱https://gist.github.com/thebucknerlife/10090014#steps
+0
謝謝。但問題是用戶必須輸入當前密碼才能創建新密碼。 –
+0
然後添加另一個需要當前密碼的字段,並在更新之前在控制器中檢查它。我會更新我的答案。 – Tobias
相關問題
- 1. Ruby on Rails中的OpenID身份驗證
- 2. Ruby on Rails中最新的身份驗證
- 3. BizTalk Server 2009基本身份驗證到Ruby on Rails網站
- 4. 使用Ruby on Rails和Devise進行身份驗證
- 5. Ruby on Rails的採用OpenID身份驗證例外
- 6. Devise gem用戶身份驗證Ruby on Rails
- 7. 如何使用Ruby on Rails設置MSSQL用戶身份驗證?
- 8. 基本ruby on rails身份驗證問題
- 9. 帶骨幹的Ruby on Rails - 身份驗證
- 10. Ruby on Rails - 使用REST後端的Facebook身份驗證
- 11. Ruby On Rails身份驗證與設計和(監獄)回調
- 12. 在Ruby on Rails中使用Windows身份驗證
- 13. Rails身份驗證
- 14. Ruby on Rails,具有Twitter身份驗證和電子郵件身份驗證功能(autlogic和'誓言)
- 15. OpenID身份驗證進入奇怪的錯誤循環(Ruby on Rails,ruby-openid,open_id_authentication)
- 16. Ruby on Rails:「after_create」和驗證
- 17. Ruby on rails 3.2 accept_nested_attributes驗證
- 18. 跳過Ruby on Rails驗證
- 19. Ruby on Rails - 模型驗證
- 20. Ruby on Rails和驗證碼
- 21. rails 3身份驗證
- 22. Rails身份驗證問題
- 23. Rails Capistrano身份驗證失敗錯誤
- 24. Rails 3 - 只使用OpenID身份驗證
- 25. Pentaho的Acegi安全框架摘要式身份驗證和Ruby on Rails的
- 26. 在Ruby on Rails中進行身份驗證的最佳解決方案
- 27. 在php和Ruby On Rails應用程序之間通過身份驗證
- 28. 在Ruby on Rails中使用Devise插件進行身份驗證限制
- 29. 如何使用Ruby on Rails中的設計身份驗證進行確認
- 30. BCrypt身份驗證總是失敗RAILS
您是否在使用Devise?還是你推出了自己的認證系統? –
我已經通過自己的認證系統實施。 –