<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>XSRF Form</title>
  <link rel="stylesheet" href="../style.css">
</head>
<body class="container">

  <nav class="py-4">
    <a href=".">&laquo; Back to FileHandler</a>
  </nav>

  <section class="content">
    {% if 'key' in handler.args %}
      <h1>Success</h1>
      <p>Your key <code>{{ handler.get_arg('key') }}</code> has been submitted.</p>
    {% else %}
      <h1>XSRF template</h1>
      <p>The XSRF key here is inserted via Tornado templating.</p>
      <form method="POST">
        <div class="form-group">
          <label for="_xsrf">XSRF token from template</label>
          <input name="_xsrf" class="form-control" value="{{ handler.xsrf_token }}">
        </div>
        <div class="form-group">
          <label for="key">Input</label>
          <input name="key" class="form-control" placeholder="Enter a value">
        </div>
        <button type="submit" class="btn btn-primary">Submit template form</button>
      </form>
      <p>When you submit this form, the input will be sent as a POST request.
          If you modify the XSRF token, the result will fail.
      </p>

      <hr>
      <h1>XSRF AJAX</h1>
      <p>The XSRF key here is inserted via AJAX.</p>
      <form method="POST" class="ajax">
        <div class="form-group">
          <label for="key">Key</label>
          <input name="key" class="form-control" placeholder="Enter a value">
        </div>
        <button type="submit" class="btn btn-primary">Submit AJAX form</button>
      </form>
      <script src="../ui/jquery/dist/jquery.min.js"></script>
      <script>
        // Disallow form submission until XSRF is enabled
        var $forms = $('.ajax')
          .on('submit.no-xsrf', function (e) { e.preventDefault() })
        $.get('xsrf', function (token) {           // Get the XSRF token via AJX
          var $xsrf = $('<input>').attr({         // Create a form input field
            // type: 'hidden',
            class: 'form-control',
            name: '_xsrf',                        // called _xsrf
            value: token                          // and add the XSRF token value.
          })
          $forms.prepend($xsrf)                   // Add the input field to all forms
            .off('submit.no-xsrf')                // and re-enable submission
        })
      </script>
      <p>When you submit this form, the input will be sent as a POST request.
          If you modify the XSRF token, the result will fail.
      </p>
    {% end %}
  </section>
</body>
</html>
