forked from instructure/canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication_controller.rb
More file actions
2185 lines (1925 loc) · 82.9 KB
/
Copy pathapplication_controller.rb
File metadata and controls
2185 lines (1925 loc) · 82.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
class << self
[:before, :after, :around,
:skip_before, :skip_after, :skip_around,
:prepend_before, :prepend_after, :prepend_around].each do |type|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{type}_filter(*)
raise "Please use #{type}_action instead of #{type}_filter"
end
RUBY
end
end
attr_accessor :active_tab
attr_reader :context
include Api
include LocaleSelection
include Api::V1::User
include Api::V1::WikiPage
include LegalInformationHelper
around_action :set_locale
around_action :enable_request_cache
around_action :batch_statsd
helper :all
include AuthenticationMethods
include Canvas::RequestForgeryProtection
protect_from_forgery with: :exception
# load_user checks masquerading permissions, so this needs to be cleared first
before_action :clear_cached_contexts
prepend_before_action :load_user, :load_account
# make sure authlogic is before load_user
skip_before_action :activate_authlogic
prepend_before_action :activate_authlogic
before_action :check_pending_otp
before_action :set_user_id_header
before_action :set_time_zone
before_action :set_page_view
before_action :require_reacceptance_of_terms
before_action :clear_policy_cache
before_action :setup_live_events_context
after_action :log_page_view
after_action :discard_flash_if_xhr
after_action :cache_buster
# Yes, we're calling this before and after so that we get the user id logged
# on events that log someone in and log someone out.
after_action :set_user_id_header
before_action :fix_xhr_requests
before_action :init_body_classes
after_action :set_response_headers
after_action :update_enrollment_last_activity_at
add_crumb(proc {
title = I18n.t('links.dashboard', 'My Dashboard')
crumb = <<-END
<i class="icon-home"
title="#{title}">
<span class="screenreader-only">#{title}</span>
</i>
END
crumb.html_safe
}, :root_path, class: 'home')
##
# Sends data from rails to JavaScript
#
# The data you send will eventually make its way into the view by simply
# calling `to_json` on the data.
#
# It won't allow you to overwrite a key that has already been set
#
# Please use *ALL_CAPS* for keys since these are considered constants
# Also, please don't name it stuff from JavaScript's Object.prototype
# like `hasOwnProperty`, `constructor`, `__defineProperty__` etc.
#
# This method is available in controllers and views
#
# example:
#
# # ruby
# js_env :FOO_BAR => [1,2,3], :COURSE => @course
#
# # coffeescript
# require ['ENV'], (ENV) ->
# ENV.FOO_BAR #> [1,2,3]
#
def js_env(hash = {})
return {} unless request.format.html?
# set some defaults
unless @js_env
editor_css = view_context.stylesheet_path(css_url_for('what_gets_loaded_inside_the_tinymce_editor'))
@js_env = {
ASSET_HOST: Canvas::Cdn.config.host,
active_brand_config: active_brand_config.try(:md5),
active_brand_config_json_url: active_brand_config_json_url,
url_to_what_gets_loaded_inside_the_tinymce_editor_css: editor_css,
current_user_id: @current_user.try(:id),
current_user: Rails.cache.fetch(['user_display_json', @current_user].cache_key, :expires_in => 1.hour) { user_display_json(@current_user, :profile) },
current_user_roles: @current_user.try(:roles, @domain_root_account),
current_user_disabled_inbox: @current_user.try(:disabled_inbox?),
files_domain: HostUrl.file_host(@domain_root_account || Account.default, request.host_with_port),
DOMAIN_ROOT_ACCOUNT_ID: @domain_root_account.try(:global_id),
k12: k12?,
help_link_name: help_link_name,
help_link_icon: help_link_icon,
use_high_contrast: @current_user.try(:prefers_high_contrast?),
SETTINGS: {
open_registration: @domain_root_account.try(:open_registration?),
eportfolios_enabled: (@domain_root_account && @domain_root_account.settings[:enable_eportfolios] != false), # checking all user root accounts is slow
collapse_global_nav: @current_user.try(:collapse_global_nav?),
show_feedback_link: show_feedback_link?,
enable_profiles: (@domain_root_account && @domain_root_account.settings[:enable_profiles] != false)
},
}
@js_env[:page_view_update_url] = page_view_path(@page_view.id, page_view_token: @page_view.token) if @page_view
@js_env[:IS_LARGE_ROSTER] = true if !@js_env[:IS_LARGE_ROSTER] && @context.respond_to?(:large_roster?) && @context.large_roster?
@js_env[:context_asset_string] = @context.try(:asset_string) if !@js_env[:context_asset_string]
@js_env[:ping_url] = polymorphic_url([:api_v1, @context, :ping]) if @context.is_a?(Course)
@js_env[:TIMEZONE] = Time.zone.tzinfo.identifier if !@js_env[:TIMEZONE]
@js_env[:CONTEXT_TIMEZONE] = @context.time_zone.tzinfo.identifier if !@js_env[:CONTEXT_TIMEZONE] && @context.respond_to?(:time_zone) && @context.time_zone.present?
unless @js_env[:LOCALE]
@js_env[:LOCALE] = I18n.locale.to_s
@js_env[:BIGEASY_LOCALE] = I18n.bigeasy_locale
@js_env[:FULLCALENDAR_LOCALE] = I18n.fullcalendar_locale
@js_env[:MOMENT_LOCALE] = I18n.moment_locale
end
@js_env[:lolcalize] = true if ENV['LOLCALIZE']
end
hash.each do |k,v|
if @js_env[k]
raise "js_env key #{k} is already taken"
else
@js_env[k] = v
end
end
@js_env
end
helper_method :js_env
# add keys to JS environment necessary for the RCE at the given risk level
def rce_js_env(risk_level, root_account: @domain_root_account, domain: request.env['HTTP_HOST'], context: @context)
rce_env_hash = Services::RichContent.env_for(root_account,
risk_level: risk_level,
user: @current_user,
domain: domain,
real_user: @real_current_user,
context: context)
js_env(rce_env_hash)
end
helper_method :rce_js_env
def conditional_release_js_env(assignment = nil, includes: [])
return unless ConditionalRelease::Service.enabled_in_context?(@context)
cr_env = ConditionalRelease::Service.env_for(
@context,
@current_user,
session: session,
assignment: assignment,
domain: request.env['HTTP_HOST'],
real_user: @real_current_user,
includes: includes
)
js_env(cr_env)
end
helper_method :conditional_release_js_env
def external_tools_display_hashes(type, context=@context, custom_settings=[])
return [] if context.is_a?(Group)
context = context.account if context.is_a?(User)
tools = ContextExternalTool.all_tools_for(context, {:placements => type,
:root_account => @domain_root_account, :current_user => @current_user}).to_a
tools.select!{|tool| ContextExternalTool.visible?(tool.extension_setting(type)['visibility'], @current_user, context, session)}
tools.map do |tool|
external_tool_display_hash(tool, type, {}, context, custom_settings)
end
end
def external_tool_display_hash(tool, type, url_params={}, context=@context, custom_settings=[])
url_params = {
id: tool.id,
launch_type: type
}.merge(url_params)
hash = {
:title => tool.label_for(type, I18n.locale),
:base_url => polymorphic_url([context, :external_tool], url_params)
}
extension_settings = [:icon_url, :canvas_icon_class] | custom_settings
extension_settings.each do |setting|
hash[setting] = tool.extension_setting(type, setting)
end
hash
end
helper_method :external_tool_display_hash
def k12?
@domain_root_account && @domain_root_account.feature_enabled?(:k12)
end
helper_method :k12?
def grading_periods?
!!@context.try(:grading_periods?)
end
helper_method :grading_periods?
def master_courses?
@domain_root_account && @domain_root_account.feature_enabled?(:master_courses)
end
helper_method :master_courses?
def setup_master_course_restrictions(objects, course)
return unless master_courses? && course.is_a?(Course) && course.grants_right?(@current_user, session, :read_as_admin)
if MasterCourses::MasterTemplate.is_master_course?(course)
MasterCourses::Restrictor.preload_default_template_restrictions(objects, course)
return :master # return master/child status
elsif MasterCourses::ChildSubscription.is_child_course?(course)
MasterCourses::Restrictor.preload_child_restrictions(objects)
return :child
end
end
helper_method :setup_master_course_restrictions
def set_master_course_js_env_data(object, course)
return unless object.respond_to?(:master_course_api_restriction_data) && object.persisted?
status = setup_master_course_restrictions([object], course)
return unless status
# we might have to include more information about the object here to make it easier to plug a common component in
data = object.master_course_api_restriction_data(status)
if status == :master
data[:default_restrictions] = MasterCourses::MasterTemplate.full_template_for(course).default_restrictions_for(object)
end
js_env(:MASTER_COURSE_DATA => data)
end
helper_method :set_master_course_js_env_data
def load_blueprint_courses_ui
return unless @context && @context.is_a?(Course) && master_courses? && @context.grants_right?(@current_user, :manage)
is_child = MasterCourses::ChildSubscription.is_child_course?(@context)
is_master = MasterCourses::MasterTemplate.is_master_course?(@context)
return unless is_master || is_child
js_bundle :blueprint_courses
css_bundle :blueprint_courses
master_course = is_master ? @context : @context.master_course_subscriptions.active.first.master_template.course
js_env :BLUEPRINT_COURSES_DATA => {
isMasterCourse: is_master,
isChildCourse: is_child,
accountId: @context.account.id,
masterCourse: master_course.slice(:id, :name, :enrollment_term_id),
course: @context.slice(:id, :name, :enrollment_term_id),
subAccounts: @context.account.sub_accounts.pluck(:id, :name).map{|id, name| {id: id, name: name}},
terms: @context.account.root_account.enrollment_terms.active.pluck(:id, :name).map{|id, name| {id: id, name: name}},
canManageCourse: MasterCourses::MasterTemplate.is_master_course?(@context) && @context.account.grants_right?(@current_user, :manage_master_courses)
}
end
helper_method :load_blueprint_courses_ui
def editing_restricted?(content, edit_type=:any)
return false unless master_courses? && content.respond_to?(:editing_restricted?)
content.editing_restricted?(edit_type)
end
helper_method :editing_restricted?
def tool_dimensions
tool_dimensions = {selection_width: '100%', selection_height: '100%'}
tool_dimensions.each do |k, v|
tool_dimensions[k] = @tool.settings[k] || v
tool_dimensions[k] = tool_dimensions[k].to_s << 'px' unless tool_dimensions[k].to_s =~ /%|px/
end
tool_dimensions
end
private :tool_dimensions
# Reject the request by halting the execution of the current handler
# and returning a helpful error message (and HTTP status code).
#
# @param [String] cause
# The reason the request is rejected for.
# @param [Optional, Integer|Symbol, Default :bad_request] status
# HTTP status code or symbol.
def reject!(cause, status=:bad_request)
raise RequestError.new(cause, status)
end
# returns the user actually logged into canvas, even if they're currently masquerading
#
# This is used by the google docs integration, among other things --
# having @real_current_user first ensures that a masquerading user never sees the
# masqueradee's files, but in general you may want to block access to google
# docs for masqueraders earlier in the request
def logged_in_user
@real_current_user || @current_user
end
def not_fake_student_user
@current_user && @current_user.fake_student? ? logged_in_user : @current_user
end
def rescue_action_dispatch_exception
rescue_action_in_public(request.env['action_dispatch.exception'])
end
# used to generate context-specific urls without having to
# check which type of context it is everywhere
def named_context_url(context, name, *opts)
if context.is_a?(UserProfile)
name = name.to_s.sub(/context/, "profile")
else
klass = context.class.base_class
name = name.to_s.sub(/context/, klass.name.underscore)
opts.unshift(context)
end
opts.push({}) unless opts[-1].is_a?(Hash)
include_host = opts[-1].delete(:include_host)
if !include_host
opts[-1][:host] = context.host_name rescue nil
opts[-1][:only_path] = true unless name.end_with?("_path")
end
self.send name, *opts
end
def self.promote_view_path(path)
self.view_paths = self.view_paths.to_ary.reject{ |p| p.to_s == path }
prepend_view_path(path)
end
protected
# we track the cost of each request in RequestThrottle in order
# to rate limit clients that are abusing the API. Some actions consume
# time or resources that are not well represented by simple time/cpu
# benchmarks, so you can use this method to increase the perceived cost
# of a request by an arbitrary amount. For an anchor, rate limiting
# kicks in when a user has exceeded 600 arbitrary units of cost (it's
# a leaky bucket, go see RequestThrottle), so using an 'amount'
# param of 600, for example, would max out the bucket immediately
def increment_request_cost(amount)
current_cost = request.env['extra-request-cost'] || 0
request.env['extra-request-cost'] = current_cost + amount
end
def assign_localizer
I18n.localizer = lambda {
infer_locale :context => @context,
:user => not_fake_student_user,
:root_account => @domain_root_account,
:session_locale => session[:locale],
:accept_language => request.headers['Accept-Language']
}
end
def set_locale
store_session_locale
assign_localizer
yield if block_given?
ensure
I18n.localizer = nil
end
def enable_request_cache(&block)
RequestCache.enable(&block)
end
def batch_statsd(&block)
CanvasStatsd::Statsd.batch(&block)
end
def store_session_locale
return unless locale = params[:session_locale]
supported_locales = I18n.available_locales.map(&:to_s)
session[:locale] = locale if supported_locales.include? locale
end
def init_body_classes
@body_classes = []
end
def set_user_id_header
headers['X-Canvas-User-Id'] ||= @current_user.global_id.to_s if @current_user
headers['X-Canvas-Real-User-Id'] ||= @real_current_user.global_id.to_s if @real_current_user
end
# make things requested from jQuery go to the "format.js" part of the "respond_to do |format|" block
# see http://codetunes.com/2009/01/31/rails-222-ajax-and-respond_to/ for why
def fix_xhr_requests
request.format = :js if request.xhr? && request.format == :html && !params[:html_xhr]
end
# scopes all time objects to the user's specified time zone
def set_time_zone
user = not_fake_student_user
if user && !user.time_zone.blank?
Time.zone = user.time_zone
if Time.zone && Time.zone.name == "UTC" && user.time_zone && user.time_zone.name.match(/\s/)
Time.zone = user.time_zone.name.split(/\s/)[1..-1].join(" ") rescue nil
end
else
Time.zone = @domain_root_account && @domain_root_account.default_time_zone
end
end
# retrieves the root account for the given domain
def load_account
@domain_root_account = request.env['canvas.domain_root_account'] || LoadAccount.default_domain_root_account
@files_domain = request.host_with_port != HostUrl.context_host(@domain_root_account) && HostUrl.is_file_host?(request.host_with_port)
@domain_root_account
end
def set_response_headers
# we can't block frames on the files domain, since files domain requests
# are typically embedded in an iframe in canvas, but the hostname is
# different
if !files_domain? && Setting.get('block_html_frames', 'true') == 'true' && !@embeddable
headers['X-Frame-Options'] = 'SAMEORIGIN'
end
RequestContextGenerator.store_request_meta(request, @context)
true
end
def files_domain?
!!@files_domain
end
def check_pending_otp
if session[:pending_otp] && params[:controller] != 'login/otp'
return render plain: "Please finish logging in", status: 403 if request.xhr?
reset_session
redirect_to login_url
end
end
def user_url(*opts)
opts[0] == @current_user && !@current_user.grants_right?(@current_user, session, :view_statistics) ?
user_profile_url(@current_user) :
super
end
def tab_enabled?(id, opts = {})
return true unless @context && @context.respond_to?(:tabs_available)
tabs = Rails.cache.fetch(['tabs_available', @context, @current_user, @domain_root_account,
session[:enrollment_uuid]].cache_key, expires_in: 1.hour) do
@context.tabs_available(@current_user,
:session => session, :include_hidden_unused => true, :root_account => @domain_root_account)
end
valid = tabs.any?{|t| t[:id] == id }
render_tab_disabled unless valid || opts[:no_render]
return valid
end
def render_tab_disabled
msg = tab_disabled_message(@context)
respond_to do |format|
format.html {
flash[:notice] = msg
redirect_to named_context_url(@context, :context_url)
}
format.json {
render :json => { :message => msg }, :status => :not_found
}
end
end
def tab_disabled_message(context)
if context.is_a?(Account)
t "#application.notices.page_disabled_for_account", "That page has been disabled for this account"
elsif context.is_a?(Course)
t "#application.notices.page_disabled_for_course", "That page has been disabled for this course"
elsif context.is_a?(Group)
t "#application.notices.page_disabled_for_group", "That page has been disabled for this group"
else
t "#application.notices.page_disabled", "That page has been disabled"
end
end
def require_password_session
if session[:used_remember_me_token]
flash[:warning] = t "#application.warnings.please_log_in", "For security purposes, please enter your password to continue"
store_location
redirect_to login_url
return false
end
true
end
def run_login_hooks
LoginHooks.run_hooks(request)
end
# checks the authorization policy for the given object using
# the vendor/plugins/adheres_to_policy plugin. If authorized,
# returns true, otherwise renders unauthorized messages and returns
# false. To be used as follows:
# if authorized_action(object, @current_user, :update)
# render
# end
def authorized_action(object, actor, rights)
can_do = object.grants_any_right?(actor, session, *Array(rights))
render_unauthorized_action unless can_do
can_do
end
alias :authorized_action? :authorized_action
def fix_ms_office_redirects
if ms_office?
# Office will follow 302's internally, until it gets to a 200. _then_ it will pop it out
# to a web browser - but you've lost your cookies! This breaks not only store_location,
# but in the case of delegated authentication where the provider does an additional
# redirect storing important information in session, makes it impossible to log in at all
render plain: '', status: 200
return false
end
true
end
def render_unauthorized_action
respond_to do |format|
@show_left_side = false
clear_crumbs
path_params = request.path_parameters
path_params[:format] = nil
@headers = !!@current_user if @headers != false
@files_domain = @account_domain && @account_domain.host_type == 'files'
format.html {
return unless fix_ms_office_redirects
store_location
return redirect_to login_url(params.permit(:authentication_provider)) if !@files_domain && !@current_user
if @context.is_a?(Course) && @context_enrollment
if @context_enrollment.inactive?
start_date = @context_enrollment.available_at
end
if @context.claimed?
@unauthorized_message = t('#application.errors.unauthorized.unpublished', "This course has not been published by the instructor yet.")
@unauthorized_reason = :unpublished
elsif start_date && start_date > Time.now.utc
@unauthorized_message = t('#application.errors.unauthorized.not_started_yet', "The course you are trying to access has not started yet. It will start %{date}.", :date => TextHelper.date_string(start_date))
@unauthorized_reason = :unpublished
end
end
render "shared/unauthorized", status: :unauthorized
}
format.zip { redirect_to(url_for(path_params)) }
format.json { render_json_unauthorized }
format.all { render plain: 'Unauthorized', status: :unauthorized }
end
set_no_cache_headers
end
# To be used as a before_action, requires controller or controller actions
# to have their urls scoped to a context in order to be valid.
# So /courses/5/assignments or groups/1/assignments would be valid, but
# not /assignments
def require_context
get_context
if !@context
if @context_is_current_user
store_location
redirect_to login_url
elsif params[:context_id]
raise ActiveRecord::RecordNotFound.new("Cannot find #{params[:context_type] || 'Context'} for ID: #{params[:context_id]}")
else
raise ActiveRecord::RecordNotFound.new("Context is required, but none found")
end
end
return @context != nil
end
def require_context_and_read_access
require_context && authorized_action(@context, @current_user, :read)
end
helper_method :clean_return_to
def require_account_context
require_context_type(Account)
end
def require_course_context
require_context_type(Course)
end
def require_context_type(klass)
unless require_context && @context.is_a?(klass)
raise ActiveRecord::RecordNotFound.new("Context must be of type '#{klass}'")
end
true
end
MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS = 3
# Can be used as a before_action, or just called from controller code.
# Assigns the variable @context to whatever context the url is scoped
# to. So /courses/5/assignments would have a @context=Course.find(5).
# Also assigns @context_membership to the membership type of @current_user
# if @current_user is a member of the context.
def get_context
unless @context
if params[:course_id]
@context = api_find(Course.active, params[:course_id])
@context.root_account = @domain_root_account if @context.root_account_id == @domain_root_account.id # no sense in refetching it
params[:context_id] = params[:course_id]
params[:context_type] = "Course"
if @context && @current_user
@context_enrollment = @context.enrollments.where(user_id: @current_user).joins(:enrollment_state).
order(Enrollment.state_by_date_rank_sql, Enrollment.type_rank_sql).readonly(false).first
end
@context_membership = @context_enrollment
check_for_readonly_enrollment_state
elsif params[:account_id] || (self.is_a?(AccountsController) && params[:account_id] = params[:id])
@context = api_find(Account, params[:account_id])
params[:context_id] = @context.id
params[:context_type] = "Account"
@context_enrollment = @context.account_users.where(user_id: @current_user.id).first if @context && @current_user
@context_membership = @context_enrollment
@account = @context
elsif params[:group_id]
@context = api_find(Group.active, params[:group_id])
params[:context_id] = params[:group_id]
params[:context_type] = "Group"
@context_enrollment = @context.group_memberships.where(user_id: @current_user).first if @context && @current_user
@context_membership = @context_enrollment
elsif params[:user_id] || (self.is_a?(UsersController) && params[:user_id] = params[:id])
@context = api_find(User, params[:user_id])
params[:context_id] = params[:user_id]
params[:context_type] = "User"
@context_membership = @context if @context == @current_user
elsif params[:course_section_id] || (self.is_a?(SectionsController) && params[:course_section_id] = params[:id])
params[:context_id] = params[:course_section_id]
params[:context_type] = "CourseSection"
@context = api_find(CourseSection, params[:course_section_id])
elsif request.path.match(/\A\/profile/) || request.path == '/' || request.path.match(/\A\/dashboard\/files/) || request.path.match(/\A\/calendar/) || request.path.match(/\A\/assignments/) || request.path.match(/\A\/files/) || request.path == '/api/v1/calendar_events/visible_contexts'
# ^ this should be split out into things on the individual controllers
@context_is_current_user = true
@context = @current_user
@context_membership = @context
end
assign_localizer if @context.present?
if request.format.html?
if @context.is_a?(Account) && !@context.root_account?
account_chain = @context.account_chain.to_a.select {|a| a.grants_right?(@current_user, session, :read) }
account_chain.slice!(0) # the first element is the current context
count = account_chain.length
account_chain.reverse.each_with_index do |a, idx|
if idx == 1 && count >= MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS
add_crumb(I18n.t('#lib.text_helper.ellipsis', '...'), nil)
elsif count >= MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS && idx > 0 && idx <= count - MAX_ACCOUNT_LINEAGE_TO_SHOW_IN_CRUMBS
next
else
add_crumb(a.short_name, account_url(a.id), :id => "crumb_#{a.asset_string}")
end
end
end
if @context && @context.respond_to?(:short_name)
crumb_url = named_context_url(@context, :context_url) if @context.grants_right?(@current_user, session, :read)
add_crumb(@context.nickname_for(@current_user, :short_name), crumb_url)
end
@set_badge_counts = true
end
end
# There is lots of interesting information set up in here, that we want
# to place into the live events context.
setup_live_events_context
end
# This is used by a number of actions to retrieve a list of all contexts
# associated with the given context. If the context is a user then it will
# include all the user's current contexts.
# Assigns it to the variable @contexts
def get_all_pertinent_contexts(opts = {})
return if @already_ran_get_all_pertinent_contexts
@already_ran_get_all_pertinent_contexts = true
raise(ArgumentError, "Need a starting context") if @context.nil?
@contexts = [@context]
only_contexts = ActiveRecord::Base.parse_asset_string_list(opts[:only_contexts] || params[:only_contexts])
if @context && @context.is_a?(User)
# we already know the user can read these courses and groups, so skip
# the grants_right? check to avoid querying for the various memberships
# again.
enrollment_scope = Enrollment.for_user(@context).current.active_by_date
include_groups = !!opts[:include_groups]
group_ids = nil
courses = []
if only_contexts.present?
# find only those courses and groups passed in the only_contexts
# parameter, but still scoped by user so we know they have rights to
# view them.
course_ids = only_contexts.select { |c| c.first == "Course" }.map(&:last)
unless course_ids.empty?
courses = Course.where(:id => course_ids).where(:id => enrollment_scope.select(:course_id)).to_a
end
if include_groups
group_ids = only_contexts.select { |c| c.first == "Group" }.map(&:last)
include_groups = false if group_ids.empty?
end
else
courses = Course.shard(opts[:cross_shard] ? @context.in_region_associated_shards : Shard.current).
where(:id => enrollment_scope.select(:course_id)).to_a
end
groups = []
if include_groups
if group_ids
Shard.partition_by_shard(group_ids) do |shard_group_ids|
groups += @context.current_groups.shard(Shard.current).where(:id => shard_group_ids).to_a
end
else
groups = @context.current_groups.shard(opts[:cross_shard] ? @context.in_region_associated_shards : Shard.current).to_a
end
end
groups.reject!{|g| g.context_type == "Course" && g.context.concluded?}
if opts[:favorites_first]
favorite_course_ids = @context.favorite_context_ids("Course")
courses = courses.sort_by {|c| [favorite_course_ids.include?(c.id) ? 0 : 1, Canvas::ICU.collation_key(c.name)]}
end
@contexts.concat courses
@contexts.concat groups
end
include_contexts = opts[:include_contexts] || params[:include_contexts]
if include_contexts
include_contexts.split(",").each do |include_context|
# don't load it again if we've already got it
next if @contexts.any? { |c| c.asset_string == include_context }
context = Context.find_by_asset_string(include_context)
@contexts << context if context && context.grants_right?(@current_user, session, :read)
end
end
@contexts = @contexts.uniq
Course.require_assignment_groups(@contexts)
@context_enrollment = @context.membership_for_user(@current_user) if @context.respond_to?(:membership_for_user)
@context_membership = @context_enrollment
end
def check_for_readonly_enrollment_state
return unless request.format.html?
if @context_enrollment && @context_enrollment.is_a?(Enrollment) && ['invited', 'active'].include?(@context_enrollment.workflow_state) && action_name != "enrollment_invitation"
state = @context_enrollment.state_based_on_date
case state
when :invited
if @context_enrollment.available_at
flash[:html_notice] = mt "#application.notices.need_to_accept_future_enrollment",
"You'll need to [accept the enrollment invitation](%{url}) before you can fully participate in this course, starting on %{date}.",
:url => course_url(@context),:date => datetime_string(@context_enrollment.available_at)
else
flash[:html_notice] = mt "#application.notices.need_to_accept_enrollment",
"You'll need to [accept the enrollment invitation](%{url}) before you can fully participate in this course.", :url => course_url(@context)
end
when :accepted
flash[:html_notice] = t("This course hasn’t started yet. You will not be able to participate in this course until %{date}.", :date => datetime_string(@context_enrollment.available_at))
end
end
end
def set_badge_counts_for(context, user, enrollment=nil)
return if @js_env && @js_env[:badge_counts].present?
return unless context.present? && user.present?
return unless context.respond_to?(:content_participation_counts) # just Course and Group so far
js_env(:badge_counts => badge_counts_for(context, user, enrollment))
end
helper_method :set_badge_counts_for
def badge_counts_for(context, user, enrollment=nil)
badge_counts = {}
['Submission'].each do |type|
participation_count = context.content_participation_counts.
where(:user_id => user.id, :content_type => type).first
participation_count ||= ContentParticipationCount.create_or_update({
:context => context,
:user => user,
:content_type => type,
})
badge_counts[type.underscore.pluralize] = participation_count.unread_count
end
badge_counts
end
def get_upcoming_assignments(course)
assignments = AssignmentGroup.visible_assignments(
@current_user,
course,
course.assignment_groups.active
).to_a
log_course(course)
if @current_user
submissions = @current_user.submissions.shard(@current_user).to_a
submissions.each{ |s| s.mute if s.muted_assignment? }
else
submissions = []
end
assignments.map! {|a| a.overridden_for(@current_user)}
sorted = SortsAssignments.by_due_date({
:assignments => assignments,
:user => @current_user,
:session => session,
:upcoming_limit => 1.week.from_now,
:submissions => submissions
})
sorted.upcoming.sort
end
def log_course(course)
log_asset_access([ "assignments", course ], "assignments", "other")
end
# Calculates the file storage quota for @context
def get_quota(context=nil)
quota_params = Attachment.get_quota(context || @context)
@quota = quota_params[:quota]
@quota_used = quota_params[:quota_used]
end
# Renders a quota exceeded message if the @context's quota is exceeded
def quota_exceeded(context=nil, redirect=nil)
context ||= @context
redirect ||= root_url
get_quota(context)
if response.body.size + @quota_used > @quota
if context.is_a?(Account)
error = t "#application.errors.quota_exceeded_account", "Account storage quota exceeded"
elsif context.is_a?(Course)
error = t "#application.errors.quota_exceeded_course", "Course storage quota exceeded"
elsif context.is_a?(Group)
error = t "#application.errors.quota_exceeded_group", "Group storage quota exceeded"
elsif context.is_a?(User)
error = t "#application.errors.quota_exceeded_user", "User storage quota exceeded"
else
error = t "#application.errors.quota_exceeded", "Storage quota exceeded"
end
respond_to do |format|
flash[:error] = error unless request.format.to_s == "text/plain"
format.html {redirect_to redirect }
format.json {render :json => {:errors => {:base => error}}, :status => :bad_request }
format.text {render :json => {:errors => {:base => error}}, :status => :bad_request }
end
return true
end
false
end
# Used to retrieve the context from a :feed_code parameter. These
# :feed_code attributes are keyed off the object type and the object's
# uuid. Using the uuid attribute gives us an unguessable url so
# that we can offer the feeds without requiring password authentication.
def get_feed_context(opts={})
pieces = params[:feed_code].split("_", 2)
if params[:feed_code].match(/\Agroup_membership/)
pieces = ["group_membership", params[:feed_code].split("_", 3)[-1]]
end
@context = nil
@problem = nil
if pieces[0] == "enrollment"
@enrollment = Enrollment.where(uuid: pieces[1]).first if pieces[1]
@context_type = "Course"
if !@enrollment
@problem = t "#application.errors.mismatched_verification_code", "The verification code does not match any currently enrolled user."
elsif @enrollment.course && !@enrollment.course.available?
@problem = t "#application.errors.feed_unpublished_course", "Feeds for this course cannot be accessed until it is published."
end
@context = @enrollment.course unless @problem
@current_user = @enrollment.user unless @problem
elsif pieces[0] == 'group_membership'
@membership = GroupMembership.active.where(uuid: pieces[1]).first if pieces[1]
@context_type = "Group"
if !@membership
@problem = t "#application.errors.mismatched_verification_code", "The verification code does not match any currently enrolled user."
elsif @membership.group && !@membership.group.available?
@problem = t "#application.errors.feed_unpublished_group", "Feeds for this group cannot be accessed until it is published."
end
@context = @membership.group unless @problem
@current_user = @membership.user unless @problem
else
@context_type = pieces[0].classify
if Context::CONTEXT_TYPES.include?(@context_type.to_sym)
@context_class = Object.const_get(@context_type, false)
@context = @context_class.where(uuid: pieces[1]).first if pieces[1]
end
if !@context
@problem = t "#application.errors.invalid_verification_code", "The verification code is invalid."
elsif (!@context.is_public rescue false) && (!@context.respond_to?(:uuid) || pieces[1] != @context.uuid)
if @context_type == 'course'
@problem = t "#application.errors.feed_private_course", "The matching course has gone private, so public feeds like this one will no longer be visible."
elsif @context_type == 'group'
@problem = t "#application.errors.feed_private_group", "The matching group has gone private, so public feeds like this one will no longer be visible."
else
@problem = t "#application.errors.feed_private", "The matching context has gone private, so public feeds like this one will no longer be visible."
end
end
@context = nil if @problem
@current_user = @context if @context.is_a?(User)
end
if !@context || (opts[:only] && !opts[:only].include?(@context.class.to_s.underscore.to_sym))
@problem ||= t("#application.errors.invalid_feed_parameters", "Invalid feed parameters.") if (opts[:only] && !opts[:only].include?(@context.class.to_s.underscore.to_sym))
@problem ||= t "#application.errors.feed_not_found", "Could not find feed."
render template: "shared/unauthorized_feed", status: :bad_request, formats: [:html]
return false
end
@context
end
def discard_flash_if_xhr
if request.xhr? || request.format.to_s == 'text/plain'
flash.discard
end
end
def cancel_cache_buster
@cancel_cache_buster = true
end
def cache_buster
# Annoying problem. If I set the cache-control to anything other than "no-cache, no-store"
# then the local cache is used when the user clicks the 'back' button. I don't know how
# to tell the browser to ALWAYS check back other than to disable caching...
return true if @cancel_cache_buster || request.xhr? || api_request?
set_no_cache_headers
end
def set_no_cache_headers
response.headers["Pragma"] = "no-cache"
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
end
def clear_cached_contexts
RoleOverride.clear_cached_contexts
end
def set_page_view
return true if !page_views_enabled?
ENV['RAILS_HOST_WITH_PORT'] ||= request.host_with_port rescue nil
# We only record page_views for html page requests coming from within the
# app, or if coming from a developer api request and specified as a
# page_view.
if @current_user && !request.xhr? && request.get?
generate_page_view
end
end
def require_reacceptance_of_terms
if session[:require_terms] && request.get? && !api_request? && !verified_file_request?
render "shared/terms_required", status: :unauthorized