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.

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