Module: Strelka::App::CORS

Extended by:
Plugin
Defined in:
lib/strelka/app/cors.rb

Overview

Strelka::App plugin module for Cross-Origin Resource Sharing (CORS)

class MyService < Strelka::App
    plugins :cors

    allow_origins '*'

end # MyService

Resources:

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(object) ⇒ Object

Extension callback – extend the HTTPRequest class with Auth support when this plugin is loaded.



60
61
62
63
64
65
# File 'lib/strelka/app/cors.rb', line 60

def self::included( object )
	self.log.debug "Extending Request with CORS mixin"
	Strelka::HTTPRequest.class_eval { include Strelka::HTTPRequest::CORS }
	Strelka::HTTPResponse.class_eval { include Strelka::HTTPResponse::CORS }
	super
end

Instance Method Details

#handle_preflight_request(request) ⇒ Object

Handle a CORS preflight request.



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/strelka/app/cors.rb', line 88

def handle_preflight_request( request )
	path = request.app_path
	response = request.response

	self.class.access_controls.each do |pattern, options|
		self.log.debug "Applying access controls: %p (%p)" % [ pattern, options ]

		# TODO: Skip requests that don't match options? E.g.,
		#   next unless options[:allowed_methods].include?( request.verb )

		options[:block].call( request, response ) if
			options[:block] && ( !pattern || path.match(pattern) )
	end

	response.add_cors_headers
	response.status = 204

	return response
end

#handle_request(request) ⇒ Object

Extend handled requests with CORS stuff.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/strelka/app/cors.rb', line 69

def handle_request( request )
	if request.origin
		self.log.info "Request has an Origin (%p): applying CORS" % [ request.origin ]
		response = if request.is_preflight?
				self.log.debug "Preflight request for %s" % [ request.uri ]
				self.handle_preflight_request( request )
			else
				request.response.add_cors_headers
				super
			end

		return response
	else
		super
	end
end