user.rb 15 KB

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