|
1 | 1 | # Decides whether this is a request for the UI or a request for the API
|
| 2 | +# This is only needed so that the correct authentication method is applied (UI or API auth) |
2 | 3 |
|
3 | 4 | module Rack
|
4 | 5 | module PactBroker
|
5 | 6 | class UIRequestFilter
|
| 7 | + WEB_EXTENSIONS = %w[.js .woff .woff2 .css .png .html .map .ttf .ico].freeze |
| 8 | + API_CONTENT_TYPES = %w[application/hal+json application/json text/csv application/yaml].freeze |
| 9 | + |
6 | 10 | def initialize app
|
7 | 11 | @app = app
|
8 | 12 | end
|
9 | 13 |
|
10 | 14 | def call env
|
11 |
| - if request_for_ui_resource? env |
12 |
| - @app.call(env) |
13 |
| - else |
| 15 | + if request_for_api(env) || (accept_all(env) && !is_web_extension(env)) |
| 16 | + # send the request on to the next app in the Rack::Cascade |
14 | 17 | [404, {},[]]
|
| 18 | + else |
| 19 | + @app.call(env) |
15 | 20 | end
|
16 | 21 | end
|
17 | 22 |
|
18 | 23 | private
|
19 | 24 |
|
20 |
| - def request_for_ui_resource? env |
21 |
| - request_for_file?(env) || accepts_html?(env) |
| 25 | + def body_is_json(env) |
| 26 | + env['CONTENT_TYPE'] && env['CONTENT_TYPE'].include?("json") |
22 | 27 | end
|
23 | 28 |
|
24 |
| - def request_for_file?(env) |
25 |
| - if last_segment = env['PATH_INFO'].split("/").last |
26 |
| - last_segment.include?(".") |
27 |
| - else |
28 |
| - false |
29 |
| - end |
| 29 | + def request_for_api(env) |
| 30 | + accepts_api_content_type(env) || body_is_api_content_type(env) |
| 31 | + end |
| 32 | + |
| 33 | + def accepts_api_content_type(env) |
| 34 | + is_api_content_type((env['HTTP_ACCEPT'] && env['HTTP_ACCEPT'].downcase) || "") |
| 35 | + end |
| 36 | + |
| 37 | + def body_is_api_content_type(env) |
| 38 | + is_api_content_type((env['CONTENT_TYPE'] && env['CONTENT_TYPE'].downcase) || "") |
| 39 | + end |
| 40 | + |
| 41 | + def is_api_content_type(header) |
| 42 | + API_CONTENT_TYPES.any?{ |content_type| header.include?(content_type) } |
| 43 | + end |
| 44 | + |
| 45 | + def accept_all(env) |
| 46 | + env['HTTP_ACCEPT'] == "*/*" |
30 | 47 | end
|
31 | 48 |
|
32 |
| - def accepts_html?(env) |
33 |
| - (env['HTTP_ACCEPT'] || '').include?("text/html") |
| 49 | + def is_web_extension(env) |
| 50 | + env['PATH_INFO'].end_with?(*WEB_EXTENSIONS) |
34 | 51 | end
|
35 | 52 | end
|
36 | 53 | end
|
|
0 commit comments