session_helper.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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
  47. .new('User')
  48. .attributes(nil, skip_permission: true)
  49. .select { |attribute| allowed_user_attributes.include?(attribute[:name]) }
  50. {
  51. 'User' => user_attributes,
  52. }
  53. end
  54. def self.cleanup_expired
  55. # delete temp. sessions
  56. ActiveRecord::SessionStore::Session
  57. .where(persistent: nil, updated_at: ...2.hours.ago)
  58. .delete_all
  59. # web sessions not updated the last x days
  60. ActiveRecord::SessionStore::Session
  61. .where(updated_at: ...60.days.ago)
  62. .delete_all
  63. end
  64. def self.get(id)
  65. ActiveRecord::SessionStore::Session.find_by(id: id)
  66. end
  67. def self.list(limit = 10_000)
  68. ActiveRecord::SessionStore::Session.reorder(updated_at: :desc).limit(limit)
  69. end
  70. def self.destroy(id)
  71. ActiveRecord::SessionStore::Session
  72. .find_by(id: id)
  73. &.destroy
  74. end
  75. end