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.

205 lines
5.9 KiB

Web Push Notifications (#3243) * feat: Register push subscription * feat: Notify when mentioned * feat: Boost, favourite, reply, follow, follow request * feat: Notification interaction * feat: Handle change of public key * feat: Unsubscribe if things go wrong * feat: Do not send normal notifications if push is enabled * feat: Focus client if open * refactor: Move push logic to WebPushSubscription * feat: Better title and body * feat: Localize messages * chore: Fix lint errors * feat: Settings * refactor: Lazy load * fix: Check if push settings exist * feat: Device-based preferences * refactor: Simplify logic * refactor: Pull request feedback * refactor: Pull request feedback * refactor: Create /api/web/push_subscriptions endpoint * feat: Spec PushSubscriptionController * refactor: WebPushSubscription => Web::PushSubscription * feat: Spec Web::PushSubscription * feat: Display first media attachment * feat: Support direction * fix: Stuff broken while rebasing * refactor: Integration with session activations * refactor: Cleanup * refactor: Simplify implementation * feat: Set VAPID keys via environment * chore: Comments * fix: Crash when no alerts * fix: Set VAPID keys in testing environment * fix: Follow link * feat: Notification actions * fix: Delete previous subscription * chore: Temporary logs * refactor: Move migration to a later date * fix: Fetch the correct session activation and misc bugs * refactor: Move migration to a later date * fix: Remove follow request (no notifications) * feat: Send administrator contact to push service * feat: Set time-to-live * fix: Do not show sensitive images * fix: Reducer crash in error handling * feat: Add badge * chore: Fix lint error * fix: Checkbox label overlap * fix: Check for payload support * fix: Rename action "type" (crash in latest Chrome) * feat: Action to expand notification * fix: Lint errors * fix: Unescape notification body * fix: Do not allow boosting if the status is hidden * feat: Add VAPID keys to the production sample environment * fix: Strip HTML tags from status * refactor: Better error messages * refactor: Handle browser not implementing the VAPID protocol (Samsung Internet) * fix: Error when target_status is nil * fix: Handle lack of image * fix: Delete reference to invalid subscriptions * feat: Better error handling * fix: Unescape HTML characters after tags are striped * refactor: Simpify code * fix: Modify to work with #4091 * Sort strings alphabetically * i18n: Updated Polish translation it annoys me that it's not fully localized :P * refactor: Use current_session in PushSubscriptionController * fix: Rebase mistake * fix: Set cacheName to mastodon * refactor: Pull request feedback * refactor: Remove logging statements * chore(yarn): Fix conflicts with master * chore(yarn): Copy latest from master * chore(yarn): Readd offline-plugin * refactor: Use save! and update! * refactor: Send notifications async * fix: Allow retry when push fails * fix: Save track for failed pushes * fix: Minify sw.js * fix: Remove account_id from fabricator
6 years ago
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: users
  5. #
  6. # id :integer not null, primary key
  7. # email :string default(""), not null
  8. # created_at :datetime not null
  9. # updated_at :datetime not null
  10. # encrypted_password :string default(""), not null
  11. # reset_password_token :string
  12. # reset_password_sent_at :datetime
  13. # remember_created_at :datetime
  14. # sign_in_count :integer default(0), not null
  15. # current_sign_in_at :datetime
  16. # last_sign_in_at :datetime
  17. # current_sign_in_ip :inet
  18. # last_sign_in_ip :inet
  19. # admin :boolean default(FALSE), not null
  20. # confirmation_token :string
  21. # confirmed_at :datetime
  22. # confirmation_sent_at :datetime
  23. # unconfirmed_email :string
  24. # locale :string
  25. # encrypted_otp_secret :string
  26. # encrypted_otp_secret_iv :string
  27. # encrypted_otp_secret_salt :string
  28. # consumed_timestep :integer
  29. # otp_required_for_login :boolean default(FALSE), not null
  30. # last_emailed_at :datetime
  31. # otp_backup_codes :string is an Array
  32. # filtered_languages :string default([]), not null, is an Array
  33. # account_id :integer not null
  34. # disabled :boolean default(FALSE), not null
  35. # moderator :boolean default(FALSE), not null
  36. # invite_id :integer
  37. #
  38. class User < ApplicationRecord
  39. include Settings::Extend
  40. ACTIVE_DURATION = 14.days
  41. devise :registerable, :recoverable,
  42. :rememberable, :trackable, :validatable, :confirmable,
  43. :two_factor_authenticatable, :two_factor_backupable,
  44. otp_secret_encryption_key: ENV['OTP_SECRET'],
  45. otp_number_of_backup_codes: 10
  46. belongs_to :account, inverse_of: :user, required: true
  47. belongs_to :invite, counter_cache: :uses
  48. accepts_nested_attributes_for :account
  49. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  50. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  51. validates_with BlacklistedEmailValidator, if: :email_changed?
  52. scope :recent, -> { order(id: :desc) }
  53. scope :admins, -> { where(admin: true) }
  54. scope :moderators, -> { where(moderator: true) }
  55. scope :staff, -> { admins.or(moderators) }
  56. scope :confirmed, -> { where.not(confirmed_at: nil) }
  57. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  58. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended: false }) }
  59. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  60. scope :with_recent_ip_address, ->(value) { where(arel_table[:current_sign_in_ip].eq(value).or(arel_table[:last_sign_in_ip].eq(value))) }
  61. before_validation :sanitize_languages
  62. # This avoids a deprecation warning from Rails 5.1
  63. # It seems possible that a future release of devise-two-factor will
  64. # handle this itself, and this can be removed from our User class.
  65. attribute :otp_secret
  66. has_many :session_activations, dependent: :destroy
  67. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  68. :reduce_motion, :system_font_ui, :noindex, :theme,
  69. to: :settings, prefix: :setting, allow_nil: false
  70. attr_accessor :invite_code
  71. def confirmed?
  72. confirmed_at.present?
  73. end
  74. def staff?
  75. admin? || moderator?
  76. end
  77. def role
  78. if admin?
  79. 'admin'
  80. elsif moderator?
  81. 'moderator'
  82. else
  83. 'user'
  84. end
  85. end
  86. def role?(role)
  87. case role
  88. when 'user'
  89. true
  90. when 'moderator'
  91. staff?
  92. when 'admin'
  93. admin?
  94. else
  95. false
  96. end
  97. end
  98. def disable!
  99. update!(disabled: true,
  100. last_sign_in_at: current_sign_in_at,
  101. current_sign_in_at: nil)
  102. end
  103. def enable!
  104. update!(disabled: false)
  105. end
  106. def confirm!
  107. skip_confirmation!
  108. save!
  109. end
  110. def promote!
  111. if moderator?
  112. update!(moderator: false, admin: true)
  113. elsif !admin?
  114. update!(moderator: true)
  115. end
  116. end
  117. def demote!
  118. if admin?
  119. update!(admin: false, moderator: true)
  120. elsif moderator?
  121. update!(moderator: false)
  122. end
  123. end
  124. def disable_two_factor!
  125. self.otp_required_for_login = false
  126. otp_backup_codes&.clear
  127. save!
  128. end
  129. def active_for_authentication?
  130. super && !disabled?
  131. end
  132. def setting_default_privacy
  133. settings.default_privacy || (account.locked? ? 'private' : 'public')
  134. end
  135. def token_for_app(a)
  136. return nil if a.nil? || a.owner != self
  137. Doorkeeper::AccessToken
  138. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  139. t.scopes = a.scopes
  140. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  141. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  142. end
  143. end
  144. def activate_session(request)
  145. session_activations.activate(session_id: SecureRandom.hex,
  146. user_agent: request.user_agent,
  147. ip: request.remote_ip).session_id
  148. end
  149. def exclusive_session(id)
  150. session_activations.exclusive(id)
  151. end
  152. def session_active?(id)
  153. session_activations.active? id
  154. end
  155. def web_push_subscription(session)
  156. session.web_push_subscription.nil? ? nil : session.web_push_subscription.as_payload
  157. end
  158. def invite_code=(code)
  159. self.invite = Invite.find_by(code: code) unless code.blank?
  160. @invite_code = code
  161. end
  162. protected
  163. def send_devise_notification(notification, *args)
  164. devise_mailer.send(notification, self, *args).deliver_later
  165. end
  166. private
  167. def sanitize_languages
  168. filtered_languages.reject!(&:blank?)
  169. end
  170. end