Permalink
Browse files

Switch to non-guessable tokens for urls

  • Loading branch information...
1 parent 7179b2f commit 36dc18101bffdca6c7910e541c8e0434f6b199fa Michael Nutt committed Jul 9, 2009
View
4 app/controllers/hidims_controller.rb
@@ -6,15 +6,15 @@ def new
def create
@hidim = Hidim.new( params[:hidim] )
if @hidim.save
- redirect_to @hidim
+ redirect_to hidim_url(@hidim.token)
else
flash[:notice] = @hidim.errors[:torrent]
redirect_to "/"
end
end
def show
- @hidim = Hidim.find params[:id]
+ @hidim = Hidim.find_by_token(params[:id]) or raise ActiveRecord::RecordNotFound
end
def index
View
13 app/models/hidim.rb
@@ -7,18 +7,29 @@ class Hidim < ActiveRecord::Base
has_attached_file :png
has_attached_file :torrent
- attr_protected :featured
+ attr_accessible :torrent
validates_attachment_content_type :torrent, :content_type => ['application/x-bittorrent', 'application/x-torrent'],
:message => "The file you uploaded does not appear to be a torrent."
validates_attachment_presence :torrent, :message => "Please select 'Browse' to select a file before submitting."
validates_attachment_size :torrent, :less_than => 300.kilobytes, :message => "Please select a file smaller than 250KB."
+ validates_presence_of :token
+ validates_uniqueness_of :token
+ before_validation_on_create :generate_token
before_create :set_content
before_create :convert_to_png
named_scope :featured, :conditions => {:featured => true}
+ def generate_token
+ self.token = rand(36**8).to_s(36) if self.new_record? and self.token.nil?
+ end
+
+ def to_yaml
+ self.token
+ end
+
def name
self.torrent_file_name
end
View
10 db/migrate/20090709011003_add_token_to_hidims.rb
@@ -0,0 +1,10 @@
+class AddTokenToHidims < ActiveRecord::Migration
+ def self.up
+ add_column :hidims, :token, :string
+ add_index :hidims, :token
+ end
+
+ def self.down
+ remove_column :hidims, :token
+ end
+end
View
5 db/schema.rb
@@ -9,7 +9,7 @@
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20090704150028) do
+ActiveRecord::Schema.define(:version => 20090709011003) do
create_table "hidims", :force => true do |t|
t.datetime "created_at"
@@ -23,6 +23,9 @@
t.integer "png_file_size"
t.datetime "png_updated_at"
t.boolean "featured"
+ t.string "token"
end
+ add_index "hidims", ["token"], :name => "index_hidims_on_token"
+
end
View
10 spec/models/hidim_spec.rb
@@ -20,9 +20,15 @@
@hidim.png.should_not be_nil
end
- it "should not allow :featured to be set" do
- @hidim = Hidim.create!(@valid_attributes.merge(:featured => true))
+ it "should have a token" do
+ @hidim = Hidim.create!(@valid_attributes)
+ @hidim.token.size.should == 8
+ end
+
+ it "should not allow attributes to be set" do
+ @hidim = Hidim.create!(@valid_attributes.merge(:featured => true, :token => "foo"))
@hidim.featured.should_not be_true
+ @hidim.token.should_not == "foo"
end
end

0 comments on commit 36dc181

Please sign in to comment.