DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Nic has posted 15 posts at DZone. View Full User Profile

Reset User Password Based On Another Users

05.04.2007
| 5832 views |
  • submit to reddit
        When you first create an app you might not have time *cough* to add special user password reset features. Especially if you don't have many users.

Here's a quick script to set the password of a user to another user (say a manually created user 'tester' with a known password).

namespace :user do
  desc 'Reset user (USER=username) password to that of username "tester" (or FROM=username env)'
  task :reset => :environment do
    reset_username = ENV['USER']
    unless ENV['USER']
      puts 'Require "USER=username" for user to be reset'
      next
    end
    reset_user     = User.find_by_username reset_username
    unless reset_user
      puts "Cannot find user: #{reset_username}"
      next
    end
    from_username  = ENV['FROM'] || 'tester'
    from_user      = User.find_by_username from_username
    unless from_user
      puts "Cannot find user: #{from_username}"
      next
    end
    
    reset_user.crypted_password = from_user.crypted_password
    reset_user.salt             = from_user.salt
    reset_user  .save
    puts 'User password reset'
  end
end