Class: ApplicationController
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"
CanonicalURL::ControllerExtensions::ALLOWED_CANONICAL_PARAMS
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
-
#application_layout ⇒ Object
-
#can_cache_content? ⇒ Boolean
-
#clear_notifications ⇒ Object
-
#conditionally_allow_site_embedding ⇒ Object
-
#current_homepage ⇒ Object
-
#discourse_expires_in(time_length) ⇒ Object
-
#dont_cache_page ⇒ Object
-
#ember_cli_required? ⇒ Boolean
-
#fetch_user_from_params(opts = nil, eager_load = []) ⇒ Object
-
#guardian ⇒ Object
-
#handle_permalink(path) ⇒ Object
-
#handle_theme ⇒ Object
-
#handle_unverified_request ⇒ Object
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.
-
#has_escaped_fragment? ⇒ Boolean
-
#immutable_for(duration) ⇒ Object
-
#no_cookies ⇒ Object
-
#perform_refresh_session ⇒ Object
-
#post_ids_including_replies ⇒ Object
-
#preload_json ⇒ Object
If we are rendering HTML, preload the session data.
-
#rate_limit_second_factor!(user) ⇒ Object
-
#redirect_with_client_support(url, options = {}) ⇒ Object
-
#render_json_dump(obj, opts = nil) ⇒ Object
-
#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.
-
#rescue_discourse_actions(type, status_code, opts = nil) ⇒ Object
-
#resolve_safe_mode ⇒ Object
-
#secure_session ⇒ Object
-
#serialize_data(obj, serializer, opts = nil) ⇒ Object
-
#set_current_user_for_logs ⇒ Object
-
#set_layout ⇒ Object
-
#set_mobile_view ⇒ Object
-
#set_mp_snapshot_fields ⇒ Object
-
#show_browser_update? ⇒ Boolean
-
#store_preloaded(key, json) ⇒ Object
-
#use_crawler_layout? ⇒ Boolean
-
#with_resolved_locale(check_current_user: true) ⇒ Object
Methods included from VaryHeader
#ensure_vary_header
#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
#canonical_url, #default_canonical, included
#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_id ⇒ Object
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_layout ⇒ Object
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
555
556
557
|
# File 'app/controllers/application_controller.rb', line 555
def can_cache_content?
current_user.blank? && cookies[:authentication_data].blank?
end
|
#clear_notifications ⇒ Object
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.["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_embedding ⇒ Object
99
100
101
|
# File 'app/controllers/application_controller.rb', line 99
def conditionally_allow_site_embedding
response..delete("X-Frame-Options") if SiteSetting.allow_embedding_site_in_an_iframe
end
|
#current_homepage ⇒ Object
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
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_page ⇒ Object
91
92
93
94
95
96
97
|
# File 'app/controllers/application_controller.rb', line 91
def dont_cache_page
if !response.["Cache-Control"] && response.cache_control.blank?
response.cache_control[:no_cache] = true
response.cache_control[:extras] = ["no-store"]
end
response.["Discourse-No-Onebox"] = "1" if SiteSetting.login_required
end
|
#ember_cli_required? ⇒ 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.["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? provider = Discourse.enabled_authenticators.find { |a| a.name == provider_name }
raise Discourse::NotFound if !provider&.is_managed? 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
|
#guardian ⇒ Object
510
511
512
513
514
515
516
517
|
# File 'app/controllers/application_controller.rb', line 510
def guardian
if (@guardian&.user).blank? && current_user.present?
@guardian = Guardian.new(current_user, request)
end
@guardian ||= Guardian.new(current_user, request)
end
|
#handle_permalink(path) ⇒ Object
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_theme ⇒ Object
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_request ⇒ Object
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
unless is_api? || is_user_api?
super
clear_current_user
render plain: "[\"BAD CSRF\"]", status: 403
end
end
|
#has_escaped_fragment? ⇒ 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_cookies ⇒ Object
608
609
610
611
612
613
|
# File 'app/controllers/application_controller.rb', line 608
def no_cookies
.delete "Set-Cookie"
request.session_options[:skip] = true
end
|
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_replies ⇒ Object
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_json ⇒ Object
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
return if request.xhr? || request.format.json?
return if request.method != "GET"
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.["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)
if permalink.present? && permalink.target_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
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
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_mode ⇒ Object
#secure_session ⇒ Object
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)
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_logs ⇒ Object
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.["X-Discourse-Username"] = current_user.username
end
response.["X-Discourse-Route"] = "#{controller_name}/#{action_name}"
end
|
#set_layout ⇒ Object
112
113
114
115
116
117
118
119
120
121
|
# File 'app/controllers/application_controller.rb', line 112
def set_layout
case request.["Discourse-Render"]
when "desktop"
return application_layout
when "crawler"
return "crawler"
end
use_crawler_layout? ? "crawler" : application_layout
end
|
#set_mobile_view ⇒ Object
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_fields ⇒ Object
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
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 ||= {}
@preloaded[key] = json.gsub("</", "<\\/")
end
|
#use_crawler_layout? ⇒ 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.["HTTP_VIA"])
)
end
|
#with_resolved_locale(check_current_user: true) ⇒ Object