Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Darcy Laycock September 23, 2010
file 78 lines (60 sloc) 1.831 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
# Wrapper class for password resets. OF DOOM.
class PasswordReset
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attr_accessor :email, :password, :password_confirmation
  attr_reader :user

  validates_presence_of :password, :password_confirmation, :if => :persisted?
  validates_presence_of :email, :user, :if => :new_record?
  
  validates_confirmation_of :password, :if => :persisted?
  

  def self.find(token)
    return if token.blank?
    user = User.find_using_perishable_token(token.to_s.strip)
    return if user.blank?
    self.new({}, user, true)
  end
  
  def initialize(params = {}, user = nil, persisted = false)
    @user = user
    @persisted = persisted
    self.attributes = params
  end

  def create
    valid?.tap do |value|
      user.reset_perishable_token!
      user.notify! :password_reset
    end
  end

  def update(attributes = {})
    return false if new_record?
    self.attributes = attributes
    valid?.tap { |v| user.update_password!(password) if v }
  end
  
  def save
    new_record? && create
  end
  
  def attributes=(attributes)
    attributes = (attributes || {}).symbolize_keys
    (attributes.keys & [:password, :password_confirmation, :email]).each do |v|
      send(:"#{v}=", attributes[v].to_s)
    end
    load_from_email if attributes[:email].present? && new_record?
  end
  
  def new_record?
    !persisted?
  end
  
  def persisted?
    @persisted
  end
  
  def id
    @user.try(:perishable_token)
  end
  
  protected
  
  def load_from_email
    @user = email.blank? ? nil : find_user_by_email(email)
  end
  
  def find_user_by_email(email)
    users = User.where(:email => email).all
    users.detect { |u| u.using_password? } || users.first
  end
  
end
Something went wrong with that request. Please try again.