user.rb 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. # settings :text
  42. # time_zone :string
  43. #
  44. class User < ApplicationRecord
  45. self.ignored_columns += %w(
  46. remember_created_at
  47. remember_token
  48. current_sign_in_ip
  49. last_sign_in_ip
  50. skip_sign_in_token
  51. filtered_languages
  52. admin
  53. moderator
  54. )
  55. include LanguagesHelper
  56. include Redisable
  57. include User::HasSettings
  58. include User::LdapAuthenticable
  59. include User::Omniauthable
  60. include User::PamAuthenticable
  61. # The home and list feeds will be stored in Redis for this amount
  62. # of time, and status fan-out to followers will include only people
  63. # within this time frame. Lowering the duration may improve performance
  64. # if lots of people sign up, but not a lot of them check their feed
  65. # every day. Raising the duration reduces the amount of expensive
  66. # RegenerationWorker jobs that need to be run when those people come
  67. # to check their feed
  68. ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
  69. devise :two_factor_authenticatable,
  70. otp_secret_encryption_key: Rails.configuration.x.otp_secret
  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_with BlacklistedEmailValidator, if: -> { ENV['EMAIL_DOMAIN_LISTS_APPLY_AFTER_CONFIRMATION'] == 'true' || !confirmed? }
  90. validates_with EmailMxValidator, if: :validate_email_dns?
  91. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  92. # Honeypot/anti-spam fields
  93. attr_accessor :registration_form_time, :website, :confirm_password
  94. validates_with RegistrationFormTimeValidator, on: :create
  95. validates :website, absence: true, on: :create
  96. validates :confirm_password, absence: true, on: :create
  97. validate :validate_role_elevation
  98. scope :recent, -> { order(id: :desc) }
  99. scope :pending, -> { where(approved: false) }
  100. scope :approved, -> { where(approved: true) }
  101. scope :confirmed, -> { where.not(confirmed_at: nil) }
  102. scope :enabled, -> { where(disabled: false) }
  103. scope :disabled, -> { where(disabled: true) }
  104. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  105. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
  106. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  107. scope :matches_ip, ->(value) { left_joins(:ips).where('user_ips.ip <<= ?', value).group('users.id') }
  108. before_validation :sanitize_role
  109. before_create :set_approved
  110. after_commit :send_pending_devise_notifications
  111. after_create_commit :trigger_webhooks
  112. normalizes :locale, with: ->(locale) { I18n.available_locales.exclude?(locale.to_sym) ? nil : locale }
  113. normalizes :time_zone, with: ->(time_zone) { ActiveSupport::TimeZone[time_zone].nil? ? nil : time_zone }
  114. normalizes :chosen_languages, with: ->(chosen_languages) { chosen_languages.compact_blank.presence }
  115. # This avoids a deprecation warning from Rails 5.1
  116. # It seems possible that a future release of devise-two-factor will
  117. # handle this itself, and this can be removed from our User class.
  118. attribute :otp_secret
  119. has_many :session_activations, dependent: :destroy
  120. delegate :can?, to: :role
  121. attr_reader :invite_code
  122. attr_writer :external, :bypass_invite_request_check, :current_account
  123. def self.those_who_can(*any_of_privileges)
  124. matching_role_ids = UserRole.that_can(*any_of_privileges).map(&:id)
  125. if matching_role_ids.empty?
  126. none
  127. else
  128. where(role_id: matching_role_ids)
  129. end
  130. end
  131. def self.skip_mx_check?
  132. Rails.env.local?
  133. end
  134. def role
  135. if role_id.nil?
  136. UserRole.everyone
  137. else
  138. super
  139. end
  140. end
  141. def confirmed?
  142. confirmed_at.present?
  143. end
  144. def invited?
  145. invite_id.present?
  146. end
  147. def valid_invitation?
  148. invite_id.present? && invite.valid_for_use?
  149. end
  150. def disable!
  151. update!(disabled: true)
  152. end
  153. def enable!
  154. update!(disabled: false)
  155. end
  156. def to_log_human_identifier
  157. account.acct
  158. end
  159. def to_log_route_param
  160. account_id
  161. end
  162. def confirm
  163. wrap_email_confirmation do
  164. super
  165. end
  166. end
  167. # Mark current email as confirmed, bypassing Devise
  168. def mark_email_as_confirmed!
  169. wrap_email_confirmation do
  170. skip_confirmation!
  171. save!
  172. end
  173. end
  174. def update_sign_in!(new_sign_in: false)
  175. old_current = current_sign_in_at
  176. new_current = Time.now.utc
  177. self.last_sign_in_at = old_current || new_current
  178. self.current_sign_in_at = new_current
  179. if new_sign_in
  180. self.sign_in_count ||= 0
  181. self.sign_in_count += 1
  182. end
  183. save(validate: false) unless new_record?
  184. prepare_returning_user!
  185. end
  186. def pending?
  187. !approved?
  188. end
  189. def active_for_authentication?
  190. !account.memorial?
  191. end
  192. def functional?
  193. functional_or_moved? && account.moved_to_account_id.nil?
  194. end
  195. def functional_or_moved?
  196. confirmed? && approved? && !disabled? && !account.unavailable? && !account.memorial?
  197. end
  198. def unconfirmed?
  199. !confirmed?
  200. end
  201. def unconfirmed_or_pending?
  202. unconfirmed? || pending?
  203. end
  204. def inactive_message
  205. approved? ? super : :pending
  206. end
  207. def approve!
  208. return if approved?
  209. update!(approved: true)
  210. # Avoid extremely unlikely race condition when approving and confirming
  211. # the user at the same time
  212. reload unless confirmed?
  213. prepare_new_user! if confirmed?
  214. end
  215. def otp_enabled?
  216. otp_required_for_login
  217. end
  218. def webauthn_enabled?
  219. webauthn_credentials.any?
  220. end
  221. def two_factor_enabled?
  222. otp_required_for_login? || webauthn_credentials.any?
  223. end
  224. def disable_two_factor!
  225. self.otp_required_for_login = false
  226. self.otp_secret = nil
  227. otp_backup_codes&.clear
  228. webauthn_credentials.destroy_all if webauthn_enabled?
  229. save!
  230. end
  231. def token_for_app(app)
  232. return nil if app.nil? || app.owner != self
  233. Doorkeeper::AccessToken.find_or_create_by(application_id: app.id, resource_owner_id: id) do |t|
  234. t.scopes = app.scopes
  235. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  236. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  237. end
  238. end
  239. def activate_session(request)
  240. session_activations.activate(
  241. session_id: SecureRandom.hex,
  242. user_agent: request.user_agent,
  243. ip: request.remote_ip
  244. ).session_id
  245. end
  246. def clear_other_sessions(id)
  247. session_activations.exclusive(id)
  248. end
  249. def web_push_subscription(session)
  250. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  251. end
  252. def invite_code=(code)
  253. self.invite = Invite.find_by(code: code) if code.present?
  254. @invite_code = code
  255. end
  256. def password_required?
  257. return false if external?
  258. super
  259. end
  260. def external_or_valid_password?(compare_password)
  261. # If encrypted_password is blank, we got the user from LDAP or PAM,
  262. # so credentials are already valid
  263. encrypted_password.blank? || valid_password?(compare_password)
  264. end
  265. def send_reset_password_instructions
  266. return false if encrypted_password.blank?
  267. super
  268. end
  269. def reset_password(new_password, new_password_confirmation)
  270. return false if encrypted_password.blank?
  271. super
  272. end
  273. def revoke_access!
  274. Doorkeeper::AccessGrant.by_resource_owner(self).update_all(revoked_at: Time.now.utc)
  275. Doorkeeper::AccessToken.by_resource_owner(self).in_batches do |batch|
  276. batch.update_all(revoked_at: Time.now.utc)
  277. Web::PushSubscription.where(access_token_id: batch).delete_all
  278. end
  279. end
  280. def reset_password!
  281. # First, change password to something random and deactivate all sessions
  282. transaction do
  283. update(password: SecureRandom.hex)
  284. session_activations.destroy_all
  285. end
  286. # Then, remove all authorized applications and connected push subscriptions
  287. revoke_access!
  288. # Finally, send a reset password prompt to the user
  289. send_reset_password_instructions
  290. end
  291. protected
  292. def send_devise_notification(notification, *args, **kwargs)
  293. # This method can be called in `after_update` and `after_commit` hooks,
  294. # but we must make sure the mailer is actually called *after* commit,
  295. # otherwise it may work on stale data. To do this, figure out if we are
  296. # within a transaction.
  297. # It seems like devise sends keyword arguments as a hash in the last
  298. # positional argument
  299. kwargs = args.pop if args.last.is_a?(Hash) && kwargs.empty?
  300. if ActiveRecord::Base.connection.current_transaction.try(:records)&.include?(self)
  301. pending_devise_notifications << [notification, args, kwargs]
  302. else
  303. render_and_send_devise_message(notification, *args, **kwargs)
  304. end
  305. end
  306. private
  307. def send_pending_devise_notifications
  308. pending_devise_notifications.each do |notification, args, kwargs|
  309. render_and_send_devise_message(notification, *args, **kwargs)
  310. end
  311. # Empty the pending notifications array because the
  312. # after_commit hook can be called multiple times which
  313. # could cause multiple emails to be sent.
  314. pending_devise_notifications.clear
  315. end
  316. def pending_devise_notifications
  317. @pending_devise_notifications ||= []
  318. end
  319. def render_and_send_devise_message(notification, *args, **kwargs)
  320. devise_mailer.send(notification, self, *args, **kwargs).deliver_later
  321. end
  322. def set_approved
  323. self.approved = begin
  324. if sign_up_from_ip_requires_approval? || sign_up_email_requires_approval?
  325. false
  326. else
  327. open_registrations? || valid_invitation? || external?
  328. end
  329. end
  330. end
  331. def grant_approval_on_confirmation?
  332. # Re-check approval on confirmation if the server has switched to open registrations
  333. open_registrations? && !sign_up_from_ip_requires_approval? && !sign_up_email_requires_approval?
  334. end
  335. def wrap_email_confirmation
  336. new_user = !confirmed?
  337. self.approved = true if grant_approval_on_confirmation?
  338. yield
  339. if new_user
  340. # Avoid extremely unlikely race condition when approving and confirming
  341. # the user at the same time
  342. reload unless approved?
  343. if approved?
  344. prepare_new_user!
  345. else
  346. notify_staff_about_pending_account!
  347. end
  348. end
  349. end
  350. def sign_up_from_ip_requires_approval?
  351. sign_up_ip.present? && IpBlock.sign_up_requires_approval.exists?(['ip >>= ?', sign_up_ip.to_s])
  352. end
  353. def sign_up_email_requires_approval?
  354. return false if email.blank?
  355. _, domain = email.split('@', 2)
  356. return false if domain.blank?
  357. records = []
  358. # Doing this conditionally is not very satisfying, but this is consistent
  359. # with the MX records validations we do and keeps the specs tractable.
  360. unless self.class.skip_mx_check?
  361. Resolv::DNS.open do |dns|
  362. dns.timeouts = 5
  363. records = dns.getresources(domain, Resolv::DNS::Resource::IN::MX).to_a.map { |e| e.exchange.to_s }.compact_blank
  364. end
  365. end
  366. EmailDomainBlock.requires_approval?(records + [domain], attempt_ip: sign_up_ip)
  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_role
  378. self.role = nil if role.present? && role.everyone?
  379. end
  380. def prepare_new_user!
  381. BootstrapTimelineWorker.perform_async(account_id)
  382. ActivityTracker.increment('activity:accounts:local')
  383. ActivityTracker.record('activity:logins', id)
  384. UserMailer.welcome(self).deliver_later
  385. TriggerWebhookWorker.perform_async('account.approved', 'Account', account_id)
  386. end
  387. def prepare_returning_user!
  388. return unless confirmed?
  389. ActivityTracker.record('activity:logins', id)
  390. regenerate_feed! if needs_feed_update?
  391. end
  392. def notify_staff_about_pending_account!
  393. User.those_who_can(:manage_users).includes(:account).find_each do |u|
  394. next unless u.allows_pending_account_emails?
  395. AdminMailer.with(recipient: u.account).new_pending_account(self).deliver_later
  396. end
  397. end
  398. def regenerate_feed!
  399. RegenerationWorker.perform_async(account_id) if redis.set("account:#{account_id}:regeneration", true, nx: true, ex: 1.day.seconds)
  400. end
  401. def needs_feed_update?
  402. last_sign_in_at < ACTIVE_DURATION.ago
  403. end
  404. def validate_email_dns?
  405. email_changed? && !external? && !self.class.skip_mx_check?
  406. end
  407. def validate_role_elevation
  408. errors.add(:role_id, :elevated) if defined?(@current_account) && role&.overrides?(@current_account&.user_role)
  409. end
  410. def invite_text_required?
  411. Setting.require_invite_text && !open_registrations? && !invited? && !external? && !bypass_invite_request_check?
  412. end
  413. def trigger_webhooks
  414. TriggerWebhookWorker.perform_async('account.created', 'Account', account_id)
  415. end
  416. end