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.

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