1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionview/lib/action_view/helpers/csrf_helper.rb
Genadi Samokovarov a58db74c4f Don't expect defined protect_against_forgery? in {token,csrf_meta}_tag
The `#csrf_meta_tags` and `#token_tag` Action View helper methods are
expecting the class in which are included to explicitly define the
method `#protect_against_forgery?` or else they will fail with
`NoMethodError`.

This is a problem if you want to use Action View outside of Rails
applications. For example, in #34788 I used the `#button_to` helper
inside of the error pages templates that have a custom
`ActionView::Base` subclass, which did not defined
`#protect_against_forgery?` and trying to call the button failed.

I had to dig inside of Action View to find-out what's was going on. I
think we should either set a default method implementation in the
helpers or check for the method definition, but don't explicitly require
the presence of `#protect_against_forgery?` in every `ActionViews::Base`
subclass as the errors are hard to figure out.
2018-12-27 11:33:54 +02:00

35 lines
1.2 KiB
Ruby

# frozen_string_literal: true
module ActionView
# = Action View CSRF Helper
module Helpers #:nodoc:
module CsrfHelper
# Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
# request forgery protection parameter and token, respectively.
#
# <head>
# <%= csrf_meta_tags %>
# </head>
#
# These are used to generate the dynamic forms that implement non-remote links with
# <tt>:method</tt>.
#
# You don't need to use these tags for regular forms as they generate their own hidden fields.
#
# For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the
# "X-CSRF-Token" HTTP header. If you are using rails-ujs this happens automatically.
#
def csrf_meta_tags
if defined?(protect_against_forgery?) && protect_against_forgery?
[
tag("meta", name: "csrf-param", content: request_forgery_protection_token),
tag("meta", name: "csrf-token", content: form_authenticity_token)
].join("\n").html_safe
end
end
# For backwards compatibility.
alias csrf_meta_tag csrf_meta_tags
end
end
end