]> cat aescling's git repositories - mastodon.git/blob - app/models/user.rb
Fix featured hashtag URL being interpreted as media or with_replies (#12048)
[mastodon.git] / app / models / user.rb
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 # approved :boolean default(TRUE), not null
41 #
42
43 class User < ApplicationRecord
44 include Settings::Extend
45 include UserRoles
46
47 # The home and list feeds will be stored in Redis for this amount
48 # of time, and status fan-out to followers will include only people
49 # within this time frame. Lowering the duration may improve performance
50 # if lots of people sign up, but not a lot of them check their feed
51 # every day. Raising the duration reduces the amount of expensive
52 # RegenerationWorker jobs that need to be run when those people come
53 # to check their feed
54 ACTIVE_DURATION = ENV.fetch('USER_ACTIVE_DAYS', 7).to_i.days.freeze
55
56 devise :two_factor_authenticatable,
57 otp_secret_encryption_key: Rails.configuration.x.otp_secret
58
59 devise :two_factor_backupable,
60 otp_number_of_backup_codes: 10
61
62 devise :registerable, :recoverable, :rememberable, :trackable, :validatable,
63 :confirmable
64
65 include Omniauthable
66 include PamAuthenticable
67 include LdapAuthenticable
68
69 belongs_to :account, inverse_of: :user
70 belongs_to :invite, counter_cache: :uses, optional: true
71 belongs_to :created_by_application, class_name: 'Doorkeeper::Application', optional: true
72 accepts_nested_attributes_for :account
73
74 has_many :applications, class_name: 'Doorkeeper::Application', as: :owner
75 has_many :backups, inverse_of: :user
76 has_many :invites, inverse_of: :user
77 has_many :markers, inverse_of: :user, dependent: :destroy
78
79 has_one :invite_request, class_name: 'UserInviteRequest', inverse_of: :user, dependent: :destroy
80 accepts_nested_attributes_for :invite_request, reject_if: ->(attributes) { attributes['text'].blank? }
81
82 validates :locale, inclusion: I18n.available_locales.map(&:to_s), if: :locale?
83 validates_with BlacklistedEmailValidator, on: :create
84 validates_with EmailMxValidator, if: :validate_email_dns?
85 validates :agreement, acceptance: { allow_nil: false, accept: [true, 'true', '1'] }, on: :create
86
87 scope :recent, -> { order(id: :desc) }
88 scope :pending, -> { where(approved: false) }
89 scope :approved, -> { where(approved: true) }
90 scope :confirmed, -> { where.not(confirmed_at: nil) }
91 scope :enabled, -> { where(disabled: false) }
92 scope :disabled, -> { where(disabled: true) }
93 scope :inactive, -> { where(arel_table[:current_sign_in_at].lt(ACTIVE_DURATION.ago)) }
94 scope :active, -> { confirmed.where(arel_table[:current_sign_in_at].gteq(ACTIVE_DURATION.ago)).joins(:account).where(accounts: { suspended_at: nil }) }
95 scope :matches_email, ->(value) { where(arel_table[:email].matches("#{value}%")) }
96 scope :emailable, -> { confirmed.enabled.joins(:account).merge(Account.searchable) }
97
98 before_validation :sanitize_languages
99 before_create :set_approved
100
101 # This avoids a deprecation warning from Rails 5.1
102 # It seems possible that a future release of devise-two-factor will
103 # handle this itself, and this can be removed from our User class.
104 attribute :otp_secret
105
106 has_many :session_activations, dependent: :destroy
107
108 delegate :auto_play_gif, :default_sensitive, :unfollow_modal, :boost_modal, :delete_modal,
109 :reduce_motion, :system_font_ui, :noindex, :theme, :display_media, :hide_network,
110 :expand_spoilers, :default_language, :aggregate_reblogs, :show_application,
111 :advanced_layout, :use_blurhash, :use_pending_items, :trends,
112 to: :settings, prefix: :setting, allow_nil: false
113
114 attr_reader :invite_code
115 attr_writer :external
116
117 def confirmed?
118 confirmed_at.present?
119 end
120
121 def invited?
122 invite_id.present?
123 end
124
125 def valid_invitation?
126 invite_id.present? && invite.valid_for_use?
127 end
128
129 def disable!
130 update!(disabled: true,
131 last_sign_in_at: current_sign_in_at,
132 current_sign_in_at: nil)
133 end
134
135 def enable!
136 update!(disabled: false)
137 end
138
139 def confirm
140 new_user = !confirmed?
141 self.approved = true if open_registrations?
142
143 super
144
145 if new_user && approved?
146 prepare_new_user!
147 elsif new_user
148 notify_staff_about_pending_account!
149 end
150 end
151
152 def confirm!
153 new_user = !confirmed?
154 self.approved = true if open_registrations?
155
156 skip_confirmation!
157 save!
158
159 prepare_new_user! if new_user && approved?
160 end
161
162 def pending?
163 !approved?
164 end
165
166 def active_for_authentication?
167 true
168 end
169
170 def functional?
171 confirmed? && approved? && !disabled? && !account.suspended? && account.moved_to_account_id.nil?
172 end
173
174 def unconfirmed_or_pending?
175 !(confirmed? && approved?)
176 end
177
178 def inactive_message
179 !approved? ? :pending : super
180 end
181
182 def approve!
183 return if approved?
184
185 update!(approved: true)
186 prepare_new_user!
187 end
188
189 def update_tracked_fields!(request)
190 super
191 prepare_returning_user!
192 end
193
194 def disable_two_factor!
195 self.otp_required_for_login = false
196 otp_backup_codes&.clear
197 save!
198 end
199
200 def setting_default_privacy
201 settings.default_privacy || (account.locked? ? 'private' : 'public')
202 end
203
204 def allows_digest_emails?
205 settings.notification_emails['digest']
206 end
207
208 def allows_report_emails?
209 settings.notification_emails['report']
210 end
211
212 def allows_pending_account_emails?
213 settings.notification_emails['pending_account']
214 end
215
216 def allows_trending_tag_emails?
217 settings.notification_emails['trending_tag']
218 end
219
220 def hides_network?
221 @hides_network ||= settings.hide_network
222 end
223
224 def aggregates_reblogs?
225 @aggregates_reblogs ||= settings.aggregate_reblogs
226 end
227
228 def shows_application?
229 @shows_application ||= settings.show_application
230 end
231
232 def token_for_app(a)
233 return nil if a.nil? || a.owner != self
234 Doorkeeper::AccessToken
235 .find_or_create_by(application_id: a.id, resource_owner_id: id) do |t|
236
237 t.scopes = a.scopes
238 t.expires_in = Doorkeeper.configuration.access_token_expires_in
239 t.use_refresh_token = Doorkeeper.configuration.refresh_token_enabled?
240 end
241 end
242
243 def activate_session(request)
244 session_activations.activate(session_id: SecureRandom.hex,
245 user_agent: request.user_agent,
246 ip: request.remote_ip).session_id
247 end
248
249 def exclusive_session(id)
250 session_activations.exclusive(id)
251 end
252
253 def session_active?(id)
254 session_activations.active? id
255 end
256
257 def web_push_subscription(session)
258 session.web_push_subscription.nil? ? nil : session.web_push_subscription
259 end
260
261 def invite_code=(code)
262 self.invite = Invite.find_by(code: code) if code.present?
263 @invite_code = code
264 end
265
266 def password_required?
267 return false if external?
268
269 super
270 end
271
272 def send_reset_password_instructions
273 return false if encrypted_password.blank?
274
275 super
276 end
277
278 def reset_password!(new_password, new_password_confirmation)
279 return false if encrypted_password.blank?
280
281 super
282 end
283
284 def show_all_media?
285 setting_display_media == 'show_all'
286 end
287
288 def hide_all_media?
289 setting_display_media == 'hide_all'
290 end
291
292 protected
293
294 def send_devise_notification(notification, *args)
295 devise_mailer.send(notification, self, *args).deliver_later
296 end
297
298 private
299
300 def set_approved
301 self.approved = open_registrations? || valid_invitation? || external?
302 end
303
304 def open_registrations?
305 Setting.registrations_mode == 'open'
306 end
307
308 def external?
309 !!@external
310 end
311
312 def sanitize_languages
313 return if chosen_languages.nil?
314 chosen_languages.reject!(&:blank?)
315 self.chosen_languages = nil if chosen_languages.empty?
316 end
317
318 def prepare_new_user!
319 BootstrapTimelineWorker.perform_async(account_id)
320 ActivityTracker.increment('activity:accounts:local')
321 UserMailer.welcome(self).deliver_later
322 end
323
324 def prepare_returning_user!
325 ActivityTracker.record('activity:logins', id)
326 regenerate_feed! if needs_feed_update?
327 end
328
329 def notify_staff_about_pending_account!
330 User.staff.includes(:account).each do |u|
331 next unless u.allows_pending_account_emails?
332 AdminMailer.new_pending_account(u.account, self).deliver_later
333 end
334 end
335
336 def regenerate_feed!
337 return unless Redis.current.setnx("account:#{account_id}:regeneration", true)
338 Redis.current.expire("account:#{account_id}:regeneration", 1.day.seconds)
339 RegenerationWorker.perform_async(account_id)
340 end
341
342 def needs_feed_update?
343 last_sign_in_at < ACTIVE_DURATION.ago
344 end
345
346 def validate_email_dns?
347 email_changed? && !(Rails.env.test? || Rails.env.development?)
348 end
349 end
This page took 0.138224 seconds and 4 git commands to generate.