user.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. # confirmation_token :string
  17. # confirmed_at :datetime
  18. # confirmation_sent_at :datetime
  19. # unconfirmed_email :string
  20. # locale :string
  21. # encrypted_otp_secret :string
  22. # encrypted_otp_secret_iv :string
  23. # encrypted_otp_secret_salt :string
  24. # consumed_timestep :integer
  25. # otp_required_for_login :boolean default(FALSE), not null
  26. # last_emailed_at :datetime
  27. # otp_backup_codes :string is an Array
  28. # account_id :bigint(8) not null
  29. # disabled :boolean default(FALSE), not null
  30. # invite_id :bigint(8)
  31. # chosen_languages :string is an Array
  32. # created_by_application_id :bigint(8)
  33. # approved :boolean default(TRUE), not null
  34. # sign_in_token :string
  35. # sign_in_token_sent_at :datetime
  36. # webauthn_id :string
  37. # sign_up_ip :inet
  38. # role_id :bigint(8)
  39. # settings :text
  40. # time_zone :string
  41. # otp_secret :string
  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. filtered_languages
  51. admin
  52. moderator
  53. )
  54. include LanguagesHelper
  55. include Redisable
  56. include User::HasSettings
  57. include User::LdapAuthenticable
  58. include User::Omniauthable
  59. include User::PamAuthenticable
  60. # The home and list feeds will be stored in Redis for this amount
  61. # of time, and status fan-out to followers will include only people
  62. # within this time frame. Lowering the duration may improve performance
  63. # if lots of people sign up, but not a lot of them check their feed
  64. # every day. Raising the duration reduces the amount of expensive
  65. # RegenerationWorker jobs that need to be run when those people come
  66. # to check their feed
  67. ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
  68. devise :two_factor_authenticatable,
  69. otp_secret_encryption_key: Rails.configuration.x.otp_secret
  70. include LegacyOtpSecret # Must be after the above `devise` line in order to override the legacy method
  71. devise :two_factor_backupable,
  72. otp_number_of_backup_codes: 10
  73. devise :registerable, :recoverable, :validatable,
  74. :confirmable
  75. belongs_to :account, inverse_of: :user
  76. belongs_to :invite, counter_cache: :uses, optional: true
  77. belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
  78. belongs_to :role, class_name: 'UserRole', optional: true
  79. accepts_nested_attributes_for :account
  80. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner, dependent: nil
  81. has_many :backups, inverse_of: :user, dependent: nil
  82. has_many :invites, inverse_of: :user, dependent: nil
  83. has_many :markers, inverse_of: :user, dependent: :destroy
  84. has_many :webauthn_credentials, dependent: :destroy
  85. has_many :ips, class_name: 'UserIp', inverse_of: :user, dependent: nil
  86. has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  87. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? && !Setting.require_invite_text }
  88. validates :invite_request, presence: true, on: :create, if: :invite_text_required?
  89. validates :email, presence: true, email_address: true
  90. validates_with BlacklistedEmailValidator, if: -> { ENV['EMAIL_DOMAIN_LISTS_APPLY_AFTER_CONFIRMATION'] == 'true' || !confirmed? }
  91. validates_with EmailMxValidator, if: :validate_email_dns?
  92. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  93. # Honeypot/anti-spam fields
  94. attr_accessor :registration_form_time, :website, :confirm_password
  95. validates_with RegistrationFormTimeValidator, on: :create
  96. validates :website, absence: true, on: :create
  97. validates :confirm_password, absence: true, on: :create
  98. validate :validate_role_elevation
  99. scope :account_not_suspended, -> { joins(:account).merge(Account.without_suspended) }
  100. scope :recent, -> { order(id: :desc) }
  101. scope :pending, -> { where(approved: false) }
  102. scope :approved, -> { where(approved: true) }
  103. scope :confirmed, -> { where.not(confirmed_at: nil) }
  104. scope :enabled, -> { where(disabled: false) }
  105. scope :disabled, -> { where(disabled: true) }
  106. scope :active, -> { confirmed.signed_in_recently.account_not_suspended }
  107. scope :signed_in_recently, -> { where(current_sign_in_at: ACTIVE_DURATION.ago..) }
  108. scope :not_signed_in_recently, -> { where(current_sign_in_at: ...ACTIVE_DURATION.ago) }
  109. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  110. scope :matches_ip, ->(value) { left_joins(:ips).where('user_ips.ip <<= ?', value).group('users.id') }
  111. before_validation :sanitize_role
  112. before_create :set_approved
  113. after_commit :send_pending_devise_notifications
  114. after_create_commit :trigger_webhooks
  115. normalizes :locale, with: ->(locale) { I18n.available_locales.exclude?(locale.to_sym) ? nil : locale }
  116. normalizes :time_zone, with: ->(time_zone) { ActiveSupport::TimeZone[time_zone].nil? ? nil : time_zone }
  117. normalizes :chosen_languages, with: ->(chosen_languages) { chosen_languages.compact_blank.presence }
  118. has_many :session_activations, dependent: :destroy
  119. delegate :can?, to: :role
  120. attr_reader :invite_code
  121. attr_writer :external, :bypass_invite_request_check, :current_account
  122. def self.those_who_can(*any_of_privileges)
  123. matching_role_ids = UserRole.that_can(*any_of_privileges).map(&:id)
  124. if matching_role_ids.empty?
  125. none
  126. else
  127. where(role_id: matching_role_ids)
  128. end
  129. end
  130. def self.skip_mx_check?
  131. Rails.env.local?
  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. wrap_email_confirmation do
  163. super
  164. end
  165. end
  166. # Mark current email as confirmed, bypassing Devise
  167. def mark_email_as_confirmed!
  168. wrap_email_confirmation do
  169. skip_confirmation!
  170. save!
  171. end
  172. end
  173. def update_sign_in!(new_sign_in: false)
  174. old_current = current_sign_in_at
  175. new_current = Time.now.utc
  176. self.last_sign_in_at = old_current || new_current
  177. self.current_sign_in_at = new_current
  178. if new_sign_in
  179. self.sign_in_count ||= 0
  180. self.sign_in_count += 1
  181. end
  182. save(validate: false) unless new_record?
  183. prepare_returning_user!
  184. end
  185. def pending?
  186. !approved?
  187. end
  188. def active_for_authentication?
  189. !account.memorial?
  190. end
  191. def functional?
  192. functional_or_moved? && account.moved_to_account_id.nil?
  193. end
  194. def functional_or_moved?
  195. confirmed? && approved? && !disabled? && !account.unavailable? && !account.memorial?
  196. end
  197. def unconfirmed?
  198. !confirmed?
  199. end
  200. def unconfirmed_or_pending?
  201. unconfirmed? || pending?
  202. end
  203. def inactive_message
  204. approved? ? super : :pending
  205. end
  206. def approve!
  207. return if approved?
  208. update!(approved: true)
  209. # Avoid extremely unlikely race condition when approving and confirming
  210. # the user at the same time
  211. reload unless confirmed?
  212. prepare_new_user! if confirmed?
  213. end
  214. def otp_enabled?
  215. otp_required_for_login
  216. end
  217. def webauthn_enabled?
  218. webauthn_credentials.any?
  219. end
  220. def two_factor_enabled?
  221. otp_required_for_login? || webauthn_credentials.any?
  222. end
  223. def disable_two_factor!
  224. self.otp_required_for_login = false
  225. self.otp_secret = nil
  226. otp_backup_codes&.clear
  227. webauthn_credentials.destroy_all if webauthn_enabled?
  228. save!
  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 revoke_access!
  273. Doorkeeper::AccessGrant.by_resource_owner(self).update_all(revoked_at: Time.now.utc)
  274. Doorkeeper::AccessToken.by_resource_owner(self).in_batches do |batch|
  275. batch.update_all(revoked_at: Time.now.utc)
  276. Web::PushSubscription.where(access_token_id: batch).delete_all
  277. # Revoke each access token for the Streaming API, since `update_all``
  278. # doesn't trigger ActiveRecord Callbacks:
  279. # TODO: #28793 Combine into a single topic
  280. payload = Oj.dump(event: :kill)
  281. redis.pipelined do |pipeline|
  282. batch.ids.each do |id|
  283. pipeline.publish("timeline:access_token:#{id}", payload)
  284. end
  285. end
  286. end
  287. end
  288. def reset_password!
  289. # First, change password to something random and deactivate all sessions
  290. transaction do
  291. update(password: SecureRandom.hex)
  292. session_activations.destroy_all
  293. end
  294. # Then, remove all authorized applications and connected push subscriptions
  295. revoke_access!
  296. # Finally, send a reset password prompt to the user
  297. send_reset_password_instructions
  298. end
  299. protected
  300. def send_devise_notification(notification, *args, **kwargs)
  301. # This method can be called in `after_update` and `after_commit` hooks,
  302. # but we must make sure the mailer is actually called *after* commit,
  303. # otherwise it may work on stale data. To do this, figure out if we are
  304. # within a transaction.
  305. # It seems like devise sends keyword arguments as a hash in the last
  306. # positional argument
  307. kwargs = args.pop if args.last.is_a?(Hash) && kwargs.empty?
  308. if ActiveRecord::Base.connection.current_transaction.try(:records)&.include?(self)
  309. pending_devise_notifications << [notification, args, kwargs]
  310. else
  311. render_and_send_devise_message(notification, *args, **kwargs)
  312. end
  313. end
  314. private
  315. def send_pending_devise_notifications
  316. pending_devise_notifications.each do |notification, args, kwargs|
  317. render_and_send_devise_message(notification, *args, **kwargs)
  318. end
  319. # Empty the pending notifications array because the
  320. # after_commit hook can be called multiple times which
  321. # could cause multiple emails to be sent.
  322. pending_devise_notifications.clear
  323. end
  324. def pending_devise_notifications
  325. @pending_devise_notifications ||= []
  326. end
  327. def render_and_send_devise_message(notification, *args, **kwargs)
  328. devise_mailer.send(notification, self, *args, **kwargs).deliver_later
  329. end
  330. def set_approved
  331. self.approved = begin
  332. if sign_up_from_ip_requires_approval? || sign_up_email_requires_approval?
  333. false
  334. else
  335. open_registrations? || valid_invitation? || external?
  336. end
  337. end
  338. end
  339. def grant_approval_on_confirmation?
  340. # Re-check approval on confirmation if the server has switched to open registrations
  341. open_registrations? && !sign_up_from_ip_requires_approval? && !sign_up_email_requires_approval?
  342. end
  343. def wrap_email_confirmation
  344. new_user = !confirmed?
  345. self.approved = true if grant_approval_on_confirmation?
  346. yield
  347. if new_user
  348. # Avoid extremely unlikely race condition when approving and confirming
  349. # the user at the same time
  350. reload unless approved?
  351. if approved?
  352. prepare_new_user!
  353. else
  354. notify_staff_about_pending_account!
  355. end
  356. end
  357. end
  358. def sign_up_from_ip_requires_approval?
  359. sign_up_ip.present? && IpBlock.severity_sign_up_requires_approval.exists?(['ip >>= ?', sign_up_ip.to_s])
  360. end
  361. def sign_up_email_requires_approval?
  362. return false if email.blank?
  363. _, domain = email.split('@', 2)
  364. return false if domain.blank?
  365. records = []
  366. # Doing this conditionally is not very satisfying, but this is consistent
  367. # with the MX records validations we do and keeps the specs tractable.
  368. unless self.class.skip_mx_check?
  369. Resolv::DNS.open do |dns|
  370. dns.timeouts = 5
  371. records = dns.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }.compact_blank
  372. end
  373. end
  374. EmailDomainBlock.requires_approval?(records + [domain], attempt_ip: sign_up_ip)
  375. end
  376. def open_registrations?
  377. Setting.registrations_mode == 'open'
  378. end
  379. def external?
  380. !!@external
  381. end
  382. def bypass_invite_request_check?
  383. @bypass_invite_request_check
  384. end
  385. def sanitize_role
  386. self.role = nil if role.present? && role.everyone?
  387. end
  388. def prepare_new_user!
  389. BootstrapTimelineWorker.perform_async(account_id)
  390. ActivityTracker.increment('activity:accounts:local')
  391. ActivityTracker.record('activity:logins', id)
  392. UserMailer.welcome(self).deliver_later(wait: 1.hour)
  393. TriggerWebhookWorker.perform_async('account.approved', 'Account', account_id)
  394. end
  395. def prepare_returning_user!
  396. return unless confirmed?
  397. ActivityTracker.record('activity:logins', id)
  398. regenerate_feed! if needs_feed_update?
  399. end
  400. def notify_staff_about_pending_account!
  401. User.those_who_can(:manage_users).includes(:account).find_each do |u|
  402. next unless u.allows_pending_account_emails?
  403. AdminMailer.with(recipient: u.account).new_pending_account(self).deliver_later
  404. end
  405. end
  406. def regenerate_feed!
  407. RegenerationWorker.perform_async(account_id) if redis.set("account:#{account_id}:regeneration", true, nx: true, ex: 1.day.seconds)
  408. end
  409. def needs_feed_update?
  410. last_sign_in_at < ACTIVE_DURATION.ago
  411. end
  412. def validate_email_dns?
  413. email_changed? && !external? && !self.class.skip_mx_check?
  414. end
  415. def validate_role_elevation
  416. errors.add(:role_id, :elevated) if defined?(@current_account) && role&.overrides?(@current_account&.user_role)
  417. end
  418. def invite_text_required?
  419. Setting.require_invite_text && !open_registrations? && !invited? && !external? && !bypass_invite_request_check?
  420. end
  421. def trigger_webhooks
  422. TriggerWebhookWorker.perform_async('account.created', 'Account', account_id)
  423. end
  424. end