For a more recent discussion about a similar topic check this question out.
What\'s the best way to validate whether a particular user has ownership of a website?
Thanks a lot guys. I used a blend of Steve's and Amiel's suggestions to find a solution that works:
In the website model:
class Website < ActiveRecord::Base
require 'net/http'
belongs_to :user
before_create :generate_unique_id
# Validate unless already validated
def verify!
verify_unique_id unless self.verified == true
end
protected
# Generate a random string for unique_id
def generate_unique_id
self.unique_id = ActiveSupport::SecureRandom.hex(10)
end
def verify_unique_id
response = Net::HTTP.start(self.domain, 80) {|http| http.head("/# {unique_id}.html") }
self.verified = true if response.code == "200"
end
end
The controller is nearly unchanged from Steve's suggestion except for the part where the app finds the id of the website:
def verify
@website = Website.find_by_id(params[:website])
@website.verify!
respond_to do |format|
if @website.save && @website.verified == true
flash[:notice] = 'Site verified!'
format.html { redirect_to(websites_path) }
format.xml { head :ok }
else
flash[:notice] = 'Site verification failed!'
format.html { redirect_to(websites_path) }
format.xml { render :status => :unprocessable_entity }
end
end
end
Finally I have an index view of the user's websites (It's ugly but it does the job):
<% for website in @websites %>
<%= link_to "#{website.domain}", website %> |
<% if website.verified? %> VERIFIED |
<% else %> NOT VERIFIED
<%= link_to "Verify your website", verify_website_path(:website => website.id), :id => website.id %>
Verification key: <%= website.unique_id %>
<% end %><% end %>
<%= link_to "Add a website", new_website_path %>
Anyway, I put this through a few manual tests with one of my existing websites and it works without a problem. I still of course have to implement other validations but this was the one I really needed help on. Thanks guys!
Kenji