2016-08-13 156 views
-1

我正在嘗試爲更改用戶密碼創建一個單獨的視圖,我不知道該怎麼做。當我開始時,我意識到它需要不同的方法,並且可能會在模型中進行一些驗證。 我需要幫助,我該如何做到這一點。我不知道,我需要包含在控制器,模型和視圖中。 我也在執行「輸入舊密碼來創建新密碼」。Ruby on Rails身份驗證

+0

您是否在使用Devise?還是你推出了自己的認證系統? –

+0

我已經通過自己的認證系統實施。 –

回答

0

我建議你遵循RESTful原則。

在您的項目中使用editupdate動作創建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

相關問題