Search code examples
ruby-on-railsemail-validationactivation

rails - email activation upon user signup


I want the user to click on an activation link before being "activated" or before they can log in with the email/password.

I am not using an gems and want to keep it that way. My problem is that after the user registers, they can login in without clicking on the activation code. I have an confirmation_token line and a confirmed line to the model.

user controller:

def create
  @user = User.new(params[:user])
 if @user.save
  render "root_path"
 else
  render "new"
 end
end

def confirmed
 user = User.find(:first, :conditions => {:confirmation_token => params[:confirmation_token]})
 if (!params[:confirmation_token].blank?) && user && !user.confirmed?
  user.confirmed!
  self.current_user = user
  flash[:notice] = "Thank you.  You account is now activated."
  redirect_to account_preference_path(current_user)
 else
  flash[:notice] = "Sorry we don't have your email in our database."
  redirect_to root_path
 end

end

user model:

def confirmed!
 self.confirmed = true
 self.confirmation_token = nil
 save(false) 
end

Am I missing anything? Thanks!

I know there are gems like devise, auth-logic, etc out there but I want to learn how to write it from scratch. Thanks.

EDIT:

session controller

def create
 user = User.authenticate(params[:email], params[:password])
 if user && user.confirmed == true
  cookies.permanent.signed[:remember_token]
  redirect_to account_path(user.id), :notice => "Welcome, #{user.first_name}"
 else
  flash.now.alert = "Invalid email or password."
  render "new"
 end
end

Solution

  • Of course, after much trial and tribulation, I figured it out. Before, I was redirecting the routes to a new controller where they can edit their password instead of just sending them to the route that just confirms the code. Silly mistake that cost me a lot of headache, but live and learn. Thanks everyone who looked into it.