user.rb 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. # sign_in_count :integer default(0), not null
  14. # current_sign_in_at :datetime
  15. # last_sign_in_at :datetime
  16. # admin :boolean default(FALSE), not null
  17. # confirmation_token :string
  18. # confirmed_at :datetime
  19. # confirmation_sent_at :datetime
  20. # unconfirmed_email :string
  21. # locale :string
  22. # encrypted_otp_secret :string
  23. # encrypted_otp_secret_iv :string
  24. # encrypted_otp_secret_salt :string
  25. # consumed_timestep :integer
  26. # otp_required_for_login :boolean default(FALSE), not null
  27. # last_emailed_at :datetime
  28. # otp_backup_codes :string is an Array
  29. # filtered_languages :string default([]), not null, is an Array
  30. # account_id :bigint(8) not null
  31. # disabled :boolean default(FALSE), not null
  32. # moderator :boolean default(FALSE), not null
  33. # invite_id :bigint(8)
  34. # chosen_languages :string is an Array
  35. # created_by_application_id :bigint(8)
  36. # approved :boolean default(TRUE), not null
  37. # sign_in_token :string
  38. # sign_in_token_sent_at :datetime
  39. # webauthn_id :string
  40. # sign_up_ip :inet
  41. # skip_sign_in_token :boolean
  42. #
  43. class User < ApplicationRecord
  44. self.ignored_columns = %w(
  45. remember_created_at
  46. remember_token
  47. current_sign_in_ip
  48. last_sign_in_ip
  49. skip_sign_in_token
  50. )
  51. include Settings::Extend
  52. include UserRoles
  53. include Redisable
  54. include LanguagesHelper
  55. # The home and list feeds will be stored in Redis for this amount
  56. # of time, and status fan-out to followers will include only people
  57. # within this time frame. Lowering the duration may improve performance
  58. # if lots of people sign up, but not a lot of them check their feed
  59. # every day. Raising the duration reduces the amount of expensive
  60. # RegenerationWorker jobs that need to be run when those people come
  61. # to check their feed
  62. ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
  63. devise :two_factor_authenticatable,
  64. otp_secret_encryption_key: Rails.configuration.x.otp_secret
  65. devise :two_factor_backupable,
  66. otp_number_of_backup_codes: 10
  67. devise :registerable, :recoverable, :validatable,
  68. :confirmable
  69. include Omniauthable
  70. include PamAuthenticable
  71. include LdapAuthenticable
  72. belongs_to :account, inverse_of: :user
  73. belongs_to :invite, counter_cache: :uses, optional: true
  74. belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
  75. accepts_nested_attributes_for :account
  76. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  77. has_many :backups, inverse_of: :user
  78. has_many :invites, inverse_of: :user
  79. has_many :markers, inverse_of: :user, dependent: :destroy
  80. has_many :webauthn_credentials, dependent: :destroy
  81. has_many :ips, class_name: 'UserIp', inverse_of: :user
  82. has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  83. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? && !Setting.require_invite_text }
  84. validates :invite_request, presence: true, on: :create, if: :invite_text_required?
  85. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  86. validates_with BlacklistedEmailValidator, if: -> { !confirmed? }
  87. validates_with EmailMxValidator, if: :validate_email_dns?
  88. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  89. # Honeypot/anti-spam fields
  90. attr_accessor :registration_form_time, :website, :confirm_password
  91. validates_with RegistrationFormTimeValidator, on: :create
  92. validates :website, absence: true, on: :create
  93. validates :confirm_password, absence: true, on: :create
  94. scope :recent, -> { order(id: :desc) }
  95. scope :pending, -> { where(approved: false) }
  96. scope :approved, -> { where(approved: true) }
  97. scope :confirmed, -> { where.not(confirmed_at: nil) }
  98. scope :enabled, -> { where(disabled: false) }
  99. scope :disabled, -> { where(disabled: true) }
  100. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  101. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
  102. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  103. scope :matches_ip, ->(value) { left_joins(:ips).where('user_ips.ip <<= ?', value).group('users.id') }
  104. scope :emailable, -> { confirmed.enabled.joins(:account).merge(Account.searchable) }
  105. before_validation :sanitize_languages
  106. before_create :set_approved
  107. after_commit :send_pending_devise_notifications
  108. # This avoids a deprecation warning from Rails 5.1
  109. # It seems possible that a future release of devise-two-factor will
  110. # handle this itself, and this can be removed from our User class.
  111. attribute :otp_secret
  112. has_many :session_activations, dependent: :destroy
  113. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  114. :reduce_motion, :system_font_ui, :noindex, :theme, :display_media,
  115. :expand_spoilers, :default_language, :aggregate_reblogs, :show_application,
  116. :advanced_layout, :use_blurhash, :use_pending_items, :trends, :crop_images,
  117. :disable_swiping, :always_send_emails,
  118. to: :settings, prefix: :setting, allow_nil: false
  119. attr_reader :invite_code
  120. attr_writer :external, :bypass_invite_request_check
  121. def confirmed?
  122. confirmed_at.present?
  123. end
  124. def invited?
  125. invite_id.present?
  126. end
  127. def valid_invitation?
  128. invite_id.present? && invite.valid_for_use?
  129. end
  130. def disable!
  131. update!(disabled: true)
  132. end
  133. def enable!
  134. update!(disabled: false)
  135. end
  136. def confirm
  137. new_user = !confirmed?
  138. self.approved = true if open_registrations? && !sign_up_from_ip_requires_approval?
  139. super
  140. if new_user && approved?
  141. prepare_new_user!
  142. elsif new_user
  143. notify_staff_about_pending_account!
  144. end
  145. end
  146. def confirm!
  147. new_user = !confirmed?
  148. self.approved = true if open_registrations?
  149. skip_confirmation!
  150. save!
  151. prepare_new_user! if new_user && approved?
  152. end
  153. def update_sign_in!(new_sign_in: false)
  154. old_current, new_current = current_sign_in_at, Time.now.utc
  155. self.last_sign_in_at = old_current || new_current
  156. self.current_sign_in_at = new_current
  157. if new_sign_in
  158. self.sign_in_count ||= 0
  159. self.sign_in_count += 1
  160. end
  161. save(validate: false) unless new_record?
  162. prepare_returning_user!
  163. end
  164. def pending?
  165. !approved?
  166. end
  167. def active_for_authentication?
  168. !account.memorial?
  169. end
  170. def functional?
  171. confirmed? && approved? && !disabled? && !account.suspended? && !account.memorial? && account.moved_to_account_id.nil?
  172. end
  173. def unconfirmed?
  174. !confirmed?
  175. end
  176. def unconfirmed_or_pending?
  177. unconfirmed? || pending?
  178. end
  179. def inactive_message
  180. !approved? ? :pending : super
  181. end
  182. def approve!
  183. return if approved?
  184. update!(approved: true)
  185. prepare_new_user!
  186. end
  187. def otp_enabled?
  188. otp_required_for_login
  189. end
  190. def webauthn_enabled?
  191. webauthn_credentials.any?
  192. end
  193. def two_factor_enabled?
  194. otp_required_for_login? || webauthn_credentials.any?
  195. end
  196. def disable_two_factor!
  197. self.otp_required_for_login = false
  198. self.otp_secret = nil
  199. otp_backup_codes&.clear
  200. webauthn_credentials.destroy_all if webauthn_enabled?
  201. save!
  202. end
  203. def preferred_posting_language
  204. valid_locale_cascade(settings.default_language, locale)
  205. end
  206. def setting_default_privacy
  207. settings.default_privacy || (account.locked? ? 'private' : 'public')
  208. end
  209. def allows_digest_emails?
  210. settings.notification_emails['digest']
  211. end
  212. def allows_report_emails?
  213. settings.notification_emails['report']
  214. end
  215. def allows_pending_account_emails?
  216. settings.notification_emails['pending_account']
  217. end
  218. def allows_appeal_emails?
  219. settings.notification_emails['appeal']
  220. end
  221. def allows_trends_review_emails?
  222. settings.notification_emails['trending_tag']
  223. end
  224. def aggregates_reblogs?
  225. @aggregates_reblogs ||= settings.aggregate_reblogs
  226. end
  227. def shows_application?
  228. @shows_application ||= settings.show_application
  229. end
  230. def token_for_app(app)
  231. return nil if app.nil? || app.owner != self
  232. Doorkeeper::AccessToken.find_or_create_by(application_id: app.id, resource_owner_id: id) do |t|
  233. t.scopes = app.scopes
  234. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  235. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  236. end
  237. end
  238. def activate_session(request)
  239. session_activations.activate(
  240. session_id: SecureRandom.hex,
  241. user_agent: request.user_agent,
  242. ip: request.remote_ip
  243. ).session_id
  244. end
  245. def clear_other_sessions(id)
  246. session_activations.exclusive(id)
  247. end
  248. def web_push_subscription(session)
  249. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  250. end
  251. def invite_code=(code)
  252. self.invite = Invite.find_by(code: code) if code.present?
  253. @invite_code = code
  254. end
  255. def password_required?
  256. return false if external?
  257. super
  258. end
  259. def external_or_valid_password?(compare_password)
  260. # If encrypted_password is blank, we got the user from LDAP or PAM,
  261. # so credentials are already valid
  262. encrypted_password.blank? || valid_password?(compare_password)
  263. end
  264. def send_reset_password_instructions
  265. return false if encrypted_password.blank?
  266. super
  267. end
  268. def reset_password(new_password, new_password_confirmation)
  269. return false if encrypted_password.blank?
  270. super
  271. end
  272. def reset_password!
  273. # First, change password to something random and deactivate all sessions
  274. transaction do
  275. update(password: SecureRandom.hex)
  276. session_activations.destroy_all
  277. end
  278. # Then, remove all authorized applications and connected push subscriptions
  279. Doorkeeper::AccessGrant.by_resource_owner(self).in_batches.update_all(revoked_at: Time.now.utc)
  280. Doorkeeper::AccessToken.by_resource_owner(self).in_batches do |batch|
  281. batch.update_all(revoked_at: Time.now.utc)
  282. Web::PushSubscription.where(access_token_id: batch).delete_all
  283. end
  284. # Finally, send a reset password prompt to the user
  285. send_reset_password_instructions
  286. end
  287. def show_all_media?
  288. setting_display_media == 'show_all'
  289. end
  290. def hide_all_media?
  291. setting_display_media == 'hide_all'
  292. end
  293. protected
  294. def send_devise_notification(notification, *args, **kwargs)
  295. # This method can be called in `after_update` and `after_commit` hooks,
  296. # but we must make sure the mailer is actually called *after* commit,
  297. # otherwise it may work on stale data. To do this, figure out if we are
  298. # within a transaction.
  299. # It seems like devise sends keyword arguments as a hash in the last
  300. # positional argument
  301. kwargs = args.pop if args.last.is_a?(Hash) && kwargs.empty?
  302. if ActiveRecord::Base.connection.current_transaction.try(:records)&.include?(self)
  303. pending_devise_notifications << [notification, args, kwargs]
  304. else
  305. render_and_send_devise_message(notification, *args, **kwargs)
  306. end
  307. end
  308. private
  309. def send_pending_devise_notifications
  310. pending_devise_notifications.each do |notification, args, kwargs|
  311. render_and_send_devise_message(notification, *args, **kwargs)
  312. end
  313. # Empty the pending notifications array because the
  314. # after_commit hook can be called multiple times which
  315. # could cause multiple emails to be sent.
  316. pending_devise_notifications.clear
  317. end
  318. def pending_devise_notifications
  319. @pending_devise_notifications ||= []
  320. end
  321. def render_and_send_devise_message(notification, *args, **kwargs)
  322. devise_mailer.send(notification, self, *args, **kwargs).deliver_later
  323. end
  324. def set_approved
  325. self.approved = begin
  326. if sign_up_from_ip_requires_approval?
  327. false
  328. else
  329. open_registrations? || valid_invitation? || external?
  330. end
  331. end
  332. end
  333. def sign_up_from_ip_requires_approval?
  334. !sign_up_ip.nil? && IpBlock.where(severity: :sign_up_requires_approval).where('ip >>= ?', sign_up_ip.to_s).exists?
  335. end
  336. def open_registrations?
  337. Setting.registrations_mode == 'open'
  338. end
  339. def external?
  340. !!@external
  341. end
  342. def bypass_invite_request_check?
  343. @bypass_invite_request_check
  344. end
  345. def sanitize_languages
  346. return if chosen_languages.nil?
  347. chosen_languages.reject!(&:blank?)
  348. self.chosen_languages = nil if chosen_languages.empty?
  349. end
  350. def prepare_new_user!
  351. BootstrapTimelineWorker.perform_async(account_id)
  352. ActivityTracker.increment('activity:accounts:local')
  353. ActivityTracker.record('activity:logins', id)
  354. UserMailer.welcome(self).deliver_later
  355. end
  356. def prepare_returning_user!
  357. return unless confirmed?
  358. ActivityTracker.record('activity:logins', id)
  359. regenerate_feed! if needs_feed_update?
  360. end
  361. def notify_staff_about_pending_account!
  362. User.staff.includes(:account).find_each do |u|
  363. next unless u.allows_pending_account_emails?
  364. AdminMailer.new_pending_account(u.account, self).deliver_later
  365. end
  366. end
  367. def regenerate_feed!
  368. RegenerationWorker.perform_async(account_id) if redis.set("account:#{account_id}:regeneration", true, nx: true, ex: 1.day.seconds)
  369. end
  370. def needs_feed_update?
  371. last_sign_in_at < ACTIVE_DURATION.ago
  372. end
  373. def validate_email_dns?
  374. email_changed? && !external? && !(Rails.env.test? || Rails.env.development?)
  375. end
  376. def invite_text_required?
  377. Setting.require_invite_text && !invited? && !external? && !bypass_invite_request_check?
  378. end
  379. end