Skip to content

Instantly share code, notes, and snippets.

@blacklee
Created October 11, 2013 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blacklee/6929009 to your computer and use it in GitHub Desktop.
Save blacklee/6929009 to your computer and use it in GitHub Desktop.
Avoid user post a form to rails application repeated
class ApplicationController < ActionController::Base
before_filter :check_token, :only => [some_actions...]
def check_token
token_file = File.join(Rails.root.to_s, "tmp", "tokens", params[:__token__])
if File.exists?(token_file)
require 'fileutils'
FileUtils.rm(token_file)
return true
end
false
end
end
module ApplicationHelper
def token_field
token = Digest::SHA1.hexdigest((Time.now.to_i + rand(0xffffff)).to_s)[0..39]
# by default, rails store session variables to browser's cookie, so session[:form_token] won't work
require 'fileutils'
token_dir = File.join(Rails.root.to_s, "tmp", "tokens")
FileUtils.mkdir_p(token_dir)
FileUtils.touch(File.join(token_dir, token))
hidden_field_tag(:__token__, token)
# you can ignore below codes
Thread.new do
now = Time.now.to_i
logger.info("check dir")
Dir.open(token_dir).entries.each do |entry|
next if entry.start_with?(".")
if now - File.ctime(entry).to_i > 1200
FileUtils.rm(File.join(token_dir, entry))
end
end
end
end
end
<form method='post'>
<%= token_field %>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment