Using Kemal CSRF handler with Crinja

2018 05 19 No Comments

I assume that you are using kemal, kemal-session and kemal-csrf. Require them and use add_handler to handle requests.

Default input name is authenticity_token so I used it.

require "kemal"
require "kemal-session"
require "kemal-csrf"

add_handler CSRF.new(
  allowed_methods: ["GET", "HEAD", "OPTIONS", "TRACE"],
  error: ->myerrorhandler(HTTP::Server::Context)
)

def myerrorhandler(env)
  if env.request.headers["Content-Type"]? == "application/json"
    {"error" => "csrf error"}.to_json
  else
    "No token!"
  end
end

Kemal.run

Create a function to use it in templates

def csrf_tag(env)
  Crinja.render("<input type='hidden' name='authenticity_token' value='#{env.session.string?("csrf")}'/>")
end

Send the csfr_tag function to your template

get "/" do |env|
  csrf_tag = csrf_tag(env)

  template = c.get_template("index.html")
  template.render({ "csrf_tag_fn" => csrf_tag })
end

You are ready to use it in your index.html!

{{ csrf_tag_fn | safe }} # => gives html result
{{ csrf_tag_fn }} # => gives plain result

Leave a Reply

Your email address will not be published. Required fields are marked *