The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

336 lines
9.9 KiB

  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_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
  69. accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? }
  70. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  71. validates_with BlacklistedEmailValidator, on: :create
  72. validates_with EmailMxValidator, if: :validate_email_dns?
  73. validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
  74. scope :recent, -> { order(id: :desc) }
  75. scope :pending, -> { where(approved: false) }
  76. scope :approved, -> { where(approved: true) }
  77. scope :confirmed, -> { where.not(confirmed_at: nil) }
  78. scope :enabled, -> { where(disabled: false) }
  79. scope :disabled, -> { where(disabled: true) }
  80. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  81. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
  82. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  83. scope :emailable, -> { confirmed.enabled.joins(:account).merge(Account.searchable) }
  84. before_validation :sanitize_languages
  85. before_create :set_approved
  86. # This avoids a deprecation warning from Rails 5.1
  87. # It seems possible that a future release of devise-two-factor will
  88. # handle this itself, and this can be removed from our User class.
  89. attribute :otp_secret
  90. has_many :session_activations, dependent: :destroy
  91. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  92. :reduce_motion, :system_font_ui, :noindex, :theme, :display_media, :hide_network,
  93. :expand_spoilers, :default_language, :aggregate_reblogs, :show_application,
  94. :advanced_layout, :use_blurhash, :use_pending_items, to: :settings, prefix: :setting, allow_nil: false
  95. attr_reader :invite_code
  96. attr_writer :external
  97. def confirmed?
  98. confirmed_at.present?
  99. end
  100. def invited?
  101. invite_id.present?
  102. end
  103. def valid_invitation?
  104. invite_id.present? && invite.valid_for_use?
  105. end
  106. def disable!
  107. update!(disabled: true,
  108. last_sign_in_at: current_sign_in_at,
  109. current_sign_in_at: nil)
  110. end
  111. def enable!
  112. update!(disabled: false)
  113. end
  114. def confirm
  115. new_user = !confirmed?
  116. self.approved = true if open_registrations?
  117. super
  118. if new_user && approved?
  119. prepare_new_user!
  120. elsif new_user
  121. notify_staff_about_pending_account!
  122. end
  123. end
  124. def confirm!
  125. new_user = !confirmed?
  126. self.approved = true if open_registrations?
  127. skip_confirmation!
  128. save!
  129. prepare_new_user! if new_user && approved?
  130. end
  131. def pending?
  132. !approved?
  133. end
  134. def active_for_authentication?
  135. true
  136. end
  137. def functional?
  138. confirmed? && approved? && !disabled? && !account.suspended?
  139. end
  140. def inactive_message
  141. !approved? ? :pending : super
  142. end
  143. def approve!
  144. return if approved?
  145. update!(approved: true)
  146. prepare_new_user!
  147. end
  148. def update_tracked_fields!(request)
  149. super
  150. prepare_returning_user!
  151. end
  152. def disable_two_factor!
  153. self.otp_required_for_login = false
  154. otp_backup_codes&.clear
  155. save!
  156. end
  157. def setting_default_privacy
  158. settings.default_privacy || (account.locked? ? 'private' : 'public')
  159. end
  160. def allows_digest_emails?
  161. settings.notification_emails['digest']
  162. end
  163. def allows_report_emails?
  164. settings.notification_emails['report']
  165. end
  166. def allows_pending_account_emails?
  167. settings.notification_emails['pending_account']
  168. end
  169. def hides_network?
  170. @hides_network ||= settings.hide_network
  171. end
  172. def aggregates_reblogs?
  173. @aggregates_reblogs ||= settings.aggregate_reblogs
  174. end
  175. def shows_application?
  176. @shows_application ||= settings.show_application
  177. end
  178. def token_for_app(a)
  179. return nil if a.nil? || a.owner != self
  180. Doorkeeper::AccessToken
  181. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  182. t.scopes = a.scopes
  183. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  184. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  185. end
  186. end
  187. def activate_session(request)
  188. session_activations.activate(session_id: SecureRandom.hex,
  189. user_agent: request.user_agent,
  190. ip: request.remote_ip).session_id
  191. end
  192. def exclusive_session(id)
  193. session_activations.exclusive(id)
  194. end
  195. def session_active?(id)
  196. session_activations.active? id
  197. end
  198. def web_push_subscription(session)
  199. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  200. end
  201. def invite_code=(code)
  202. self.invite = Invite.find_by(code: code) if code.present?
  203. @invite_code = code
  204. end
  205. def password_required?
  206. return false if Devise.pam_authentication || Devise.ldap_authentication
  207. super
  208. end
  209. def send_reset_password_instructions
  210. return false if encrypted_password.blank? && (Devise.pam_authentication || Devise.ldap_authentication)
  211. super
  212. end
  213. def reset_password!(new_password, new_password_confirmation)
  214. return false if encrypted_password.blank? && (Devise.pam_authentication || Devise.ldap_authentication)
  215. super
  216. end
  217. def show_all_media?
  218. setting_display_media == 'show_all'
  219. end
  220. def hide_all_media?
  221. setting_display_media == 'hide_all'
  222. end
  223. protected
  224. def send_devise_notification(notification, *args)
  225. devise_mailer.send(notification, self, *args).deliver_later
  226. end
  227. private
  228. def set_approved
  229. self.approved = open_registrations? || valid_invitation? || external?
  230. end
  231. def open_registrations?
  232. Setting.registrations_mode == 'open'
  233. end
  234. def external?
  235. !!@external
  236. end
  237. def sanitize_languages
  238. return if chosen_languages.nil?
  239. chosen_languages.reject!(&:blank?)
  240. self.chosen_languages = nil if chosen_languages.empty?
  241. end
  242. def prepare_new_user!
  243. BootstrapTimelineWorker.perform_async(account_id)
  244. ActivityTracker.increment('activity:accounts:local')
  245. UserMailer.welcome(self).deliver_later
  246. end
  247. def prepare_returning_user!
  248. ActivityTracker.record('activity:logins', id)
  249. regenerate_feed! if needs_feed_update?
  250. end
  251. def notify_staff_about_pending_account!
  252. User.staff.includes(:account).each do |u|
  253. next unless u.allows_pending_account_emails?
  254. AdminMailer.new_pending_account(u.account, self).deliver_later
  255. end
  256. end
  257. def regenerate_feed!
  258. return unless Redis.current.setnx("account:#{account_id}:regeneration", true)
  259. Redis.current.expire("account:#{account_id}:regeneration", 1.day.seconds)
  260. RegenerationWorker.perform_async(account_id)
  261. end
  262. def needs_feed_update?
  263. last_sign_in_at < ACTIVE_DURATION.ago
  264. end
  265. def validate_email_dns?
  266. email_changed? && !(Rails.env.test? || Rails.env.development?)
  267. end
  268. end