Created
October 11, 2013 03:10
-
-
Save blacklee/6929009 to your computer and use it in GitHub Desktop.
Avoid user post a form to rails application repeated
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form method='post'> | |
<%= token_field %> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment