You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.5 KiB

8 years ago
7 years ago
7 years ago
7 years ago
8 years ago
  1. # frozen_string_literal: true
  2. class ApplicationController < ActionController::Base
  3. # Prevent CSRF attacks by raising an exception.
  4. # For APIs, you may want to use :null_session instead.
  5. protect_from_forgery with: :exception
  6. force_ssl if: "Rails.env.production? && ENV['LOCAL_HTTPS'] == 'true'"
  7. helper_method :current_account
  8. rescue_from ActionController::RoutingError, with: :not_found
  9. rescue_from ActiveRecord::RecordNotFound, with: :not_found
  10. before_action :store_current_location, except: :raise_not_found, unless: :devise_controller?
  11. before_action :set_locale
  12. before_action :set_user_activity
  13. before_action :check_suspension, if: :user_signed_in?
  14. def raise_not_found
  15. raise ActionController::RoutingError, "No route matches #{params[:unmatched_route]}"
  16. end
  17. private
  18. def store_current_location
  19. store_location_for(:user, request.url)
  20. end
  21. def set_locale
  22. I18n.locale = current_user.try(:locale) || I18n.default_locale
  23. rescue I18n::InvalidLocale
  24. I18n.locale = I18n.default_locale
  25. end
  26. def require_admin!
  27. redirect_to root_path unless current_user&.admin?
  28. end
  29. def set_user_activity
  30. current_user.touch(:current_sign_in_at) if !current_user.nil? && (current_user.current_sign_in_at.nil? || current_user.current_sign_in_at < 24.hours.ago)
  31. end
  32. def check_suspension
  33. head 403 if current_user.account.suspended?
  34. end
  35. protected
  36. def not_found
  37. respond_to do |format|
  38. format.any { head 404 }
  39. end
  40. end
  41. def gone
  42. respond_to do |format|
  43. format.any { head 410 }
  44. end
  45. end
  46. def current_account
  47. @current_account ||= current_user.try(:account)
  48. end
  49. def cache_collection(raw, klass)
  50. return raw unless klass.respond_to?(:with_includes)
  51. raw = raw.cache_ids.to_a if raw.is_a?(ActiveRecord::Relation)
  52. uncached_ids = []
  53. cached_keys_with_value = Rails.cache.read_multi(*raw.map(&:cache_key))
  54. raw.each do |item|
  55. uncached_ids << item.id unless cached_keys_with_value.key?(item.cache_key)
  56. end
  57. klass.reload_stale_associations!(cached_keys_with_value.values) if klass.respond_to?(:reload_stale_associations!)
  58. unless uncached_ids.empty?
  59. uncached = klass.where(id: uncached_ids).with_includes.map { |item| [item.id, item] }.to_h
  60. uncached.values.each do |item|
  61. Rails.cache.write(item.cache_key, item)
  62. end
  63. end
  64. raw.map { |item| cached_keys_with_value[item.cache_key] || uncached[item.id] }.compact
  65. end
  66. end