2017-10-21 89 views
1

当用户在登录屏幕上点击“忘记我的密码”时,它们被重定向到“/ password-reset”路径。现在,我正在尝试了解如何通过代码正确输入电子邮件以接收Twilio发送的短信。Twilio SMS忘记密码栏杆

<div class="form-group", style="width:50%;"> 
    <%= form_for @user, url: password_patch_path(current_user) do |f| %> 
    <div class="form-group"> 
     <%= f.label :email %> 
     <%= f.email_field :email, class: "form-control" %> 
    </div> 
    <%= f.submit "Get Confirmation Code", class: "btn btn-default" %> 
    <% end %> 
</div> 

我遇到的问题是@user是零,并且我不确定URL是否正确在表单的开头。对我来说,@user是无效的,因为没有人登录,所以我不知道应该是什么。

我的路线是

get '/password-reset', :to => 'passwords#edit', as: :password_reset 
post '/password-reset', :to => 'passwords#reset', as: :password_edit 
patch '/password-confirmation', :to => 'passwords#update', as: :password_patch 

和我的密码控制器看起来像

class PasswordsController < ApplicationController 
before_action :authenticated?, only: [:edit, :update] 

def reset 
ConfirmationSender.send_confirmation_to(current_user) 
redirect_to new_confirmation_path 
end 

def edit 
@user = current_user 
end 

def update 
    if passwords_not_empty? && passwords_equal? 
    current_user.update(password_params) 
    redirect_to users_dashboard_path(current_user.username), success: "Password Updated" 
    session[:authenticated] = false 
    else 
    redirect_to password_edit_path(current_user.username), warning: "Error, please try again." 
    end 
end 

private 

    def password_params 
    params.require(:user).permit(:password, :password_confirmation) 
    end 

    def passwords_not_empty? 
    params[:user][:password].length > 0 && params[:user][:password_confirmation].length > 0 
    end 

    def passwords_equal? 
    params[:user][:password] == params[:user][:password_confirmation] 
    end 

    def authenticated? 
    render :file => "#{Rails.root}/public/404.html", :status => 404 unless session[:authenticated] 
    end 
end 

回答

1

你是正确的,就没有current_user如果用户忘记了他/她的密码。我会重新设计如下:

PasswordsContoller

class PasswordsController < ApplicationController 
    before_action :authenticated?, only: [:update] 

    def reset 
    @user = User.find_by(email: params[:user][:email]) 
    if @user.present? 
     ConfirmationSender.send_confirmation_to(@user) 
     redirect_to new_confirmation_path 
    else 
     redirect_to password_reset_path, warning: "Email not found." 
    end 
    end 

    def edit 
    @user = User.new 
    end 

... 

end 

<div class="form-group", style="width:50%;"> 
    <%= form_for @user, url: password_edit_path do |f| %> 
    <div class="form-group"> 
     <%= f.label :email %> 
     <%= f.email_field :email, class: "form-control" %> 
    </div> 
    <%= f.submit "Get Confirmation Code", class: "btn btn-default" %> 
    <% end %> 
</div> 

edit方法种子用空白用户的形式。新的reset方法通过电子邮件查找用户,并在找到用户时发送令牌。如果没有,则显示未找到电子邮件的电子邮件并重定向回忘记的密码表单。

这也使表单使用正确的路径请求密码确认。

+0

谢谢汤姆!真的很感谢快速帮助。 – Sam

+0

没问题。不要害怕投票回答你觉得有帮助的答案。 –