有关类似主题的最新讨论,请查看此问题.
验证特定用户是否拥有网站所有权的最佳方法是什么?
假设你有这个模型:
class User < ActiveRecord::Base has_many :websites end
为了确保用户确实拥有该网站,我考虑过进行电子邮件验证.示例:用户将example.com列为其网站,并将电子邮件发送至username@example.com.如果用户从example.com发送响应消息,则网站将进行验证.
问题在于,如果有一个网站,一大群人可以从具有该域名的网站发送电子邮件,例如gmail.com.我不希望用户将gmail注册为他们的个人网站.
因此,最好的方法是让用户在HTML中嵌入一些代码,rails应用程序确保代码存在.
你会怎么做呢?
这就是您如何使用RESTful样式的Google子域方法验证域.您将允许用户创建站点记录,该记录将保持未验证状态,直到用户稍后单击链接/按钮以在稍后验证域(以允许DNS传播).
此代码未经测试,但可以帮助您入门.
模型:
class Site < ActiveRecord::Base # schema # create_table "sites", :force => true do |t| # t.string "domain" # t.string "cname" # t.integer "user_id" # t.boolean "verified" # t.datetime "created_at" # t.datetime "updated_at" # end require "resolv" YOUR_DOMAIN = "example.com" belongs_to :user before_create :generate_cname attr_accessible :domain … # Validate unless already validated def validate! validate_cname unless self.verifed == true end protected # Generate a random string for cname def generate_cname chars = ('a'..'z').to_a self.cname = 10.times.collect { chars[rand(chars.length)] }.join end # Sets verifed to true if there is a CNAME record matching the cname attr and it points to this site. def validate_cname Resolv::DNS.open do |domain| @dns = domain.getresources("#{cname}.#{domain}", Resolv::DNS::Resource::IN::CNAME) self.verified = !@dns.empty? && @dns.first.name.to_s == YOUR_DOMAIN end end end
调节器
class SitesController < ActionController::Base # Usual RESTful controller actions # … def validate @site = current_user.sites.find(params[:id]) @site.validate! respond_to do |format| if @site.save && @site.verified flash[:notice] = 'Site verified!' format.html { redirect_to(@site) } format.xml { head :ok } else flash[:Error] = 'Site verification failed!' format.html { redirect_to(@site) } format.xml { render :status => :unprocessable_entity } end end end end
把它放在routes.rb中:
map.resources :sites, :member => { :validate => :put }
我将把这些观点作为练习留给你.