我想设置一个注册过程,在该过程中,用户最初从站点请求更多信息,然后收到一封电子邮件,其中包含指向实际注册页面的链接。该链接应为随机生成的 URL,否则应限制对注册页面的访问。换句话说,不应该通过在浏览器中手动输入 URL 来访问注册页面。
我将不胜感激有关如何最好地实现这些功能的任何建议。
我是 Rails 的新手,所以如果这个问题是基本的或者已经被覆盖,我提前道歉。
我想设置一个注册过程,在该过程中,用户最初从站点请求更多信息,然后收到一封电子邮件,其中包含指向实际注册页面的链接。该链接应为随机生成的 URL,否则应限制对注册页面的访问。换句话说,不应该通过在浏览器中手动输入 URL 来访问注册页面。
我将不胜感激有关如何最好地实现这些功能的任何建议。
我是 Rails 的新手,所以如果这个问题是基本的或者已经被覆盖,我提前道歉。
您需要将随机令牌存储在数据库中。由于您将其发送到电子邮件地址,因此您可能还希望存储电子邮件,以便在他们注册时将其添加到您的用户模型中。以下是您可以做的一些相关部分(尽管您需要填补空白)。
本质上,您需要RegistrationToken.new(:email => "their email address")
在控制器中使用 生成注册令牌。
该模型实现了随机令牌的生成:
class RegistrationToken < ActiveRecord::Base
# the secret is just to make the random number generator more secure
@@secret = 6345
def initialize
# info at http://www.ruby-doc.org/core-1.9.3/Random.html
seed = Random.new().integer(1000000000) + @@secret
token = Random.new(seed).integer(1000000000);
# you might want to generate random numbers larger than 1 billion
# for more security (maybe with 64 bit integers?)
end
end
以及数据库的迁移:
class CreateRegistrationTokens
def change
create_table :products do |t|
t.string :email
t.integer :token
t.timestamps
end
end
end
然后你只需要设置你的控制器和视图。
对于您的注册控制器,您只需要以下内容:
class RegistrationsController < ActiveRecord::Base
def new
@registration_token = RegistrationToken.find(params[:token]).first
if @registration_token.nil?
raise 'Invalid token' # or whatever you want, eg. redirect to a page
end
# otherwise render the registration form (can do implicit render)
end
def create
@registration_token = RegistrationToken.find(params[:token]).first
if @registration_token.nil?
raise 'Invalid token' # or whatever you want, eg. redirect to a page
end
# otherwise create the user, eg.
User.create(params[:user].merge(:email => @registration_token.email))
@registration_token.destroy
end
end
上面的控制器操作基本上确保它们只有在数据库中找到匹配的令牌时才能注册。