1
0

user.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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. otp_secret_length: 32
  71. include LegacyOtpSecret # Must be after the above `devise` line in order to override the legacy method
  72. devise :two_factor_backupable,
  73. otp_number_of_backup_codes: 10
  74. devise :registerable, :recoverable, :validatable,
  75. :confirmable
  76. belongs_to :account, inverse_of: :user
  77. belongs_to :invite, counter_cache: :uses, optional: true
  78. belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
  79. belongs_to :role, class_name: 'UserRole', optional: true
  80. accepts_nested_attributes_for :account
  81. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner, dependent: nil
  82. has_many :backups, inverse_of: :user, dependent: nil
  83. has_many :invites, inverse_of: :user, dependent: nil
  84. has_many :markers, inverse_of: :user, dependent: :destroy
  85. has_many :webauthn_credentials, dependent: :destroy
  86. has_many :ips, class_name: 'UserIp', inverse_of: :user, dependent: nil
  87. has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  88. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? && !Setting.require_invite_text }
  89. validates :invite_request, presence: true, on: :create, if: :invite_text_required?
  90. validates :email, presence: true, email_address: true
  91. validates_with UserEmailValidator, if: -> { ENV['EMAIL_DOMAIN_LISTS_APPLY_AFTER_CONFIRMATION'] == 'true' || !confirmed? }
  92. validates_with EmailMxValidator, if: :validate_email_dns?
  93. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  94. # Honeypot/anti-spam fields
  95. attr_accessor :registration_form_time, :website, :confirm_password
  96. validates_with RegistrationFormTimeValidator, on: :create
  97. validates :website, absence: true, on: :create
  98. validates :confirm_password, absence: true, on: :create
  99. validate :validate_role_elevation
  100. scope :account_not_suspended, -> { joins(:account).merge(Account.without_suspended) }
  101. scope :recent, -> { order(id: :desc) }
  102. scope :pending, -> { where(approved: false) }
  103. scope :approved, -> { where(approved: true) }
  104. scope :confirmed, -> { where.not(confirmed_at: nil) }
  105. scope :unconfirmed, -> { where(confirmed_at: nil) }
  106. scope :enabled, -> { where(disabled: false) }
  107. scope :disabled, -> { where(disabled: true) }
  108. scope :active, -> { confirmed.signed_in_recently.account_not_suspended }
  109. scope :signed_in_recently, -> { where(current_sign_in_at: ACTIVE_DURATION.ago..) }
  110. scope :not_signed_in_recently, -> { where(current_sign_in_at: ...ACTIVE_DURATION.ago) }
  111. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  112. scope :matches_ip, ->(value) { left_joins(:ips).merge(IpBlock.contained_by(value)).group(users: [:id]) }
  113. before_validation :sanitize_role
  114. before_create :set_approved
  115. after_commit :send_pending_devise_notifications
  116. after_create_commit :trigger_webhooks
  117. normalizes :locale, with: ->(locale) { I18n.available_locales.exclude?(locale.to_sym) ? nil : locale }
  118. normalizes :time_zone, with: ->(time_zone) { ActiveSupport::TimeZone[time_zone].nil? ? nil : time_zone }
  119. normalizes :chosen_languages, with: ->(chosen_languages) { chosen_languages.compact_blank.presence }
  120. has_many :session_activations, dependent: :destroy
  121. delegate :can?, to: :role
  122. attr_reader :invite_code
  123. attr_writer :external, :bypass_invite_request_check, :current_account
  124. def self.those_who_can(*any_of_privileges)
  125. matching_role_ids = UserRole.that_can(*any_of_privileges).map(&:id)
  126. if matching_role_ids.empty?
  127. none
  128. else
  129. where(role_id: matching_role_ids)
  130. end
  131. end
  132. def self.skip_mx_check?
  133. Rails.env.local?
  134. end
  135. def role
  136. if role_id.nil?
  137. UserRole.everyone
  138. else
  139. super
  140. end
  141. end
  142. def confirmed?
  143. confirmed_at.present?
  144. end
  145. def invited?
  146. invite_id.present?
  147. end
  148. def valid_invitation?
  149. invite_id.present? && invite.valid_for_use?
  150. end
  151. def disable!
  152. update!(disabled: true)
  153. end
  154. def enable!
  155. update!(disabled: false)
  156. end
  157. def to_log_human_identifier
  158. account.acct
  159. end
  160. def to_log_route_param
  161. account_id
  162. end
  163. def confirm
  164. wrap_email_confirmation do
  165. super
  166. end
  167. end
  168. # Mark current email as confirmed, bypassing Devise
  169. def mark_email_as_confirmed!
  170. wrap_email_confirmation do
  171. skip_confirmation!
  172. save!
  173. end
  174. end
  175. def update_sign_in!(new_sign_in: false)
  176. old_current = current_sign_in_at
  177. new_current = Time.now.utc
  178. self.last_sign_in_at = old_current || new_current
  179. self.current_sign_in_at = new_current
  180. if new_sign_in
  181. self.sign_in_count ||= 0
  182. self.sign_in_count += 1
  183. end
  184. save(validate: false) unless new_record?
  185. prepare_returning_user!
  186. end
  187. def pending?
  188. !approved?
  189. end
  190. def active_for_authentication?
  191. !account.memorial?
  192. end
  193. def functional?
  194. functional_or_moved? && account.moved_to_account_id.nil?
  195. end
  196. def functional_or_moved?
  197. confirmed? && approved? && !disabled? && !account.unavailable? && !account.memorial?
  198. end
  199. def unconfirmed?
  200. !confirmed?
  201. end
  202. def unconfirmed_or_pending?
  203. unconfirmed? || pending?
  204. end
  205. def approve!
  206. return if approved?
  207. update!(approved: true)
  208. # Avoid extremely unlikely race condition when approving and confirming
  209. # the user at the same time
  210. reload unless confirmed?
  211. prepare_new_user! if confirmed?
  212. end
  213. def otp_enabled?
  214. otp_required_for_login
  215. end
  216. def webauthn_enabled?
  217. webauthn_credentials.any?
  218. end
  219. def two_factor_enabled?
  220. otp_required_for_login? || webauthn_credentials.any?
  221. end
  222. def disable_two_factor!
  223. self.otp_required_for_login = false
  224. self.otp_secret = nil
  225. otp_backup_codes&.clear
  226. webauthn_credentials.destroy_all if webauthn_enabled?
  227. save!
  228. end
  229. def applications_last_used
  230. Doorkeeper::AccessToken
  231. .where(resource_owner_id: id)
  232. .where.not(last_used_at: nil)
  233. .group(:application_id)
  234. .maximum(:last_used_at)
  235. .to_h
  236. end
  237. def token_for_app(app)
  238. return nil if app.nil? || app.owner != self
  239. Doorkeeper::AccessToken.find_or_create_by(application_id: app.id, resource_owner_id: id) do |t|
  240. t.scopes = app.scopes
  241. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  242. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  243. end
  244. end
  245. def activate_session(request)
  246. session_activations.activate(
  247. session_id: SecureRandom.hex,
  248. user_agent: request.user_agent,
  249. ip: request.remote_ip
  250. ).session_id
  251. end
  252. def clear_other_sessions(id)
  253. session_activations.exclusive(id)
  254. end
  255. def web_push_subscription(session)
  256. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  257. end
  258. def invite_code=(code)
  259. self.invite = Invite.find_by(code: code) if code.present?
  260. @invite_code = code
  261. end
  262. def password_required?
  263. return false if external?
  264. super
  265. end
  266. def external_or_valid_password?(compare_password)
  267. # If encrypted_password is blank, we got the user from LDAP or PAM,
  268. # so credentials are already valid
  269. encrypted_password.blank? || valid_password?(compare_password)
  270. end
  271. def send_reset_password_instructions
  272. return false if encrypted_password.blank?
  273. super
  274. end
  275. def reset_password(new_password, new_password_confirmation)
  276. return false if encrypted_password.blank?
  277. super
  278. end
  279. def revoke_access!
  280. Doorkeeper::AccessGrant.by_resource_owner(self).update_all(revoked_at: Time.now.utc)
  281. Doorkeeper::AccessToken.by_resource_owner(self).in_batches do |batch|
  282. batch.touch_all(:revoked_at)
  283. Web::PushSubscription.where(access_token_id: batch).delete_all
  284. # Revoke each access token for the Streaming API, since `update_all``
  285. # doesn't trigger ActiveRecord Callbacks:
  286. # TODO: #28793 Combine into a single topic
  287. payload = Oj.dump(event: :kill)
  288. redis.pipelined do |pipeline|
  289. batch.ids.each do |id|
  290. pipeline.publish("timeline:access_token:#{id}", payload)
  291. end
  292. end
  293. end
  294. end
  295. def reset_password!
  296. # First, change password to something random and deactivate all sessions
  297. transaction do
  298. update(password: SecureRandom.hex)
  299. session_activations.destroy_all
  300. end
  301. # Then, remove all authorized applications and connected push subscriptions
  302. revoke_access!
  303. # Finally, send a reset password prompt to the user
  304. send_reset_password_instructions
  305. end
  306. protected
  307. def send_devise_notification(notification, *args, **kwargs)
  308. # This method can be called in `after_update` and `after_commit` hooks,
  309. # but we must make sure the mailer is actually called *after* commit,
  310. # otherwise it may work on stale data. To do this, figure out if we are
  311. # within a transaction.
  312. # It seems like devise sends keyword arguments as a hash in the last
  313. # positional argument
  314. kwargs = args.pop if args.last.is_a?(Hash) && kwargs.empty?
  315. if ActiveRecord::Base.connection.current_transaction.try(:records)&.include?(self)
  316. pending_devise_notifications << [notification, args, kwargs]
  317. else
  318. render_and_send_devise_message(notification, *args, **kwargs)
  319. end
  320. end
  321. private
  322. def send_pending_devise_notifications
  323. pending_devise_notifications.each do |notification, args, kwargs|
  324. render_and_send_devise_message(notification, *args, **kwargs)
  325. end
  326. # Empty the pending notifications array because the
  327. # after_commit hook can be called multiple times which
  328. # could cause multiple emails to be sent.
  329. pending_devise_notifications.clear
  330. end
  331. def pending_devise_notifications
  332. @pending_devise_notifications ||= []
  333. end
  334. def render_and_send_devise_message(notification, *, **)
  335. devise_mailer.send(notification, self, *, **).deliver_later
  336. end
  337. def set_approved
  338. self.approved = begin
  339. if sign_up_from_ip_requires_approval? || sign_up_email_requires_approval?
  340. false
  341. else
  342. open_registrations? || valid_invitation? || external?
  343. end
  344. end
  345. end
  346. def grant_approval_on_confirmation?
  347. # Re-check approval on confirmation if the server has switched to open registrations
  348. open_registrations? && !sign_up_from_ip_requires_approval? && !sign_up_email_requires_approval?
  349. end
  350. def wrap_email_confirmation
  351. new_user = !confirmed?
  352. self.approved = true if grant_approval_on_confirmation?
  353. yield
  354. if new_user
  355. # Avoid extremely unlikely race condition when approving and confirming
  356. # the user at the same time
  357. reload unless approved?
  358. if approved?
  359. prepare_new_user!
  360. else
  361. notify_staff_about_pending_account!
  362. end
  363. end
  364. end
  365. def sign_up_from_ip_requires_approval?
  366. sign_up_ip.present? && IpBlock.severity_sign_up_requires_approval.containing(sign_up_ip.to_s).exists?
  367. end
  368. def sign_up_email_requires_approval?
  369. return false if email.blank?
  370. _, domain = email.split('@', 2)
  371. return false if domain.blank?
  372. records = []
  373. # Doing this conditionally is not very satisfying, but this is consistent
  374. # with the MX records validations we do and keeps the specs tractable.
  375. records = DomainResource.new(domain).mx unless self.class.skip_mx_check?
  376. EmailDomainBlock.requires_approval?(records + [domain], attempt_ip: sign_up_ip)
  377. end
  378. def open_registrations?
  379. Setting.registrations_mode == 'open'
  380. end
  381. def external?
  382. !!@external
  383. end
  384. def bypass_invite_request_check?
  385. @bypass_invite_request_check
  386. end
  387. def sanitize_role
  388. self.role = nil if role.present? && role.everyone?
  389. end
  390. def prepare_new_user!
  391. BootstrapTimelineWorker.perform_async(account_id)
  392. ActivityTracker.increment('activity:accounts:local')
  393. ActivityTracker.record('activity:logins', id)
  394. UserMailer.welcome(self).deliver_later(wait: 1.hour)
  395. TriggerWebhookWorker.perform_async('account.approved', 'Account', account_id)
  396. end
  397. def prepare_returning_user!
  398. return unless confirmed?
  399. ActivityTracker.record('activity:logins', id)
  400. regenerate_feed! if needs_feed_update?
  401. end
  402. def notify_staff_about_pending_account!
  403. User.those_who_can(:manage_users).includes(:account).find_each do |u|
  404. next unless u.allows_pending_account_emails?
  405. AdminMailer.with(recipient: u.account).new_pending_account(self).deliver_later
  406. end
  407. end
  408. def regenerate_feed!
  409. RegenerationWorker.perform_async(account_id) if redis.set("account:#{account_id}:regeneration", true, nx: true, ex: 1.day.seconds)
  410. end
  411. def needs_feed_update?
  412. last_sign_in_at < ACTIVE_DURATION.ago
  413. end
  414. def validate_email_dns?
  415. email_changed? && !external? && !self.class.skip_mx_check?
  416. end
  417. def validate_role_elevation
  418. errors.add(:role_id, :elevated) if defined?(@current_account) && role&.overrides?(@current_account&.user_role)
  419. end
  420. def invite_text_required?
  421. Setting.require_invite_text && !open_registrations? && !invited? && !external? && !bypass_invite_request_check?
  422. end
  423. def trigger_webhooks
  424. TriggerWebhookWorker.perform_async('account.created', 'Account', account_id)
  425. end
  426. end