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.

316 lines
8.5 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. # remember_token :string
  38. #
  39. class User < ApplicationRecord
  40. include Settings::Extend
  41. ACTIVE_DURATION = 14.days
  42. devise :two_factor_authenticatable,
  43. otp_secret_encryption_key: ENV['OTP_SECRET']
  44. devise :two_factor_backupable,
  45. otp_number_of_backup_codes: 10
  46. devise :registerable, :recoverable, :rememberable, :trackable, :validatable,
  47. :confirmable
  48. devise :pam_authenticatable
  49. belongs_to :account, inverse_of: :user
  50. belongs_to :invite, counter_cache: :uses, optional: true
  51. accepts_nested_attributes_for :account
  52. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  53. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  54. validates_with BlacklistedEmailValidator, if: :email_changed?
  55. scope :recent, -> { order(id: :desc) }
  56. scope :admins, -> { where(admin: true) }
  57. scope :moderators, -> { where(moderator: true) }
  58. scope :staff, -> { admins.or(moderators) }
  59. scope :confirmed, -> { where.not(confirmed_at: nil) }
  60. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  61. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended: false }) }
  62. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  63. scope :with_recent_ip_address, ->(value) { where(arel_table[:current_sign_in_ip].eq(value).or(arel_table[:last_sign_in_ip].eq(value))) }
  64. before_validation :sanitize_languages
  65. # This avoids a deprecation warning from Rails 5.1
  66. # It seems possible that a future release of devise-two-factor will
  67. # handle this itself, and this can be removed from our User class.
  68. attribute :otp_secret
  69. has_many :session_activations, dependent: :destroy
  70. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  71. :reduce_motion, :system_font_ui, :noindex, :theme,
  72. to: :settings, prefix: :setting, allow_nil: false
  73. attr_accessor :invite_code
  74. def pam_conflict(_)
  75. # block pam login tries on traditional account
  76. nil
  77. end
  78. def pam_conflict?
  79. return false unless Devise.pam_authentication
  80. encrypted_password.present? && is_pam_account?
  81. end
  82. def pam_get_name
  83. return account.username if account.present?
  84. super
  85. end
  86. def pam_setup(_attributes)
  87. acc = Account.new(username: pam_get_name)
  88. acc.save!(validate: false)
  89. self.email = "#{acc.username}@#{find_pam_suffix}" if email.nil? && find_pam_suffix
  90. self.confirmed_at = Time.now.utc
  91. self.admin = false
  92. self.account = acc
  93. acc.destroy! unless save
  94. end
  95. def confirmed?
  96. confirmed_at.present?
  97. end
  98. def staff?
  99. admin? || moderator?
  100. end
  101. def role
  102. if admin?
  103. 'admin'
  104. elsif moderator?
  105. 'moderator'
  106. else
  107. 'user'
  108. end
  109. end
  110. def role?(role)
  111. case role
  112. when 'user'
  113. true
  114. when 'moderator'
  115. staff?
  116. when 'admin'
  117. admin?
  118. else
  119. false
  120. end
  121. end
  122. def disable!
  123. update!(disabled: true,
  124. last_sign_in_at: current_sign_in_at,
  125. current_sign_in_at: nil)
  126. end
  127. def enable!
  128. update!(disabled: false)
  129. end
  130. def confirm
  131. new_user = !confirmed?
  132. super
  133. prepare_new_user! if new_user
  134. end
  135. def confirm!
  136. new_user = !confirmed?
  137. skip_confirmation!
  138. save!
  139. prepare_new_user! if new_user
  140. end
  141. def update_tracked_fields!(request)
  142. super
  143. prepare_returning_user!
  144. end
  145. def promote!
  146. if moderator?
  147. update!(moderator: false, admin: true)
  148. elsif !admin?
  149. update!(moderator: true)
  150. end
  151. end
  152. def demote!
  153. if admin?
  154. update!(admin: false, moderator: true)
  155. elsif moderator?
  156. update!(moderator: false)
  157. end
  158. end
  159. def disable_two_factor!
  160. self.otp_required_for_login = false
  161. otp_backup_codes&.clear
  162. save!
  163. end
  164. def active_for_authentication?
  165. super && !disabled?
  166. end
  167. def setting_default_privacy
  168. settings.default_privacy || (account.locked? ? 'private' : 'public')
  169. end
  170. def allows_digest_emails?
  171. settings.notification_emails['digest']
  172. end
  173. def token_for_app(a)
  174. return nil if a.nil? || a.owner != self
  175. Doorkeeper::AccessToken
  176. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  177. t.scopes = a.scopes
  178. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  179. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  180. end
  181. end
  182. def activate_session(request)
  183. session_activations.activate(session_id: SecureRandom.hex,
  184. user_agent: request.user_agent,
  185. ip: request.remote_ip).session_id
  186. end
  187. def exclusive_session(id)
  188. session_activations.exclusive(id)
  189. end
  190. def session_active?(id)
  191. session_activations.active? id
  192. end
  193. def web_push_subscription(session)
  194. session.web_push_subscription.nil? ? nil : session.web_push_subscription.as_payload
  195. end
  196. def invite_code=(code)
  197. self.invite = Invite.find_by(code: code) unless code.blank?
  198. @invite_code = code
  199. end
  200. def password_required?
  201. return false if Devise.pam_authentication
  202. super
  203. end
  204. def send_reset_password_instructions
  205. return false if encrypted_password.blank? && Devise.pam_authentication
  206. super
  207. end
  208. def reset_password!(new_password, new_password_confirmation)
  209. return false if encrypted_password.blank? && Devise.pam_authentication
  210. super
  211. end
  212. def self.pam_get_user(attributes = {})
  213. if attributes[:email]
  214. resource =
  215. if Devise.check_at_sign && !attributes[:email].index('@')
  216. joins(:account).find_by(accounts: { username: attributes[:email] })
  217. else
  218. find_by(email: attributes[:email])
  219. end
  220. if resource.blank?
  221. resource = new(email: attributes[:email])
  222. if Devise.check_at_sign && !resource[:email].index('@')
  223. resource[:email] = "#{attributes[:email]}@#{resource.find_pam_suffix}"
  224. end
  225. end
  226. resource
  227. end
  228. end
  229. def self.authenticate_with_pam(attributes = {})
  230. return nil unless Devise.pam_authentication
  231. super
  232. end
  233. protected
  234. def send_devise_notification(notification, *args)
  235. devise_mailer.send(notification, self, *args).deliver_later
  236. end
  237. private
  238. def sanitize_languages
  239. filtered_languages.reject!(&:blank?)
  240. end
  241. def prepare_new_user!
  242. BootstrapTimelineWorker.perform_async(account_id)
  243. ActivityTracker.increment('activity:accounts:local')
  244. UserMailer.welcome(self).deliver_later
  245. end
  246. def prepare_returning_user!
  247. ActivityTracker.record('activity:logins', id)
  248. regenerate_feed! if needs_feed_update?
  249. end
  250. def regenerate_feed!
  251. Redis.current.setnx("account:#{account_id}:regeneration", true) && Redis.current.expire("account:#{account_id}:regeneration", 1.day.seconds)
  252. RegenerationWorker.perform_async(account_id)
  253. end
  254. def needs_feed_update?
  255. last_sign_in_at < ACTIVE_DURATION.ago
  256. end
  257. end