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.
 
 
 
 

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