Sha256: d16f34be7ff7cad4aaa3a9f80337e2ea3c9bd230bd7648b43da3636452c8c699

Contents?: true

Size: 1.58 KB

Versions: 1

Compression:

Stored size: 1.58 KB

Contents

require 'crystal_ext/gems'

# 
# Processor
# 
module Crystal
  module Processors
    class PrepareAutenticityToken < Processor      
      def call        
        if config.session?
          request = workspace.request.must_be.defined
          params = workspace.params.must_be.defined
              
          token = request.session['authenticity_token'] || params['session_authenticity_token']

          if token.blank? and request.get? and
            token = generate_authenticity_token
            request.session['authenticity_token'] = token
          end
                
          workspace.session_authenticity_token = token
        end
        
        next_processor.call
      end

        
      protected
        def generate_authenticity_token
          ActiveSupport::SecureRandom.base64(32)
        end
    end
  end
end


# 
# Remote
# 
Crystal::HttpController.class_eval do
  BROWSER_GENERATED_TYPES = %w(html url_encoded_form multipart_form text).to_set
  
  protected
    def protect_from_forgery &block
      request = workspace.request
      allow = (
        request.get? or
        # TODO2 check content_type is lovercased
        !BROWSER_GENERATED_TYPES.include?(request.content_type) or
        (workspace.session_authenticity_token.present? and 
        workspace.session_authenticity_token == params.authenticity_token)
      )

      if allow
        block.call
      else
        raise "Invalid authenticity token!"
      end
    end
end

Crystal::HttpController::ClassMethods.class_eval do  
  def protect_from_forgery options = {}
    around :protect_from_forgery, options
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
crystal_ext-0.0.7 lib/crystal_ext/protect_from_forgery.rb