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

末鹿安然 提交于 2019-11-28 15:19:44
Paul Russell

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.

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)

Devise is an other excellent authentication gem that comes with email activation build in, perhaps you could give it a go.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!