我正在尝试为更改用户密码创建一个单独的视图,我不知道该怎么做。当我开始时,我意识到它需要不同的方法,并且可能会在模型中进行一些验证。 我需要帮助,我该如何做到这一点。我不知道,我需要包含在控制器,模型和视图中。 我也在执行“输入旧密码来创建新密码”。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 - RESTful API身份验证
- 2. Ruby on Rails身份验证错误postgres
- 3. Ruby on Rails中的OpenID身份验证
- 4. Ruby On rails验证
- 5. Ruby on rails验证
- 6. OAuth 1.0a使用Ruby on Rails进行“单脚”身份验证
- 7. 带骨干的Ruby on Rails - 身份验证
- 8. BizTalk Server 2009基本身份验证到Ruby on Rails网站
- 9. 使用Ruby on Rails进行Windows身份验证
- 10. Ruby on Rails的采用OpenID身份验证例外
- 11. Ruby on Rails - 使用REST后端的Facebook身份验证
- 12. 使用Ruby on Rails和Devise进行身份验证
- 13. Ruby On Rails身份验证与设计和(监狱)回调
- 14. Devise gem用户身份验证Ruby on Rails
- 15. 在Ruby on Rails中使用Windows身份验证
- 16. Ruby on Rails身份验证设计或Authlogic
- 17. Ruby on Rails中最新的身份验证
- 18. 如何使用Ruby on Rails设置MSSQL用户身份验证?
- 19. 基本ruby on rails身份验证问题
- 20. Rails身份验证
- 21. Ruby on Rails,具有Twitter身份验证和电子邮件身份验证功能(autlogic和'誓言)
- 22. OpenID身份验证进入奇怪的错误循环(Ruby on Rails,ruby-openid,open_id_authentication)
- 23. Ruby on Rails jquery ajax验证
- 24. Ruby on Rails和验证码
- 25. Ruby on Rails - 模型验证
- 26. Ruby on Rails:“after_create”和验证
- 27. Ruby on rails 3.2 accept_nested_attributes验证
- 28. 字段验证Ruby on Rails
- 29. Ruby on Rails的password_confirmation验证
- 30. 跳过Ruby on Rails验证
您是否在使用Devise?还是你推出了自己的认证系统? –
我已经通过自己的认证系统实施。 –