Skip to content

Instantly share code, notes, and snippets.

@kyontan
Created November 17, 2012 04:04
Show Gist options
  • Save kyontan/4093196 to your computer and use it in GitHub Desktop.
Save kyontan/4093196 to your computer and use it in GitHub Desktop.
Sinatraメモ
helpers do
include Rack::Utils
alias_method :h, :escape_html
def csrf_token
Rack::Csrf.csrf_token(env)
end
def check_csrf
unless params[Rack::Csrf.csrf_field] == session['csrf.token']
raise Rack::Csrf::InvalidCsrfToken
end
end
end
h "<html>" #=> &lt;html&gt;
configure do
logger = Logger.new("logs/access.log", "daily")
logger.instance_eval {
alias :write :'<<' unless respond_to?(:write)
}
use Rack::CommonLogger, logger
use Rack::Session::Cookie,
:key => 'rack.session',
:domain => 'test.monora.me',
:path => '/',
:expire_after => 60*60*24*7,
:secret => 'fueefuee'
use Rack::Csrf, :raise => true, :skip => ['POST:.*', 'PUT:.*', 'DELETE:.*']
end
before do
set :haml, :attr_wrapper => '"'
set :haml, :format => :html5
set :inline_templates => true
end
session["key"] = value
get '/' do
"#{request.path_info}" #=> '/'
"#{request.script_name}" #=> Pass to root directory of this application
end
["/a", "/b"].each do |path| #=> /a or /b
get path do
"fuee"
session["test"] = "fuee" #=> set session
end
get 'test/?' do #=> /test/ or /test
hoge...
end
get '/form' do
haml :test
end
before '/post'
check_csrf if request.post?
end
post '/post' do
nyan... #=> if there's no csrf_token -> raise Rack::Csrf::InvalidCsrfToken
end
error Rack::Csrf::InvalidCsrfToken do
#"CSRFが検出されました。"
end
__END__
@@test
!!!
%html
%form(action = "/post" method = "POST")
%input(type = "hidden" name = "_csrf" value = "#{csrf_token}")
%input(type = "submit")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment