Automatically Generating User Passwords with Devise

This article will discuss how to bypass password and password confirmation in the registration process and send a password through email when a user registers themselves.

First, create a new project.

1
2
rails new password_mailer
rails db:create db:migrate

Add devise gem to your project from this guide.

Now, add application-wide authentication.

1
2
3
4
5
# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

Generate a welcome controller.

1
rails g controller Welcome index

Configure routes.

1
2
3
# config/routes.rb

root to: 'welcome#index'

Generate a Mailer.

1
rails g mailer UserMailer send_password

Put the following code in app/mailers/user_mailer.rb:

1
2
3
4
5
6
7
8
class UserMailer < ApplicationMailer
 def send_password(user, password)
   @greeting = 'Hi'
   @password = password

   mail to: user.email
 end
end

In app/views/user_mailer/send_password.html.erb, put the following code:

1
2
3
4
5
# app/views/user_mailer/send_password.html.erb

<p>
  <%= @greeting %>, your password is <%= @password %>
</p>

Next, add a callback method that will run after the successful creation of a user.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/models/user.rb

after_create :send_password

def password_required?
 return false if new_record?
 super
end

def send_password
 pass = SecureRandom.hex(6)
 update(password: pass)
 UserMailer.send_password(self, pass).deliver_now
end

Now run the following command:

1
rails g devise:views

Remove password-related fields from app/views/devise/registrations/new.html.erb, then run.

1
rails s

Now the mailer should work properly.