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.
 
 
 
 

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