Class: Rage::Cors
- Inherits:
-
Object
- Object
- Rage::Cors
- Defined in:
- lib/rage/middleware/cors.rb
Instance Method Summary collapse
-
#allow(*origins, methods: "*", allow_headers: "*", expose_headers: nil, max_age: nil, allow_credentials: false) ⇒ Object
Set CORS rules for the application.
Instance Method Details
#allow(*origins, methods: "*", allow_headers: "*", expose_headers: nil, max_age: nil, allow_credentials: false) ⇒ Object
Note:
The middleware only supports the basic case of allowing one or several origins for the whole application. Use Rack::Cors if you are looking to specify more advanced rules.
Set CORS rules for the application.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/rage/middleware/cors.rb', line 57 def allow(*origins, methods: "*", allow_headers: "*", expose_headers: nil, max_age: nil, allow_credentials: false) @allow_headers = Array(allow_headers).join(", ") if allow_headers @expose_headers = Array(expose_headers).join(", ") if expose_headers @max_age = max_age.to_s if max_age @allow_credentials = "true" if allow_credentials @default_methods = %w(GET POST PUT PATCH DELETE HEAD OPTIONS) @methods = if methods != "*" methods.map! { |method| method.to_s.upcase }.tap { |m| if (invalid_methods = m - @default_methods).any? raise ArgumentError, "Unsupported method passed to Rage::Cors: #{invalid_methods[0]}" end }.join(", ") elsif @allow_credentials @default_methods.join(", ") else "*" end if @allow_credentials raise ArgumentError, "Rage::Cors requires you to explicitly list allowed headers when using `allow_credentials: true`" if @allow_headers == "*" raise ArgumentError, "Rage::Cors requires you to explicitly list exposed headers when using `allow_credentials: true`" if @expose_headers == "*" end @origins = [] origins.each do |origin| if origin == "*" @origins = "*" break elsif origin.is_a?(Regexp) || origin =~ /^\S+:\/\// @origins << origin else @origins << "https://#{origin}" << "http://#{origin}" end end @cors_check = create_cors_proc @cors_response = [204, create_headers, []] end |