Thursday, January 2, 2014

Changed Database... now gotta rake task for Heroku, but how?

Issue: Ok, so for Hacker Corral I never setup a "forgotten password" field in case, well, if someone forgets their password. To do this I need to setup an Authorization Token for each user so that when an email is sent, that specific token, which will be assigned to a user some random token (SecureRandom.urlsafe_base64) is sent with the email, rather than just the user id number.

Here's the problem: the database on my Heroku deployed version has actual users, not fake ones. On my "local" version it was ok for me to just rake db:reset my database... but I dont want to do that on a live site. Doing so would delete my users.

The solution: RAKE TASK it baby!! ;)

What this means: Essentially, it will go thru my database and generate the auth_token as needed for those users who dont have one. Pretty cool, no?


lib/tasks/rebuild_token_auth.rake

+namespace :user do
+  desc "Rebuild Auth-Tokens"
+  task :rebuild_auth_token => :environment do
+    User.transaction do
+      User.all.each { |u|
+        u.generate_token(:auth_token)
+        u.save!
+      }
+    end
+  end
+  
+end

The only "downside" of this particular implementation is that it the auth_token that will be sent to the user will be the same for any future request to update a password. I'll probably do something like running this particular task once a week/month/whatever to keep those auth_tokens changing, thus preventing someone who may get a user's token from being able to reset the password. 

Anyway, next steps are simple. 

1. git add .
2. git commit -m "rake take to generate auth token"

This is the part where one has to think about what is going on with heroku.

3. heroku run rake user:rebuild_auth_token
       this then populates the auth_token as needed
4. for good measure, heroku restart

Now we have populated what is needed, and the users who registered before I created the reset password option can do so as well, yay!

No comments:

Post a Comment