Search code examples
ruby-on-railsrubywarden

How to implement "forgot password" using Warden?


In the process of switching from Devise to directly using Warden.

How can I go about implementing a "forgot password" functionality that comes out of the box with Devise?

Is there a gem that can add this onto Warden?

PS. The reason for not using Devise is because of some customization needed that makes hacking Devise to make it work not worthwhile.


Solution

  • I don't know if there is a gem, but doing it yourself doesn't take to long. Assuming that each account has an email attached to it. Have a forgot password button that links to a page where the user will input there username or whatever information that is unique to the user and once the user submits the form. Send a new password to there email.

    Step-by-step:

    1. Create a forgot password button on your login page to link to a new forgot password page.
    2. Make the route, controller actions for the this new forgot password page.
    3. Make a form on the forgot password page that takes in a unique piece of information about the user. ex. username. This form will be a post request to a action in your controller that will email a new password to the user who has this username for example.

      This is what one of mine looked like:

      def emailor
      
        @user = User.find_by username: params[:user][:username] 
      
        random_password = Array.new(10).map { (65 + rand(58)).chr }.join
        @user.password = random_password
      
        if @user.save
          UserMailer.reset_password_email(@user.email, random_password ).deliver
          flash[:notice] = "Email has been sent";
          redirect_to root_path
        end
      
      end
      
    4. Make your mailer. This guide goes over how its done if you don't know. Mailers in Rails