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.
 
 
 
 

320 lines
8.6 KiB

  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: users
  5. #
  6. # id :integer 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 :integer not null
  34. # disabled :boolean default(FALSE), not null
  35. # moderator :boolean default(FALSE), not null
  36. # invite_id :integer
  37. # remember_token :string
  38. #
  39. class User < ApplicationRecord
  40. include Settings::Extend
  41. include Omniauthable
  42. ACTIVE_DURATION = 14.days
  43. devise :two_factor_authenticatable,
  44. otp_secret_encryption_key: ENV['OTP_SECRET']
  45. devise :two_factor_backupable,
  46. otp_number_of_backup_codes: 10
  47. devise :registerable, :recoverable, :rememberable, :trackable, :validatable,
  48. :confirmable
  49. devise :pam_authenticatable if Devise.pam_authentication
  50. devise :omniauthable
  51. belongs_to :account, inverse_of: :user
  52. belongs_to :invite, counter_cache: :uses, optional: true
  53. accepts_nested_attributes_for :account
  54. has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
  55. has_many :backups, inverse_of: :user
  56. validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
  57. validates_with BlacklistedEmailValidator, if: :email_changed?
  58. scope :recent, -> { order(id: :desc) }
  59. scope :admins, -> { where(admin: true) }
  60. scope :moderators, -> { where(moderator: true) }
  61. scope :staff, -> { admins.or(moderators) }
  62. scope :confirmed, -> { where.not(confirmed_at: nil) }
  63. scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
  64. scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended: false }) }
  65. scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
  66. scope :with_recent_ip_address, ->(value) { where(arel_table[:current_sign_in_ip].eq(value).or(arel_table[:last_sign_in_ip].eq(value))) }
  67. before_validation :sanitize_languages
  68. # This avoids a deprecation warning from Rails 5.1
  69. # It seems possible that a future release of devise-two-factor will
  70. # handle this itself, and this can be removed from our User class.
  71. attribute :otp_secret
  72. has_many :session_activations, dependent: :destroy
  73. delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
  74. :reduce_motion, :system_font_ui, :noindex, :theme, :display_sensitive_media,
  75. to: :settings, prefix: :setting, allow_nil: false
  76. attr_accessor :invite_code
  77. def pam_conflict(_)
  78. # block pam login tries on traditional account
  79. nil
  80. end
  81. def pam_conflict?
  82. return false unless Devise.pam_authentication
  83. encrypted_password.present? && is_pam_account?
  84. end
  85. def pam_get_name
  86. return account.username if account.present?
  87. super
  88. end
  89. def pam_setup(_attributes)
  90. acc = Account.new(username: pam_get_name)
  91. acc.save!(validate: false)
  92. self.email = "#{acc.username}@#{find_pam_suffix}" if email.nil? && find_pam_suffix
  93. self.confirmed_at = Time.now.utc
  94. self.admin = false
  95. self.account = acc
  96. acc.destroy! unless save
  97. end
  98. def confirmed?
  99. confirmed_at.present?
  100. end
  101. def staff?
  102. admin? || moderator?
  103. end
  104. def role
  105. if admin?
  106. 'admin'
  107. elsif moderator?
  108. 'moderator'
  109. else
  110. 'user'
  111. end
  112. end
  113. def role?(role)
  114. case role
  115. when 'user'
  116. true
  117. when 'moderator'
  118. staff?
  119. when 'admin'
  120. admin?
  121. else
  122. false
  123. end
  124. end
  125. def disable!
  126. update!(disabled: true,
  127. last_sign_in_at: current_sign_in_at,
  128. current_sign_in_at: nil)
  129. end
  130. def enable!
  131. update!(disabled: false)
  132. end
  133. def confirm
  134. new_user = !confirmed?
  135. super
  136. prepare_new_user! if new_user
  137. end
  138. def confirm!
  139. new_user = !confirmed?
  140. skip_confirmation!
  141. save!
  142. prepare_new_user! if new_user
  143. end
  144. def update_tracked_fields!(request)
  145. super
  146. prepare_returning_user!
  147. end
  148. def promote!
  149. if moderator?
  150. update!(moderator: false, admin: true)
  151. elsif !admin?
  152. update!(moderator: true)
  153. end
  154. end
  155. def demote!
  156. if admin?
  157. update!(admin: false, moderator: true)
  158. elsif moderator?
  159. update!(moderator: false)
  160. end
  161. end
  162. def disable_two_factor!
  163. self.otp_required_for_login = false
  164. otp_backup_codes&.clear
  165. save!
  166. end
  167. def active_for_authentication?
  168. super && !disabled?
  169. end
  170. def setting_default_privacy
  171. settings.default_privacy || (account.locked? ? 'private' : 'public')
  172. end
  173. def allows_digest_emails?
  174. settings.notification_emails['digest']
  175. end
  176. def token_for_app(a)
  177. return nil if a.nil? || a.owner != self
  178. Doorkeeper::AccessToken
  179. .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
  180. t.scopes = a.scopes
  181. t.expires_in = Doorkeeper.configuration.access_token_expires_in
  182. t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
  183. end
  184. end
  185. def activate_session(request)
  186. session_activations.activate(session_id: SecureRandom.hex,
  187. user_agent: request.user_agent,
  188. ip: request.remote_ip).session_id
  189. end
  190. def exclusive_session(id)
  191. session_activations.exclusive(id)
  192. end
  193. def session_active?(id)
  194. session_activations.active? id
  195. end
  196. def web_push_subscription(session)
  197. session.web_push_subscription.nil? ? nil : session.web_push_subscription.as_payload
  198. end
  199. def invite_code=(code)
  200. self.invite = Invite.find_by(code: code) unless code.blank?
  201. @invite_code = code
  202. end
  203. def password_required?
  204. return false if Devise.pam_authentication
  205. super
  206. end
  207. def send_reset_password_instructions
  208. return false if encrypted_password.blank? && Devise.pam_authentication
  209. super
  210. end
  211. def reset_password!(new_password, new_password_confirmation)
  212. return false if encrypted_password.blank? && Devise.pam_authentication
  213. super
  214. end
  215. def self.pam_get_user(attributes = {})
  216. if attributes[:email]
  217. resource =
  218. if Devise.check_at_sign && !attributes[:email].index('@')
  219. joins(:account).find_by(accounts: { username: attributes[:email] })
  220. else
  221. find_by(email: attributes[:email])
  222. end
  223. if resource.blank?
  224. resource = new(email: attributes[:email])
  225. if Devise.check_at_sign && !resource[:email].index('@')
  226. resource[:email] = "#{attributes[:email]}@#{resource.find_pam_suffix}"
  227. end
  228. end
  229. resource
  230. end
  231. end
  232. def self.authenticate_with_pam(attributes = {})
  233. return nil unless Devise.pam_authentication
  234. super
  235. end
  236. protected
  237. def send_devise_notification(notification, *args)
  238. devise_mailer.send(notification, self, *args).deliver_later
  239. end
  240. private
  241. def sanitize_languages
  242. filtered_languages.reject!(&:blank?)
  243. end
  244. def prepare_new_user!
  245. BootstrapTimelineWorker.perform_async(account_id)
  246. ActivityTracker.increment('activity:accounts:local')
  247. UserMailer.welcome(self).deliver_later
  248. end
  249. def prepare_returning_user!
  250. ActivityTracker.record('activity:logins', id)
  251. regenerate_feed! if needs_feed_update?
  252. end
  253. def regenerate_feed!
  254. Redis.current.setnx("account:#{account_id}:regeneration", true) && Redis.current.expire("account:#{account_id}:regeneration", 1.day.seconds)
  255. RegenerationWorker.perform_async(account_id)
  256. end
  257. def needs_feed_update?
  258. last_sign_in_at < ACTIVE_DURATION.ago
  259. end
  260. end