Tuesday, September 25, 2007

Tutorial: Email Authentication When Signing Up

This is to help us remember how to do email authentication (emailing the password to the user, so that they can use that to log in) when signing up.

This assumes you're using the LoginGenerator.

1. In account_controller.rb, add this as a private method:

def generate_password(length = 8)
chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('1'..'9').to_a - ['o', 'O', 'i', 'I']
Array.new(length) { chars[rand(chars.size)] }.join
end


2. Then add/edit this method to the account_controller.rb

def signup
case @request.method
when :post
@password = generate_password

@user = User.new(@params['user'])
@user.password = @password

if @user.save
#@session['user'] = User.authenticate(@user.login, @params['user']['password'])
Notifier::deliver_account_details(@user, @password)
flash['notice'] = "An email has been sent."
redirect_to :action => "login"
end
when :get
@user = User.new
end
end


3. Make the notifier:

ruby script/generate model Notifier


4. Make the method that takes care of the emailing in notifier.rb:

class Notifier < ActionMailer::Base
def account_details(user,password)
# Email header info MUST be added here
@recipients = user.email
@from = "noreply@domain.com"
@subject = "Account Details"

# Email body substitutions go here
@body["username"] = user.login
@body["password"] = password
end
end


5. Create views/notifier/account_details.rhtml like this:

Hello <%= @username %>,

Your password is:
<%= @password %>

When you log in, please change your password for security.

Thank you,
Mailman


6. Finally, add this to the bottom of config/environment.rb:

ActionMailer::Base.smtp_settings = {
:address => "mail.domain.com",
:port => 25, #some servers use 26 - I got stuck here before!
:domain => 'www.domain.com',
:user_name => "info@domain.com",
:password => "pass",
:authentication => :login
}

No comments: