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.

80 lines
2.0 KiB

  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. #
  15. class SessionActivation < ApplicationRecord
  16. belongs_to :access_token, class_name: 'Doorkeeper::AccessToken', dependent: :destroy
  17. delegate :token,
  18. to: :access_token,
  19. allow_nil: true
  20. def detection
  21. @detection ||= Browser.new(user_agent)
  22. end
  23. def browser
  24. detection.id
  25. end
  26. def platform
  27. detection.platform.id
  28. end
  29. before_create :assign_access_token
  30. before_save :assign_user_agent
  31. class << self
  32. def active?(id)
  33. id && where(session_id: id).exists?
  34. end
  35. def activate(options = {})
  36. activation = create!(options)
  37. purge_old
  38. activation
  39. end
  40. def deactivate(id)
  41. return unless id
  42. where(session_id: id).destroy_all
  43. end
  44. def purge_old
  45. order('created_at desc').offset(Rails.configuration.x.max_session_activations).destroy_all
  46. end
  47. def exclusive(id)
  48. where('session_id != ?', id).destroy_all
  49. end
  50. end
  51. private
  52. def assign_user_agent
  53. self.user_agent = '' if user_agent.nil?
  54. end
  55. def assign_access_token
  56. superapp = Doorkeeper::Application.find_by(superapp: true)
  57. return if superapp.nil?
  58. self.access_token = Doorkeeper::AccessToken.create!(application_id: superapp.id,
  59. resource_owner_id: user_id,
  60. scopes: 'read write follow',
  61. expires_in: Doorkeeper.configuration.access_token_expires_in,
  62. use_refresh_token: Doorkeeper.configuration.refresh_token_enabled?)
  63. end
  64. end