Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email confirmation in Rails without using any existing authentication gems/plugins

I'm working on this alerting service in Rails. And really, all I need to do is, when a user signs up, send a confirmation email to the user. And upon confirmation from the user, activate the user. I tried playing around with Matt Hooks' Authlogic email activation tutorial, but its really leading nowhere. So , any ideas how I can do this with minimum fuss ? Thanks !

UPDATE

So how i got devise to do the job for me is :

  1. Install the gem.

  2. Create a migration for devise's confirmable fields.

  3. Specify

    devise :confirmable in your model.

  4. Create a confirm method in the relevant controller(and a route for that method) which would update the confirmed_at attribute of the relevant model.

  5. The devise generator creates a few views for you, one which is confirmation_instructions.html.erb. Customize the path there.

I used Rails 2.3.2 and I 've used this method along with Authlogic's authentication and it worked well. I do plan to switch to devise completely.

In all honesty, I wanted to accept both answers (unfortunately I can't do that), but its just that the devise solution seemed a easier solution.

like image 377
Shreyas Avatar asked Oct 21 '10 06:10

Shreyas


2 Answers

Assuming given the title that you definitely want to avoid Devise, Authlogic and friends, here's what I think you need to do:

  • Create 'confirmation code' and 'confirmed' attributes in your user model.
  • Create a new controller method on your user controller that expects a user id and confirmation code, looks up the user and then checks if the code in the parameter matches the code stored in the DB. If so, it clears the code and sets confirmed = true.
  • Create a route that maps e.g. /users/1/confirm/code to your new controller method.
  • Create an ActionMailer template for the e-mail you want to send. This should accept a user as a parameter, and use the confirmation code of the user to send a mail containing a link to your new route.
  • Create an observer for your user model. If the record is created or the e-mail address modified, then generate a random confirmation code, set it into the model and clear the confirmed flag. Then trigger your ActionMailer.
  • Create a helper method which allows views to check if the current user is confirmed.
  • Use this method to enable/disable functionality as appropriate. Remember to protect your controller methods as appropriate as well as your view logic.
like image 165
Paul Russell Avatar answered Oct 25 '22 08:10

Paul Russell


You could also make use of scopes for selecting users.

class User < ActiveRecord::Base
  scope :certified, where(:certified => true)
end

And then in your code:

@user = User.certified.find_by_username(foo)
like image 6
user1017926 Avatar answered Oct 25 '22 10:10

user1017926