user.rb 15 KB

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