Sha256: ee9dda64f291bee2b68bbf3dcaf0ed1b3e6b73a3ebfc032a445cce502c09efd9

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

# 
# 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

2 entries across 2 versions & 1 rubygems

Version Path
crystal_ext-0.0.5 lib/crystal_ext/protect_from_forgery.rb
crystal_ext-0.0.4 lib/crystal_ext/protect_from_forgery.rb