Class: ApplicationController

Inherits:
ActionController::Base
  • Object
show all
Includes:
CanonicalURL::ControllerExtensions, CurrentUser, GlobalPath, Hijack, JsonError, ReadOnlyMixin, ThemeResolver, VaryHeader
Defined in:
app/controllers/application_controller.rb

Direct Known Subclasses

AboutController, Admin::AdminController, Admin::StaffController, AssociatedGroupsController, BadgesController, BookmarksController, BootstrapController, CategoriesController, ClicksController, ComposerController, ComposerMessagesController, CspReportsController, CustomHomepageController, DirectoryColumnsController, DirectoryItemsController, DoNotDisturbController, DraftsController, EditDirectoryColumnsController, EmailController, EmbedController, ExceptionsController, ExportCsvController, ExtraLocalesController, FinishInstallationController, FormTemplatesController, GroupsController, HashtagsController, HighlightJsController, InlineOneboxController, InvitesController, ListController, MetadataController, NewInviteController, NewTopicController, NotificationsController, OfflineController, OneboxController, PageviewController, PermalinksController, PostActionUsersController, PostActionsController, PostReadersController, PostsController, PresenceController, PublishedPagesController, PushNotificationController, QunitController, ReviewableClaimedTopicsController, ReviewablesController, RobotsTxtController, SafeModeController, SearchController, SessionController, SidebarSectionsController, SimilarTopicsController, SiteController, SitemapController, SlugsController, StaticController, StepsController, StylesheetsController, SvgSpriteController, TagGroupsController, TagsController, TestRequestsController, ThemeJavascriptsController, TopicViewStatsController, TopicsController, UploadsController, UserActionsController, UserApiKeyClientsController, UserApiKeysController, UserAvatarsController, UserBadgesController, UserStatusController, Users::AssociateAccountsController, Users::OmniauthCallbacksController, UsersController, UsersEmailController, WizardController

Defined Under Namespace

Classes: PluginDisabled, RenderEmpty

Constant Summary collapse

HONEYPOT_KEY =
"HONEYPOT_KEY"
CHALLENGE_KEY =
"CHALLENGE_KEY"
NO_THEMES =
"no_themes"
NO_PLUGINS =
"no_plugins"
NO_UNOFFICIAL_PLUGINS =
"no_unofficial_plugins"
SAFE_MODE =
"safe_mode"
LEGACY_NO_THEMES =
"no_custom"
LEGACY_NO_UNOFFICIAL_PLUGINS =
"only_official"

Constants included from CanonicalURL::ControllerExtensions

CanonicalURL::ControllerExtensions::ALLOWED_CANONICAL_PARAMS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from VaryHeader

#ensure_vary_header

Methods included from ThemeResolver

resolve_theme_id

Methods included from ReadOnlyMixin

#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_mode, #get_or_check_readonly_mode, #get_or_check_staff_writes_only_mode, included, #staff_writes_only_mode?

Methods included from Hijack

#hijack

Methods included from GlobalPath

#cdn_path, #cdn_relative_path, #full_cdn_url, #path, #upload_cdn_path

Methods included from JsonError

#create_errors_json

Methods included from CanonicalURL::ControllerExtensions

#canonical_url, #default_canonical, included

Methods included from CurrentUser

#clear_current_user, #current_user, has_auth_cookie?, #is_api?, #is_user_api?, #log_off_user, #log_on_user, lookup_from_env, #refresh_session

Instance Attribute Details

#theme_idObject (readonly)

Returns the value of attribute theme_id.



15
16
17
# File 'app/controllers/application_controller.rb', line 15

def theme_id
  @theme_id
end

Class Method Details

.requires_plugin(plugin_name) ⇒ Object

If a controller requires a plugin, it will raise an exception if that plugin is disabled. This allows plugins to be disabled programmatically.



351
352
353
354
355
356
357
358
359
360
361
# File 'app/controllers/application_controller.rb', line 351

def self.requires_plugin(plugin_name)
  before_action do
    if plugin = Discourse.plugins_by_name[plugin_name]
      raise PluginDisabled.new if !plugin.enabled?
    elsif Rails.env.test?
      raise "Required plugin '#{plugin_name}' not found. The string passed to requires_plugin should match the plugin's name at the top of plugin.rb"
    else
      Rails.logger.warn("Required plugin '#{plugin_name}' not found")
    end
  end
end

Instance Method Details

#application_layoutObject



110
111
112
# File 'app/controllers/application_controller.rb', line 110

def application_layout
  ember_cli_required? ? "ember_cli" : "application"
end

#can_cache_content?Boolean

Returns:

  • (Boolean)


531
532
533
# File 'app/controllers/application_controller.rb', line 531

def can_cache_content?
  current_user.blank? && cookies[:authentication_data].blank?
end

#clear_notificationsObject



380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'app/controllers/application_controller.rb', line 380

def clear_notifications
  if current_user && !@readonly_mode
    cookie_notifications = cookies["cn"]
    notifications = request.headers["Discourse-Clear-Notifications"]

    if cookie_notifications
      if notifications.present?
        notifications += ",#{cookie_notifications}"
      else
        notifications = cookie_notifications
      end
    end

    if notifications.present?
      notification_ids = notifications.split(",").map(&:to_i)
      Notification.read(current_user, notification_ids)
      current_user.reload
      current_user.publish_notifications_state
      cookie_args = {}
      cookie_args[:path] = Discourse.base_path if Discourse.base_path.present?
      cookies.delete("cn", cookie_args)
    end
  end
end

#conditionally_allow_site_embeddingObject



101
102
103
# File 'app/controllers/application_controller.rb', line 101

def conditionally_allow_site_embedding
  response.headers.delete("X-Frame-Options") if SiteSetting.allow_embedding_site_in_an_iframe
end

#current_homepageObject



495
496
497
# File 'app/controllers/application_controller.rb', line 495

def current_homepage
  current_user&.user_option&.homepage || HomepageHelper.resolve(request, current_user)
end

#discourse_expires_in(time_length) ⇒ Object

Our custom cache method



536
537
538
539
# File 'app/controllers/application_controller.rb', line 536

def discourse_expires_in(time_length)
  return unless can_cache_content?
  Middleware::AnonymousCache.anon_cache(request.env, time_length)
end

#dont_cache_pageObject



93
94
95
96
97
98
99
# File 'app/controllers/application_controller.rb', line 93

def dont_cache_page
  if !response.headers["Cache-Control"] && response.cache_control.blank?
    response.cache_control[:no_cache] = true
    response.cache_control[:extras] = ["no-store"]
  end
  response.headers["Discourse-No-Onebox"] = "1" if SiteSetting.
end

#ember_cli_required?Boolean

Returns:

  • (Boolean)


105
106
107
108
# File 'app/controllers/application_controller.rb', line 105

def ember_cli_required?
  Rails.env.development? && ENV["ALLOW_EMBER_CLI_PROXY_BYPASS"] != "1" &&
    request.headers["X-Discourse-Ember-CLI"] != "true"
end

#fetch_user_from_params(opts = nil, eager_load = []) ⇒ Object



541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'app/controllers/application_controller.rb', line 541

def fetch_user_from_params(opts = nil, eager_load = [])
  opts ||= {}
  user =
    if params[:username]
      username_lower = params[:username].downcase.chomp(".json")

      if current_user && current_user.username_lower == username_lower
        current_user
      else
        find_opts = { username_lower: username_lower }
        find_opts[:active] = true unless opts[:include_inactive] || current_user.try(:staff?)
        result = User
        (result = result.includes(*eager_load)) if !eager_load.empty?
        result.find_by(find_opts)
      end
    elsif params[:external_id]
      external_id = params[:external_id].chomp(".json")
      if provider_name = params[:external_provider]
        raise Discourse::InvalidAccess unless guardian.is_admin? # external_id might be something sensitive
        provider = Discourse.enabled_authenticators.find { |a| a.name == provider_name }
        raise Discourse::NotFound if !provider&.is_managed? # Only managed authenticators use UserAssociatedAccount
        UserAssociatedAccount.find_by(
          provider_name: provider_name,
          provider_uid: external_id,
        )&.user
      else
        SingleSignOnRecord.find_by(external_id: external_id).try(:user)
      end
    end
  raise Discourse::NotFound if user.blank?

  guardian.ensure_can_see!(user)
  user
end

#guardianObject



486
487
488
489
490
491
492
493
# File 'app/controllers/application_controller.rb', line 486

def guardian
  # sometimes we log on a user in the middle of a request so we should throw
  # away the cached guardian instance when we do that
  if (@guardian&.user).blank? && current_user.present?
    @guardian = Guardian.new(current_user, request)
  end
  @guardian ||= Guardian.new(current_user, request)
end


595
596
597
598
599
600
# File 'app/controllers/application_controller.rb', line 595

def handle_permalink(path)
  permalink = Permalink.find_by_url(path)
  if permalink && permalink.target_url
    redirect_to permalink.target_url, status: :moved_permanently
  end
end

#handle_themeObject



477
478
479
480
481
482
483
484
# File 'app/controllers/application_controller.rb', line 477

def handle_theme
  return if request.format == "js"

  resolve_safe_mode
  return if request.env[NO_THEMES]

  @theme_id ||= ThemeResolver.resolve_theme_id(request, guardian, current_user)
end

#handle_unverified_requestObject

Default Rails 3.2 lets the request through with a blank session

we are being more pedantic here and nulling session / current_user
and then raising a CSRF exception


24
25
26
27
28
29
30
31
# File 'app/controllers/application_controller.rb', line 24

def handle_unverified_request
  # NOTE: API key is secret, having it invalidates the need for a CSRF token
  unless is_api? || is_user_api?
    super
    clear_current_user
    render plain: "[\"BAD CSRF\"]", status: 403
  end
end

#has_escaped_fragment?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'app/controllers/application_controller.rb', line 64

def has_escaped_fragment?
  SiteSetting.enable_escaped_fragments? && params.key?("_escaped_fragment_")
end

#immutable_for(duration) ⇒ Object



87
88
89
90
91
# File 'app/controllers/application_controller.rb', line 87

def immutable_for(duration)
  response.cache_control[:max_age] = duration.to_i
  response.cache_control[:public] = true
  response.cache_control[:extras] = ["immutable"]
end

#login_methodObject



610
611
612
613
# File 'app/controllers/application_controller.rb', line 610

def 
  return if current_user.anonymous?
  current_user.authenticated_with_oauth ? Auth::LOGIN_METHOD_OAUTH : Auth::LOGIN_METHOD_LOCAL
end

#no_cookiesObject



584
585
586
587
588
589
# File 'app/controllers/application_controller.rb', line 584

def no_cookies
  # do your best to ensure response has no cookies
  # longer term we may want to push this into middleware
  headers.delete "Set-Cookie"
  request.session_options[:skip] = true
end

#perform_refresh_sessionObject



83
84
85
# File 'app/controllers/application_controller.rb', line 83

def perform_refresh_session
  refresh_session(current_user) unless @readonly_mode
end

#post_ids_including_repliesObject



576
577
578
579
580
581
582
# File 'app/controllers/application_controller.rb', line 576

def post_ids_including_replies
  post_ids = params[:post_ids].map(&:to_i)
  post_ids |= PostReply.where(post_id: params[:reply_post_ids]).pluck(:reply_post_id) if params[
    :reply_post_ids
  ]
  post_ids
end

#preload_jsonObject

If we are rendering HTML, preload the session data



436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'app/controllers/application_controller.rb', line 436

def preload_json
  # We don't preload JSON on xhr or JSON request
  return if request.xhr? || request.format.json?

  # if we are posting in makes no sense to preload
  return if request.method != "GET"

  # TODO should not be invoked on redirection so this should be further deferred
  preload_anonymous_data

  if current_user
    current_user.sync_notification_channel_position
    preload_current_user_data
  end
end

#rate_limit_second_factor!(user) ⇒ Object



602
603
604
605
606
607
608
# File 'app/controllers/application_controller.rb', line 602

def rate_limit_second_factor!(user)
  return if params[:second_factor_token].blank?

  RateLimiter.new(nil, "second-factor-min-#{request.remote_ip}", 6, 1.minute).performed!

  RateLimiter.new(nil, "second-factor-min-#{user.username}", 6, 1.minute).performed! if user
end

#redirect_with_client_support(url, options = {}) ⇒ Object



269
270
271
272
273
274
275
276
# File 'app/controllers/application_controller.rb', line 269

def redirect_with_client_support(url, options = {})
  if request.xhr?
    response.headers["Discourse-Xhr-Redirect"] = "true"
    render plain: url
  else
    redirect_to url, options
  end
end

#render_json_dump(obj, opts = nil) ⇒ Object



518
519
520
521
522
523
524
525
526
527
528
529
# File 'app/controllers/application_controller.rb', line 518

def render_json_dump(obj, opts = nil)
  opts ||= {}
  if opts[:rest_serializer]
    obj["__rest_serializer"] = "1"
    opts.each { |k, v| obj[k] = v if k.to_s.start_with?("refresh_") }

    obj["extras"] = opts[:extras] if opts[:extras]
    obj["meta"] = opts[:meta] if opts[:meta]
  end

  render json: MultiJson.dump(obj), status: opts[:status] || 200
end

#render_serialized(obj, serializer, opts = nil) ⇒ Object

This is odd, but it seems that in Rails ‘render json: obj` is about 20% slower than calling MultiJSON.dump ourselves. I’m not sure why Rails doesn’t call MultiJson.dump when you pass it json: obj but it seems we don’t need whatever Rails is doing.



514
515
516
# File 'app/controllers/application_controller.rb', line 514

def render_serialized(obj, serializer, opts = nil)
  render_json_dump(serialize_data(obj, serializer, opts), opts)
end

#rescue_discourse_actions(type, status_code, opts = nil) ⇒ Object



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'app/controllers/application_controller.rb', line 278

def rescue_discourse_actions(type, status_code, opts = nil)
  opts ||= {}
  show_json_errors =
    (request.format && request.format.json?) || (request.xhr?) ||
      ((params[:external_id] || "").ends_with? ".json")

  if type == :not_found && opts[:check_permalinks]
    url = opts[:original_path] || request.fullpath
    permalink = Permalink.find_by_url(url)

    # there are some cases where we have a permalink but no url
    # cause category / topic was deleted
    if permalink.present? && permalink.target_url
      # permalink present, redirect to that URL
      redirect_with_client_support permalink.target_url,
                                   status: :moved_permanently,
                                   allow_other_host: true
      return
    end
  end

  message = title = nil
  with_resolved_locale(check_current_user: false) do
    if opts[:custom_message]
      title = message = I18n.t(opts[:custom_message], opts[:custom_message_params] || {})
    else
      message = I18n.t(type)
      if status_code == 403
        title = I18n.t("page_forbidden.title")
      else
        title = I18n.t("page_not_found.title")
      end
    end
  end

  error_page_opts = { title: title, status: status_code, group: opts[:group] }

  if show_json_errors
    opts = { type: type, status: status_code }

    with_resolved_locale(check_current_user: false) do
      # Include error in HTML format for topics#show.
      if (request.params[:controller] == "topics" && request.params[:action] == "show") ||
           (
             request.params[:controller] == "categories" &&
               request.params[:action] == "find_by_slug"
           )
        opts[:extras] = {
          title: I18n.t("page_not_found.page_title"),
          html: build_not_found_page(error_page_opts),
          group: error_page_opts[:group],
        }
      end
    end

    render_json_error message, opts
  else
    begin
      # 404 pages won't have the session and theme_keys without these:
      current_user
      handle_theme
    rescue Discourse::InvalidAccess
      return render plain: message, status: status_code
    end
    with_resolved_locale do
      error_page_opts[:layout] = (opts[:include_ember] && @preloaded) ? set_layout : "no_ember"
      render html: build_not_found_page(error_page_opts)
    end
  end
end

#resolve_safe_modeObject



464
465
466
467
468
469
470
471
472
473
474
475
# File 'app/controllers/application_controller.rb', line 464

def resolve_safe_mode
  return unless guardian.can_enable_safe_mode?

  safe_mode = params[SAFE_MODE]
  if safe_mode.is_a?(String)
    safe_mode = safe_mode.split(",")
    request.env[NO_THEMES] = safe_mode.include?(NO_THEMES) || safe_mode.include?(LEGACY_NO_THEMES)
    request.env[NO_PLUGINS] = safe_mode.include?(NO_PLUGINS)
    request.env[NO_UNOFFICIAL_PLUGINS] = safe_mode.include?(NO_UNOFFICIAL_PLUGINS) ||
      safe_mode.include?(LEGACY_NO_UNOFFICIAL_PLUGINS)
  end
end

#secure_sessionObject



591
592
593
# File 'app/controllers/application_controller.rb', line 591

def secure_session
  SecureSession.new(session["secure_session_id"] ||= SecureRandom.hex)
end

#serialize_data(obj, serializer, opts = nil) ⇒ Object



499
500
501
502
503
504
505
506
507
508
# File 'app/controllers/application_controller.rb', line 499

def serialize_data(obj, serializer, opts = nil)
  # If it's an array, apply the serializer as an each_serializer to the elements
  serializer_opts = { scope: guardian }.merge!(opts || {})
  if obj.respond_to?(:to_ary)
    serializer_opts[:each_serializer] = serializer
    ActiveModel::ArraySerializer.new(obj.to_ary, serializer_opts).as_json
  else
    serializer.new(obj, serializer_opts).as_json
  end
end

#set_current_user_for_logsObject



363
364
365
366
367
368
369
# File 'app/controllers/application_controller.rb', line 363

def set_current_user_for_logs
  if current_user
    Logster.add_to_env(request.env, "username", current_user.username)
    response.headers["X-Discourse-Username"] = current_user.username
  end
  response.headers["X-Discourse-Route"] = "#{controller_path}/#{action_name}"
end

#set_layoutObject



114
115
116
117
118
119
120
121
122
123
# File 'app/controllers/application_controller.rb', line 114

def set_layout
  case request.headers["Discourse-Render"]
  when "desktop"
    return application_layout
  when "crawler"
    return "crawler"
  end

  use_crawler_layout? ? "crawler" : application_layout
end

#set_mobile_viewObject



452
453
454
# File 'app/controllers/application_controller.rb', line 452

def set_mobile_view
  session[:mobile_view] = params[:mobile_view] if params.has_key?(:mobile_view)
end

#set_mp_snapshot_fieldsObject



371
372
373
374
375
376
377
378
# File 'app/controllers/application_controller.rb', line 371

def set_mp_snapshot_fields
  if defined?(Rack::MiniProfiler)
    Rack::MiniProfiler.add_snapshot_custom_field("Application version", Discourse.git_version)
    if Rack::MiniProfiler.snapshots_transporter?
      Rack::MiniProfiler.add_snapshot_custom_field("Site", Discourse.current_hostname)
    end
  end
end

#show_browser_update?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'app/controllers/application_controller.rb', line 68

def show_browser_update?
  @show_browser_update ||= CrawlerDetection.show_browser_update?(request.user_agent)
end

#store_preloaded(key, json) ⇒ Object



427
428
429
430
431
432
433
# File 'app/controllers/application_controller.rb', line 427

def store_preloaded(key, json)
  @preloaded ||= {}
  # I dislike that there is a gsub as opposed to a gsub!
  #  but we can not be mucking with user input, I wonder if there is a way
  #  to inject this safety deeper in the library or even in AM serializer
  @preloaded[key] = json.gsub("</", "<\\/")
end

#use_crawler_layout?Boolean

Returns:

  • (Boolean)


73
74
75
76
77
78
79
80
81
# File 'app/controllers/application_controller.rb', line 73

def use_crawler_layout?
  @use_crawler_layout ||=
    request.user_agent && (request.media_type.blank? || request.media_type.include?("html")) &&
      !%w[json rss].include?(params[:format]) &&
      (
        has_escaped_fragment? || params.key?("print") || show_browser_update? ||
          CrawlerDetection.crawler?(request.user_agent, request.headers["HTTP_VIA"])
      )
end

#with_resolved_locale(check_current_user: true) ⇒ Object



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'app/controllers/application_controller.rb', line 405

def with_resolved_locale(check_current_user: true)
  if check_current_user &&
       (
         user =
           begin
             current_user
           rescue StandardError
             nil
           end
       )
    locale = user.effective_locale
  else
    locale = Discourse.anonymous_locale(request)
    locale ||= SiteSetting.default_locale
  end

  locale = SiteSettings::DefaultsProvider::DEFAULT_LOCALE if !I18n.locale_available?(locale)

  I18n.ensure_all_loaded!
  I18n.with_locale(locale) { yield }
end