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.
 
 
 
 

353 lines
10 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. #
  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. scope :with_recent_ip_address, ->(value) { where(arel_table[:current_sign_in_ip].eq(value).or(arel_table[:last_sign_in_ip].eq(value))) }
  76. before_validation :sanitize_languages
  77. # This avoids a deprecation warning from Rails 5.1
  78. # It seems possible that a future release of devise-two-factor will
  79. # handle this itself, and this can be removed from our User class.
  80. attribute :otp_secret
  81. has_many :session_activations, dependent: :destroy
  82. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  83. :reduce_motion, :system_font_ui, :noindex, :theme, :display_sensitive_media, :hide_network,
  84. :default_language, to: :settings, prefix: :setting, allow_nil: false
  85. attr_reader :invite_code
  86. def pam_conflict(_)
  87. # block pam login tries on traditional account
  88. nil
  89. end
  90. def pam_conflict?
  91. return false unless Devise.pam_authentication
  92. encrypted_password.present? && pam_managed_user?
  93. end
  94. def pam_get_name
  95. return account.username if account.present?
  96. super
  97. end
  98. def pam_setup(_attributes)
  99. acc = Account.new(username: pam_get_name)
  100. acc.save!(validate: false)
  101. self.email = "#{acc.username}@#{find_pam_suffix}" if email.nil? && find_pam_suffix
  102. self.confirmed_at = Time.now.utc
  103. self.admin = false
  104. self.account = acc
  105. acc.destroy! unless save
  106. end
  107. def ldap_setup(_attributes)
  108. self.confirmed_at = Time.now.utc
  109. self.admin = false
  110. save!
  111. end
  112. def confirmed?
  113. confirmed_at.present?
  114. end
  115. def staff?
  116. admin? || moderator?
  117. end
  118. def role
  119. if admin?
  120. 'admin'
  121. elsif moderator?
  122. 'moderator'
  123. else
  124. 'user'
  125. end
  126. end
  127. def role?(role)
  128. case role
  129. when 'user'
  130. true
  131. when 'moderator'
  132. staff?
  133. when 'admin'
  134. admin?
  135. else
  136. false
  137. end
  138. end
  139. def disable!
  140. update!(disabled: true,
  141. last_sign_in_at: current_sign_in_at,
  142. current_sign_in_at: nil)
  143. end
  144. def enable!
  145. update!(disabled: false)
  146. end
  147. def confirm
  148. new_user = !confirmed?
  149. super
  150. prepare_new_user! if new_user
  151. end
  152. def confirm!
  153. new_user = !confirmed?
  154. skip_confirmation!
  155. save!
  156. prepare_new_user! if new_user
  157. end
  158. def update_tracked_fields!(request)
  159. super
  160. prepare_returning_user!
  161. end
  162. def promote!
  163. if moderator?
  164. update!(moderator: false, admin: true)
  165. elsif !admin?
  166. update!(moderator: true)
  167. end
  168. end
  169. def demote!
  170. if admin?
  171. update!(admin: false, moderator: true)
  172. elsif moderator?
  173. update!(moderator: false)
  174. end
  175. end
  176. def disable_two_factor!
  177. self.otp_required_for_login = false
  178. otp_backup_codes&.clear
  179. save!
  180. end
  181. def setting_default_privacy
  182. settings.default_privacy || (account.locked? ? 'private' : 'public')
  183. end
  184. def allows_digest_emails?
  185. settings.notification_emails['digest']
  186. end
  187. def allows_report_emails?
  188. settings.notification_emails['report']
  189. end
  190. def hides_network?
  191. @hides_network ||= settings.hide_network
  192. end
  193. def token_for_app(a)
  194. return nil if a.nil? || a.owner != self
  195. Doorkeeper::AccessToken
  196. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  197. t.scopes = a.scopes
  198. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  199. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  200. end
  201. end
  202. def activate_session(request)
  203. session_activations.activate(session_id: SecureRandom.hex,
  204. user_agent: request.user_agent,
  205. ip: request.remote_ip).session_id
  206. end
  207. def exclusive_session(id)
  208. session_activations.exclusive(id)
  209. end
  210. def session_active?(id)
  211. session_activations.active? id
  212. end
  213. def web_push_subscription(session)
  214. session.web_push_subscription.nil? ? nil : session.web_push_subscription
  215. end
  216. def invite_code=(code)
  217. self.invite = Invite.find_by(code: code) if code.present?
  218. @invite_code = code
  219. end
  220. def password_required?
  221. return false if Devise.pam_authentication || Devise.ldap_authentication
  222. super
  223. end
  224. def send_reset_password_instructions
  225. return false if encrypted_password.blank? && (Devise.pam_authentication || Devise.ldap_authentication)
  226. super
  227. end
  228. def reset_password!(new_password, new_password_confirmation)
  229. return false if encrypted_password.blank? && (Devise.pam_authentication || Devise.ldap_authentication)
  230. super
  231. end
  232. def self.pam_get_user(attributes = {})
  233. return nil unless attributes[:email]
  234. resource =
  235. if Devise.check_at_sign && !attributes[:email].index('@')
  236. joins(:account).find_by(accounts: { username: attributes[:email] })
  237. else
  238. find_by(email: attributes[:email])
  239. end
  240. if resource.blank?
  241. resource = new(email: attributes[:email])
  242. if Devise.check_at_sign && !resource[:email].index('@')
  243. resource[:email] = Rpam2.getenv(resource.find_pam_service, attributes[:email], attributes[:password], 'email', false)
  244. resource[:email] = "#{attributes[:email]}@#{resource.find_pam_suffix}" unless resource[:email]
  245. end
  246. end
  247. resource
  248. end
  249. def self.ldap_get_user(attributes = {})
  250. resource = joins(:account).find_by(accounts: { username: attributes[Devise.ldap_uid.to_sym].first })
  251. if resource.blank?
  252. resource = new(email: attributes[:mail].first, account_attributes: { username: attributes[Devise.ldap_uid.to_sym].first })
  253. resource.ldap_setup(attributes)
  254. end
  255. resource
  256. end
  257. def self.authenticate_with_pam(attributes = {})
  258. return nil unless Devise.pam_authentication
  259. super
  260. end
  261. protected
  262. def send_devise_notification(notification, *args)
  263. devise_mailer.send(notification, self, *args).deliver_later
  264. end
  265. private
  266. def sanitize_languages
  267. return if chosen_languages.nil?
  268. chosen_languages.reject!(&:blank?)
  269. self.chosen_languages = nil if chosen_languages.empty?
  270. end
  271. def prepare_new_user!
  272. BootstrapTimelineWorker.perform_async(account_id)
  273. ActivityTracker.increment('activity:accounts:local')
  274. UserMailer.welcome(self).deliver_later
  275. end
  276. def prepare_returning_user!
  277. ActivityTracker.record('activity:logins', id)
  278. regenerate_feed! if needs_feed_update?
  279. end
  280. def regenerate_feed!
  281. Redis.current.setnx("account:#{account_id}:regeneration", true) && 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. end