where i deviate from standard mastodon assets
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.rb 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. #
  42. class User < ApplicationRecord
  43. include Settings::Extend
  44. include UserRoles
  45. # The home and list feeds will be stored in Redis for this amount
  46. # of time, and status fan-out to followers will include only people
  47. # within this time frame. Lowering the duration may improve performance
  48. # if lots of people sign up, but not a lot of them check their feed
  49. # every day. Raising the duration reduces the amount of expensive
  50. # RegenerationWorker jobs that need to be run when those people come
  51. # to check their feed
  52. ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
  53. devise :two_factor_authenticatable,
  54. otp_secret_encryption_key: Rails.configuration.x.otp_secret
  55. devise :two_factor_backupable,
  56. otp_number_of_backup_codes: 10
  57. devise :registerable, :recoverable, :rememberable, :trackable, :validatable,
  58. :confirmable
  59. include Omniauthable
  60. include PamAuthenticable
  61. include LdapAuthenticable
  62. belongs_to :account, inverse_of: :user
  63. belongs_to :invite, counter_cache: :uses, optional: true
  64. belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
  65. accepts_nested_attributes_for :account
  66. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  67. has_many :backups, inverse_of: :user
  68. has_many :invites, inverse_of: :user
  69. has_many :markers, inverse_of: :user, dependent: :destroy
  70. has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  71. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? }
  72. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  73. validates_with BlacklistedEmailValidator, on: :create
  74. validates_with EmailMxValidator, if: :validate_email_dns?
  75. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  76. scope :recent, -> { order(id: :desc) }
  77. scope :pending, -> { where(approved: false) }
  78. scope :approved, -> { where(approved: true) }
  79. scope :confirmed, -> { where.not(confirmed_at: nil) }
  80. scope :enabled, -> { where(disabled: false) }
  81. scope :disabled, -> { where(disabled: true) }
  82. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  83. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
  84. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  85. scope :matches_ip, ->(value) { left_joins(:session_activations).where('users.current_sign_in_ip <<= ?', value).or(left_joins(:session_activations).where('users.last_sign_in_ip <<= ?', value)).or(left_joins(:session_activations).where('session_activations.ip <<= ?', value)) }
  86. scope :emailable, -> { confirmed.enabled.joins(:account).merge(Account.searchable) }
  87. before_validation :sanitize_languages
  88. before_create :set_approved
  89. # This avoids a deprecation warning from Rails 5.1
  90. # It seems possible that a future release of devise-two-factor will
  91. # handle this itself, and this can be removed from our User class.
  92. attribute :otp_secret
  93. has_many :session_activations, dependent: :destroy
  94. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :favourite_modal, :delete_modal,
  95. :reduce_motion, :system_font_ui, :noindex, :flavour, :skin, :display_media, :hide_network, :hide_followers_count,
  96. :expand_spoilers, :default_language, :aggregate_reblogs, :show_application,
  97. :advanced_layout, :use_blurhash, :use_pending_items, :trends, :crop_images,
  98. :default_content_type, :system_emoji_font,
  99. to: :settings, prefix: :setting, allow_nil: false
  100. attr_reader :invite_code
  101. attr_writer :external
  102. def confirmed?
  103. confirmed_at.present?
  104. end
  105. def invited?
  106. invite_id.present?
  107. end
  108. def valid_invitation?
  109. invite_id.present? && invite.valid_for_use?
  110. end
  111. def disable!
  112. update!(disabled: true,
  113. last_sign_in_at: current_sign_in_at,
  114. current_sign_in_at: nil)
  115. end
  116. def enable!
  117. update!(disabled: false)
  118. end
  119. def confirm
  120. new_user = !confirmed?
  121. self.approved = true if open_registrations?
  122. super
  123. if new_user && approved?
  124. prepare_new_user!
  125. elsif new_user
  126. notify_staff_about_pending_account!
  127. end
  128. end
  129. def confirm!
  130. new_user = !confirmed?
  131. self.approved = true if open_registrations?
  132. skip_confirmation!
  133. save!
  134. prepare_new_user! if new_user && approved?
  135. end
  136. def pending?
  137. !approved?
  138. end
  139. def active_for_authentication?
  140. true
  141. end
  142. def functional?
  143. confirmed? && approved? && !disabled? && !account.suspended?
  144. end
  145. def unconfirmed_or_pending?
  146. !(confirmed? && approved?)
  147. end
  148. def inactive_message
  149. !approved? ? :pending : super
  150. end
  151. def approve!
  152. return if approved?
  153. update!(approved: true)
  154. prepare_new_user!
  155. end
  156. def update_tracked_fields!(request)
  157. super
  158. prepare_returning_user!
  159. end
  160. def disable_two_factor!
  161. self.otp_required_for_login = false
  162. otp_backup_codes&.clear
  163. save!
  164. end
  165. def setting_default_privacy
  166. settings.default_privacy || (account.locked? ? 'private' : 'public')
  167. end
  168. def allows_digest_emails?
  169. settings.notification_emails['digest']
  170. end
  171. def allows_report_emails?
  172. settings.notification_emails['report']
  173. end
  174. def allows_pending_account_emails?
  175. settings.notification_emails['pending_account']
  176. end
  177. def allows_trending_tag_emails?
  178. settings.notification_emails['trending_tag']
  179. end
  180. def hides_network?
  181. @hides_network ||= settings.hide_network
  182. end
  183. def aggregates_reblogs?
  184. @aggregates_reblogs ||= settings.aggregate_reblogs
  185. end
  186. def shows_application?
  187. @shows_application ||= settings.show_application
  188. end
  189. def token_for_app(a)
  190. return nil if a.nil? || a.owner != self
  191. Doorkeeper::AccessToken
  192. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  193. t.scopes = a.scopes
  194. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  195. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  196. end
  197. end
  198. def activate_session(request)
  199. session_activations.activate(session_id: SecureRandom.hex,
  200. user_agent: request.user_agent,
  201. ip: request.remote_ip).session_id
  202. end
  203. def exclusive_session(id)
  204. session_activations.exclusive(id)
  205. end
  206. def session_active?(id)
  207. session_activations.active? id
  208. end
  209. def web_push_subscription(session)
  210. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  211. end
  212. def invite_code=(code)
  213. self.invite = Invite.find_by(code: code) if code.present?
  214. @invite_code = code
  215. end
  216. def password_required?
  217. return false if external?
  218. super
  219. end
  220. def send_reset_password_instructions
  221. return false if encrypted_password.blank?
  222. super
  223. end
  224. def reset_password!(new_password, new_password_confirmation)
  225. return false if encrypted_password.blank?
  226. super
  227. end
  228. def show_all_media?
  229. setting_display_media == 'show_all'
  230. end
  231. def hide_all_media?
  232. setting_display_media == 'hide_all'
  233. end
  234. def recent_ips
  235. @recent_ips ||= begin
  236. arr = []
  237. session_activations.each do |session_activation|
  238. arr << [session_activation.updated_at, session_activation.ip]
  239. end
  240. arr << [current_sign_in_at, current_sign_in_ip] if current_sign_in_ip.present?
  241. arr << [last_sign_in_at, last_sign_in_ip] if last_sign_in_ip.present?
  242. arr.sort_by(&:first).uniq(&:last).reverse!
  243. end
  244. end
  245. protected
  246. def send_devise_notification(notification, *args)
  247. devise_mailer.send(notification, self, *args).deliver_later
  248. end
  249. private
  250. def set_approved
  251. self.approved = open_registrations? || valid_invitation? || external?
  252. end
  253. def open_registrations?
  254. Setting.registrations_mode == 'open'
  255. end
  256. def external?
  257. !!@external
  258. end
  259. def sanitize_languages
  260. return if chosen_languages.nil?
  261. chosen_languages.reject!(&:blank?)
  262. self.chosen_languages = nil if chosen_languages.empty?
  263. end
  264. def prepare_new_user!
  265. BootstrapTimelineWorker.perform_async(account_id)
  266. ActivityTracker.increment('activity:accounts:local')
  267. UserMailer.welcome(self).deliver_later
  268. end
  269. def prepare_returning_user!
  270. ActivityTracker.record('activity:logins', id)
  271. regenerate_feed! if needs_feed_update?
  272. end
  273. def notify_staff_about_pending_account!
  274. User.staff.includes(:account).each do |u|
  275. next unless u.allows_pending_account_emails?
  276. AdminMailer.new_pending_account(u.account, self).deliver_later
  277. end
  278. end
  279. def regenerate_feed!
  280. return unless Redis.current.setnx("account:#{account_id}:regeneration", true)
  281. Redis.current.expire("account:#{account_id}:regeneration", 1.day.seconds)
  282. RegenerationWorker.perform_async(account_id)
  283. end
  284. def needs_feed_update?
  285. last_sign_in_at < ACTIVE_DURATION.ago
  286. end
  287. def validate_email_dns?
  288. email_changed? && !(Rails.env.test? || Rails.env.development?)
  289. end
  290. end