user.rb 10 KB

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