session_helper.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module SessionHelper
  3. def self.json_hash(user)
  4. collections, assets = default_collections(user)
  5. {
  6. session: user.filter_unauthorized_attributes(user.filter_attributes(user.attributes)),
  7. models: models(user),
  8. collections: collections,
  9. assets: assets,
  10. }
  11. end
  12. def self.json_hash_error(error)
  13. {
  14. error: error.message,
  15. models: models,
  16. collections: {
  17. Locale.to_app_model => Locale.where(active: true),
  18. PublicLink.to_app_model => PublicLink.all,
  19. }
  20. }
  21. end
  22. def self.default_collections(user)
  23. # auto population collections, store all here
  24. default_collection = {}
  25. assets = user.assets({})
  26. # load collections to deliver from external files
  27. dir = File.expand_path('..', __dir__)
  28. files = Dir.glob("#{dir}/lib/session_helper/collection_*.rb")
  29. files.each do |file|
  30. file =~ %r{/(session_helper/collection_.*)\.rb\z}
  31. class_name = $1.camelize
  32. next if !Object.const_defined?(class_name) && Rails.env.production?
  33. (default_collection, assets) = class_name.constantize.session(default_collection, assets, user)
  34. end
  35. [default_collection, assets]
  36. end
  37. def self.models(user = nil)
  38. return models_public if user.blank?
  39. ObjectManager.list_objects.each_with_object({}) do |object, models|
  40. attributes = ObjectManager::Object.new(object).attributes(user)
  41. models[object] = attributes
  42. end
  43. end
  44. def self.models_public
  45. allowed_user_attributes = %w[firstname lastname email password]
  46. user_attributes = ObjectManager::Object.new('User').attributes(nil, skip_permission: true).select { |attribute| allowed_user_attributes.include?(attribute[:name]) }
  47. {
  48. 'User' => user_attributes,
  49. }
  50. end
  51. def self.cleanup_expired
  52. # delete temp. sessions
  53. ActiveRecord::SessionStore::Session.where('persistent IS NULL AND updated_at < ?', 2.hours.ago).delete_all
  54. # web sessions not updated the last x days
  55. ActiveRecord::SessionStore::Session.where('updated_at < ?', 60.days.ago).delete_all
  56. end
  57. def self.get(id)
  58. ActiveRecord::SessionStore::Session.find_by(id: id)
  59. end
  60. def self.list(limit = 10_000)
  61. ActiveRecord::SessionStore::Session.reorder(updated_at: :desc).limit(limit)
  62. end
  63. def self.destroy(id)
  64. session = ActiveRecord::SessionStore::Session.find_by(id: id)
  65. return if !session
  66. session.destroy
  67. end
  68. end