session_helper.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Copyright (C) 2012-2023 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. models = {}
  39. objects = ObjectManager.list_objects
  40. objects.each do |object|
  41. # User related fields are needed for register.
  42. next if user.nil? && !object.eql?('User')
  43. attributes = ObjectManager::Object.new(object).attributes(user, skip_permission: user.nil?)
  44. models[object] = attributes
  45. end
  46. models
  47. end
  48. def self.cleanup_expired
  49. # delete temp. sessions
  50. ActiveRecord::SessionStore::Session.where('persistent IS NULL AND updated_at < ?', 2.hours.ago).delete_all
  51. # web sessions not updated the last x days
  52. ActiveRecord::SessionStore::Session.where('updated_at < ?', 60.days.ago).delete_all
  53. end
  54. def self.get(id)
  55. ActiveRecord::SessionStore::Session.find_by(id: id)
  56. end
  57. def self.list(limit = 10_000)
  58. ActiveRecord::SessionStore::Session.reorder(updated_at: :desc).limit(limit)
  59. end
  60. def self.destroy(id)
  61. session = ActiveRecord::SessionStore::Session.find_by(id: id)
  62. return if !session
  63. session.destroy
  64. end
  65. end