"Fossies" - the Fresh Open Source Software Archive

Member "discourse-2.8.3/config/initializers/008-rack-cors.rb" (14 Apr 2022, 1936 Bytes) of package /linux/www/discourse-2.8.3.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Ruby source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. See also the last Fossies "Diffs" side-by-side code changes report for "008-rack-cors.rb": 2.7.13_vs_2.8.0.

    1 # frozen_string_literal: true
    2 
    3 class Discourse::Cors
    4   ORIGINS_ENV = "Discourse_Cors_Origins"
    5 
    6   def initialize(app, options = nil)
    7     @app = app
    8     if GlobalSetting.enable_cors && GlobalSetting.cors_origin.present?
    9       @global_origins = GlobalSetting.cors_origin.split(',').map { |x| x.strip.chomp('/') }
   10     end
   11   end
   12 
   13   def call(env)
   14 
   15     cors_origins = @global_origins || []
   16     cors_origins += SiteSetting.cors_origins.split('|') if SiteSetting.cors_origins.present?
   17     cors_origins = cors_origins.presence
   18 
   19     if env['REQUEST_METHOD'] == ('OPTIONS') && env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
   20       return [200, Discourse::Cors.apply_headers(cors_origins, env, {}), []]
   21     end
   22 
   23     env[Discourse::Cors::ORIGINS_ENV] = cors_origins if cors_origins
   24 
   25     status, headers, body = @app.call(env)
   26     headers ||= {}
   27 
   28     Discourse::Cors.apply_headers(cors_origins, env, headers)
   29 
   30     [status, headers, body]
   31   end
   32 
   33   def self.apply_headers(cors_origins, env, headers)
   34     request_method = env['REQUEST_METHOD']
   35 
   36     if env['REQUEST_PATH'] =~ /\/(javascripts|assets)\// && Discourse.is_cdn_request?(env, request_method)
   37       Discourse.apply_cdn_headers(headers)
   38     elsif cors_origins
   39       origin = nil
   40       if origin = env['HTTP_ORIGIN']
   41         origin = nil unless cors_origins.include?(origin)
   42       end
   43 
   44       headers['Access-Control-Allow-Origin'] = origin || cors_origins[0]
   45       headers['Access-Control-Allow-Headers'] = 'Content-Type, Cache-Control, X-Requested-With, X-CSRF-Token, Discourse-Present, User-Api-Key, User-Api-Client-Id, Authorization'
   46       headers['Access-Control-Allow-Credentials'] = 'true'
   47       headers['Access-Control-Allow-Methods'] = 'POST, PUT, GET, OPTIONS, DELETE'
   48       headers['Access-Control-Max-Age'] = '7200'
   49     end
   50 
   51     headers
   52   end
   53 end
   54 
   55 if GlobalSetting.enable_cors || GlobalSetting.cdn_url
   56   Rails.configuration.middleware.insert_before ActionDispatch::Flash, Discourse::Cors
   57 end