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.

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