From aa3f7f764d0b405906031674511338183d94e683 Mon Sep 17 00:00:00 2001
From: Robin Ward <robin.ward@gmail.com>
Date: Tue, 4 Mar 2014 14:03:04 -0500
Subject: [PATCH] You can only reuse email tokens within 24 hours.

---
 app/models/email_token.rb       |  6 +++++-
 spec/models/email_token_spec.rb | 10 ++++++++++
 2 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/app/models/email_token.rb b/app/models/email_token.rb
index 86bc8f522..289ebd9ef 100644
--- a/app/models/email_token.rb
+++ b/app/models/email_token.rb
@@ -19,6 +19,10 @@ class EmailToken < ActiveRecord::Base
   end
 
   def self.valid_after
+    1.week.ago
+  end
+
+  def self.confirm_valid_after
     1.day.ago
   end
 
@@ -38,7 +42,7 @@ class EmailToken < ActiveRecord::Base
     return unless token.present?
     return unless token.length/2 == EmailToken.token_length
 
-    email_token = EmailToken.where("token = ? and expired = FALSE and created_at >= ?", token, EmailToken.valid_after).includes(:user).first
+    email_token = EmailToken.where("token = ? and expired = FALSE AND ((NOT confirmed AND created_at >= ?) OR (confirmed AND created_at >= ?))", token, EmailToken.valid_after, EmailToken.confirm_valid_after).includes(:user).first
     return if email_token.blank?
 
     user = email_token.user
diff --git a/spec/models/email_token_spec.rb b/spec/models/email_token_spec.rb
index a27d76dc6..c5da668cf 100644
--- a/spec/models/email_token_spec.rb
+++ b/spec/models/email_token_spec.rb
@@ -118,6 +118,16 @@ describe EmailToken do
         email_token.should be_confirmed
       end
 
+      it "can be confirmed again" do
+        EmailToken.stubs(:confirm_valid_after).returns(1.hour.ago)
+
+        EmailToken.confirm(email_token.token).should == user
+
+        # Unless `confirm_valid_after` has passed
+        EmailToken.stubs(:confirm_valid_after).returns(1.hour.from_now)
+        EmailToken.confirm(email_token.token).should be_blank
+      end
+
     end