Class: ApplicationController

Inherits:
ActionController::Base
  • Object
show all
Includes:
CanonicalURL::ControllerExtensions, CurrentUser, GlobalPath, Hijack, JsonError, ReadOnlyMixin, 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, DirectoryColumnsController, DirectoryItemsController, DoNotDisturbController, DraftsController, EditDirectoryColumnsController, EmailController, EmbedController, ExceptionsController, ExportCsvController, ExtraLocalesController, FinishInstallationController, FormTemplatesController, GroupsController, HashtagsController, HighlightJsController, InlineOneboxController, InvitesController, ListController, MetadataController, NewTopicController, NotificationsController, OfflineController, OneboxController, 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, ThemeJavascriptsController, TopicsController, UploadsController, UserActionsController, UserApiKeysController, UserAvatarsController, UserBadgesController, UserStatusController, Users::AssociateAccountsController, Users::OmniauthCallbacksController, UsersController, UsersEmailController, WizardController

Defined Under Namespace

Classes: PluginDisabled, RenderEmpty

Constant Summary collapse

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 ReadOnlyMixin

#add_readonly_header, #allowed_in_staff_writes_only_mode?, #block_if_readonly_mode, #check_readonly_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.



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

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.



348
349
350
351
352
353
354
355
356
357
358
# File 'app/controllers/application_controller.rb', line 348

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



108
109
110
# File 'app/controllers/application_controller.rb', line 108

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

#can_cache_content?Boolean

Returns:

  • (Boolean)


555
556
557
# File 'app/controllers/application_controller.rb', line 555

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

#clear_notificationsObject



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

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



99
100
101
# File 'app/controllers/application_controller.rb', line 99

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

#current_homepageObject



519
520
521
# File 'app/controllers/application_controller.rb', line 519

def current_homepage
  current_user&.user_option&.homepage || SiteSetting.anonymous_homepage
end

#discourse_expires_in(time_length) ⇒ Object

Our custom cache method



560
561
562
563
# File 'app/controllers/application_controller.rb', line 560

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

#dont_cache_pageObject



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

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)


103
104
105
106
# File 'app/controllers/application_controller.rb', line 103

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



565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
# File 'app/controllers/application_controller.rb', line 565

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



510
511
512
513
514
515
516
517
# File 'app/controllers/application_controller.rb', line 510

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


619
620
621
622
623
624
# File 'app/controllers/application_controller.rb', line 619

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



474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
# File 'app/controllers/application_controller.rb', line 474

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

  resolve_safe_mode
  return if request.env[NO_THEMES]

  theme_id = nil

  if (preview_theme_id = request[:preview_theme_id]&.to_i) &&
       guardian.allow_themes?([preview_theme_id], include_preview: true)
    theme_id = preview_theme_id
  end

  user_option = current_user&.user_option

  if theme_id.blank?
    ids, seq = cookies[:theme_ids]&.split("|")
    id = ids&.split(",")&.map(&:to_i)&.first
    if id.present? && seq && seq.to_i == user_option&.theme_key_seq.to_i
      theme_id = id if guardian.allow_themes?([id])
    end
  end

  if theme_id.blank?
    ids = user_option&.theme_ids || []
    theme_id = ids.first if guardian.allow_themes?(ids)
  end

  if theme_id.blank? && SiteSetting.default_theme_id != -1 &&
       guardian.allow_themes?([SiteSetting.default_theme_id])
    theme_id = SiteSetting.default_theme_id
  end

  @theme_id = request.env[:resolved_theme_id] = theme_id
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


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

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)


62
63
64
# File 'app/controllers/application_controller.rb', line 62

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

#immutable_for(duration) ⇒ Object



85
86
87
88
89
# File 'app/controllers/application_controller.rb', line 85

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

#no_cookiesObject



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

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



81
82
83
# File 'app/controllers/application_controller.rb', line 81

def perform_refresh_session
  refresh_session(current_user) unless @readonly_mode
end

#post_ids_including_repliesObject



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

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



433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'app/controllers/application_controller.rb', line 433

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



626
627
628
629
630
631
632
# File 'app/controllers/application_controller.rb', line 626

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



266
267
268
269
270
271
272
273
# File 'app/controllers/application_controller.rb', line 266

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



542
543
544
545
546
547
548
549
550
551
552
553
# File 'app/controllers/application_controller.rb', line 542

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.



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

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



275
276
277
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
# File 'app/controllers/application_controller.rb', line 275

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) ? "application" : "no_ember"
      render html: build_not_found_page(error_page_opts)
    end
  end
end

#resolve_safe_modeObject



461
462
463
464
465
466
467
468
469
470
471
472
# File 'app/controllers/application_controller.rb', line 461

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



615
616
617
# File 'app/controllers/application_controller.rb', line 615

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

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



523
524
525
526
527
528
529
530
531
532
# File 'app/controllers/application_controller.rb', line 523

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



360
361
362
363
364
365
366
# File 'app/controllers/application_controller.rb', line 360

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_name}/#{action_name}"
end

#set_layoutObject



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

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



449
450
451
# File 'app/controllers/application_controller.rb', line 449

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

#set_mp_snapshot_fieldsObject



368
369
370
371
372
373
374
375
# File 'app/controllers/application_controller.rb', line 368

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)


66
67
68
# File 'app/controllers/application_controller.rb', line 66

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

#store_preloaded(key, json) ⇒ Object



424
425
426
427
428
429
430
# File 'app/controllers/application_controller.rb', line 424

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)


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

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



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

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