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.

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