session_activation.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: session_activations
  5. #
  6. # id :integer not null, primary key
  7. # user_id :integer not null
  8. # session_id :string not null
  9. # created_at :datetime not null
  10. # updated_at :datetime not null
  11. # user_agent :string default(""), not null
  12. # ip :inet
  13. # access_token_id :integer
  14. # web_push_subscription_id :integer
  15. #
  16. # id :integer not null, primary key
  17. # user_id :integer not null
  18. # session_id :string not null
  19. # created_at :datetime not null
  20. # updated_at :datetime not null
  21. # user_agent :string default(""), not null
  22. # ip :inet
  23. # access_token_id :integer
  24. #
  25. class SessionActivation < ApplicationRecord
  26. belongs_to :user, inverse_of: :session_activations, required: true
  27. belongs_to :access_token, class_name: 'Doorkeeper::AccessToken', dependent: :destroy
  28. belongs_to :web_push_subscription, class_name: 'Web::PushSubscription', dependent: :destroy
  29. delegate :token,
  30. to: :access_token,
  31. allow_nil: true
  32. def detection
  33. @detection ||= Browser.new(user_agent)
  34. end
  35. def browser
  36. detection.id
  37. end
  38. def platform
  39. detection.platform.id
  40. end
  41. before_create :assign_access_token
  42. before_save :assign_user_agent
  43. class << self
  44. def active?(id)
  45. id && where(session_id: id).exists?
  46. end
  47. def activate(options = {})
  48. activation = create!(options)
  49. purge_old
  50. activation
  51. end
  52. def deactivate(id)
  53. return unless id
  54. where(session_id: id).destroy_all
  55. end
  56. def purge_old
  57. order('created_at desc').offset(Rails.configuration.x.max_session_activations).destroy_all
  58. end
  59. def exclusive(id)
  60. where('session_id != ?', id).destroy_all
  61. end
  62. end
  63. private
  64. def assign_user_agent
  65. self.user_agent = '' if user_agent.nil?
  66. end
  67. def assign_access_token
  68. superapp = Doorkeeper::Application.find_by(superapp: true)
  69. self.access_token = Doorkeeper::AccessToken.create!(application_id: superapp&.id,
  70. resource_owner_id: user_id,
  71. scopes: 'read write follow',
  72. expires_in: Doorkeeper.configuration.access_token_expires_in,
  73. use_refresh_token: Doorkeeper.configuration.refresh_token_enabled?)
  74. end
  75. end