当用户更改其电子邮件时重用activation_token和activation_digest

时间:2016-10-19 06:20:33

标签: ruby-on-rails

我的用户模型基于Hartl's Rails Tutorial.这是github page for the User model

当用户更改其电子邮件地址时,我希望他们返回帐户验证过程。是否可以重复使用attr_accessor: :activation_tokencolumn: activation_digest

我尝试创建以下方法:

user.rb
#the goal here is to reset activation_token and activation_digest
def deactivated
    update_attribute(:activated, false)
end

def create_activation_digest
    self.activation_token = User.new_token
    self.activation_digest = User.digest(activation_token)
end    

# These below are all pre-existing!

def send_activation_email
    UserMailer.account_activation(self).deliver_now
end


def User.digest(string)
  cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                BCrypt::Engine.cost
  BCrypt::Password.create(string, cost: cost)
end

def User.new_token
  SecureRandom.urlsafe_base64
end

def authenticated?(attribute, token)
    digest = send("#{attribute}_digest")
    return false if digest.nil?
    BCrypt::Password.new(digest).is_password?(token)
end

def activate
    update_attribute(:activated,    true)
    update_attribute(:activated_at, Time.zone.now)
end  

users_controller

# My Code
if !params[:user][:email].blank? 
  if @user.authenticate(params[:user][:current_password])
    params[:user].delete :current_password
    @user.update_attributes(email_user_params)
      if @user.save 
        @user.deactivated
        @user.create_activation_digest
        @user.send_activation_email
        log_out
        flash[:notice] = "Please check email pal"
        redirect_to root_url
      else 
        flash[:danger] = "Email Update Failed"
        redirect_to edit_user_email_path(@user)
      end
  else 
    flash[:danger] = "Password entered was incorrect"
    redirect_to edit_user_email_path(@user)
  end  
end  

#pre-existing 
class AccountActivationsController < ApplicationController
  def edit
    user = User.find_by(email: params[:email])
    if user && !user.activated? && user.authenticated?(:activation, params[:id])
      user.activate
      log_in user 
      flash[:success] = "Account activated!"
      redirect_to user
    else
      flash[:danger] = "Invalid activation link"
      redirect_to root_url
    end
  end
end    

这会发送一封激活电子邮件,它会更改activated属性,但是当点击该链接时,它只会从account_activations_controller向我提供失败错误消息,没有来自heroku的线索导致错误。

这是邮件

Hi <%= @user.name %>,

<%= edit_account_activation_url(@user.activation_token, email: @user.email) %>

1 个答案:

答案 0 :(得分:0)

这不起作用,因为我将该方法列为私有。公开它允许上面的代码工作。