1 # frozen_string_literal: true
3 class ApplicationController
< ActionController
::Base
4 # Prevent CSRF attacks by raising an exception.
5 # For APIs, you may want to use :null_session instead.
6 protect_from_forgery with
: :exception
8 force_ssl
if: "Rails.env.production? && ENV['LOCAL_HTTPS'] == 'true'"
11 helper_method
:current_account
13 rescue_from ActionController
::RoutingError, with
: :not_found
14 rescue_from ActiveRecord
::RecordNotFound, with
: :not_found
15 rescue_from ActionController
::InvalidAuthenticityToken, with
: :unprocessable_entity
17 before_action
:store_current_location, except
: :raise_not_found, unless: :devise_controller?
18 before_action
:set_user_activity
19 before_action
:check_suspension, if: :user_signed_in?
22 raise ActionController
::RoutingError, "No route matches #{params[:unmatched_route]}"
27 def store_current_location
28 store_location_for(:user, request
.url
)
32 redirect_to root_path
unless current_user
&.admin
?
36 return unless !current_user
.nil? && (current_user
.current_sign_in_at
.nil? || current_user
.current_sign_in_at
< 24.hours
.ago
)
38 # Mark user as signed-in today
39 current_user
.update_tracked_fields(request
)
41 # If the sign in is after a two week break, we need to regenerate their feed
42 RegenerationWorker
.perform_async(current_user
.account_id
) if current_user
.last_sign_in_at
< 14.days
.ago
46 head
403 if current_user
.account
.suspended
?
52 respond_to
do |format
|
53 format
.any
{ head
404 }
54 format
.html
{ render
'errors/404', layout
: 'error', status
: 404 }
59 respond_to
do |format
|
60 format
.any
{ head
410 }
61 format
.html
{ render
'errors/410', layout
: 'error', status
: 410 }
65 def unprocessable_entity
66 respond_to
do |format
|
67 format
.any
{ head
422 }
68 format
.html
{ render
'errors/422', layout
: 'error', status
: 422 }
73 @current_account ||= current_user
.try(:account)
76 def cache_collection(raw
, klass
)
77 return raw
unless klass
.respond_to
?(:with_includes)
79 raw
= raw
.cache_ids
.to_a
if raw
.is_a
?(ActiveRecord
::Relation)
81 cached_keys_with_value
= Rails
.cache
.read_multi(*raw
.map(&:cache_key))
84 uncached_ids
<< item
.id
unless cached_keys_with_value
.key
?(item
.cache_key
)
87 klass
.reload_stale_associations!
(cached_keys_with_value
.values
) if klass
.respond_to
?(:reload_stale_associations!
)
89 unless uncached_ids
.empty
?
90 uncached
= klass
.where(id
: uncached_ids
).with_includes
.map
{ |item
| [item
.id
, item
] }.to_h
92 uncached
.values
.each
do |item
|
93 Rails
.cache
.write(item
.cache_key
, item
)
97 raw
.map
{ |item
| cached_keys_with_value
[item
.cache_key
] || uncached
[item
.id
] }.compact