Sep
10th
Thu
10th
Adding Email and User Verification to AuthLogic
The Session
class UserSession < Authlogic::Session::Base
validate :check_if_verified
private
def check_if_verified
errors.add(:base, "You have not yet verified your account") unless attempted_record && attempted_record.verified
end
end
The Migration
class AddVerifiedToUser < ActiveRecord::Migration
def self.up
add_column :users, :verified, :boolean, :default => false
end
def self.down
remove_column :users, :verified
end
end
The User Controller
class UsersController < ApplicationController
...
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "Thanks for signing up, we've delivered an email to you with instructions on how to complete your registration!"
@user.deliver_verification_instructions!
redirect_to root_url
else
render :action => :new
end
end
end
The Verification Controller
class UserVerificationsController < ApplicationController
before_filter :load_user_using_perishable_token
def show
if @user
@user.verify!
flash[:notice] = "Thank you for verifying your account. You may now login."
end
redirect_to root_url
end
private
def load_user_using_perishable_token
@user = User.find_using_perishable_token(params[:id])
flash[:notice] = "Unable to find your account." unless @user
end
end
The User Model
class User < ActiveRecord::Base
acts_as_authentic
def deliver_password_reset_instructions!
reset_perishable_token!
Notifier.deliver_password_reset_instructions(self)
end
def verify!
self.verified = true
self.save
end
The Mailer
class Notifier < ApplicationMailer
default_url_options[:host] = "www.myurl.org"
def verification_instructions(user)
subject "Email Verification"
from "myurl"
recipients user.email
sent_on Time.now
body :verification_url => user_verification_url(user.perishable_token)
end
end
The Mailer View
Thank you for signing up for this site. Please click the following link to verify your email address:
<%= @verification_url %>
If the above URL does not work, try copying and pasting it into your browser. If you continue to have problems, please feel free to contact us.