1 # frozen_string_literal: true
3 class ApplicationController
< ActionController
::Base
6 # Prevent CSRF attacks by raising an exception.
7 # For APIs, you may want to use :null_session instead.
8 protect_from_forgery with
: :exception
10 force_ssl
if: "Rails.env.production? && ENV['LOCAL_HTTPS'] == 'true'"
12 helper_method
:current_account
14 rescue_from ActionController
::RoutingError, with
: :not_found
15 rescue_from ActiveRecord
::RecordNotFound, with
: :not_found
16 rescue_from ActionController
::InvalidAuthenticityToken, with
: :unprocessable_entity
18 before_action
:store_current_location, except
: :raise_not_found, unless: :devise_controller?
19 before_action
:set_user_activity
20 before_action
:check_suspension, if: :user_signed_in?
23 raise ActionController
::RoutingError, "No route matches #{params[:unmatched_route]}"
28 def store_current_location
29 store_location_for(:user, request
.url
)
33 redirect_to root_path
unless current_user
&.admin
?
37 return unless !current_user
.nil? && (current_user
.current_sign_in_at
.nil? || current_user
.current_sign_in_at
< 24.hours
.ago
)
39 # Mark user as signed-in today
40 current_user
.update_tracked_fields(request
)
42 # If the sign in is after a two week break, we need to regenerate their feed
43 RegenerationWorker
.perform_async(current_user
.account_id
) if current_user
.last_sign_in_at
< 14.days
.ago
48 head
403 if current_user
.account
.suspended
?
54 respond_to
do |format
|
55 format
.any
{ head
404 }
56 format
.html
{ render
'errors/404', layout
: 'error', status
: 404 }
61 respond_to
do |format
|
62 format
.any
{ head
410 }
63 format
.html
{ render
'errors/410', layout
: 'error', status
: 410 }
67 def unprocessable_entity
68 respond_to
do |format
|
69 format
.any
{ head
422 }
70 format
.html
{ render
'errors/422', layout
: 'error', status
: 422 }
75 @current_account ||= current_user
.try(:account)
78 def cache_collection(raw
, klass
)
79 return raw
unless klass
.respond_to
?(:with_includes)
81 raw
= raw
.cache_ids
.to_a
if raw
.is_a
?(ActiveRecord
::Relation)
83 cached_keys_with_value
= Rails
.cache
.read_multi(*raw
.map(&:cache_key))
86 uncached_ids
<< item
.id
unless cached_keys_with_value
.key
?(item
.cache_key
)
89 klass
.reload_stale_associations!
(cached_keys_with_value
.values
) if klass
.respond_to
?(:reload_stale_associations!
)
91 unless uncached_ids
.empty
?
92 uncached
= klass
.where(id
: uncached_ids
).with_includes
.map
{ |item
| [item
.id
, item
] }.to_h
94 uncached
.values
.each
do |item
|
95 Rails
.cache
.write(item
.cache_key
, item
)
99 raw
.map
{ |item
| cached_keys_with_value
[item
.cache_key
] || uncached
[item
.id
] }.compact