<commit_before>require "secure_random"

module Amber
  module Pipe
    # The CSRF Handler adds support for Cross Site Request Forgery.
    class CSRF < Base
      CHECK_METHODS = %w(PUT POST PATCH DELETE)
      HEADER_KEY    = "X-CSRF-TOKEN"
      PARAM_KEY     = "_csrf"
      CSRF_KEY      = "csrf.token"

      def call(context : HTTP::Server::Context)
        if valid_http_method?(context) || valid_token?(context)
          context.session.delete(CSRF_KEY)
          call_next(context)
        else
          raise Amber::Exceptions::Forbidden.new("CSRF check failed.")
          context.response.status_code = 403
          context.response.content_type = "text/plain"
          context.response.print("CSRF check failed.")
        end
      end

      def valid_http_method?(context)
        !CHECK_METHODS.includes?(context.request.method)
      end

      def valid_token?(context)<commit_msg>Remove CSRF dead code (#163)<commit_after>require "secure_random"

module Amber
  module Pipe
    # The CSRF Handler adds support for Cross Site Request Forgery.
    class CSRF < Base
      CHECK_METHODS = %w(PUT POST PATCH DELETE)
      HEADER_KEY    = "X-CSRF-TOKEN"
      PARAM_KEY     = "_csrf"
      CSRF_KEY      = "csrf.token"

      def call(context : HTTP::Server::Context)
        if valid_http_method?(context) || valid_token?(context)
          context.session.delete(CSRF_KEY)
          call_next(context)
        else
          raise Amber::Exceptions::Forbidden.new("CSRF check failed.")
        end
      end

      def valid_http_method?(context)
        !CHECK_METHODS.includes?(context.request.method)
      end

      def valid_token?(context)
{'fraction_non_alphanumeric': 0.09303721488595439, 'fraction_numerical': 0.003601440576230492, 'mean_word_length': 2.5168776371308015, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '750892', 'n_tokens_mistral': 520, 'n_tokens_neox': 505, 'n_words': 112}