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.
 
 
 
 

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