]> git.openstreetmap.org Git - rails.git/blob - app/models/user.rb
Remove unnecessary requires; use gems when possible
[rails.git] / app / models / user.rb
1 # frozen_string_literal: true
2
3 # == Schema Information
4 #
5 # Table name: users
6 #
7 #  email                :string           not null
8 #  id                   :bigint           not null, primary key
9 #  pass_crypt           :string           not null
10 #  creation_time        :datetime         not null
11 #  display_name         :string           default(""), not null
12 #  data_public          :boolean          default(FALSE), not null
13 #  description          :text             default(""), not null
14 #  home_lat             :float
15 #  home_lon             :float
16 #  home_zoom            :integer          default(3)
17 #  home_location_name   :string
18 #  pass_salt            :string
19 #  email_valid          :boolean          default(FALSE), not null
20 #  new_email            :string
21 #  languages            :string
22 #  status               :enum             default("pending"), not null
23 #  terms_agreed         :datetime
24 #  consider_pd          :boolean          default(FALSE), not null
25 #  auth_uid             :string
26 #  preferred_editor     :string
27 #  terms_seen           :boolean          default(FALSE), not null
28 #  description_format   :enum             default("markdown"), not null
29 #  changesets_count     :integer          default(0), not null
30 #  traces_count         :integer          default(0), not null
31 #  diary_entries_count  :integer          default(0), not null
32 #  image_use_gravatar   :boolean          default(FALSE), not null
33 #  auth_provider        :string
34 #  home_tile            :bigint
35 #  tou_agreed           :datetime
36 #  diary_comments_count :integer          default(0)
37 #  note_comments_count  :integer          default(0)
38 #  creation_address     :inet
39 #  company              :string
40 #
41 # Indexes
42 #
43 #  index_users_on_creation_address   (creation_address) USING gist
44 #  users_auth_idx                    (auth_provider,auth_uid) UNIQUE
45 #  users_display_name_canonical_idx  (lower(NORMALIZE(display_name, NFKC)))
46 #  users_display_name_idx            (display_name) UNIQUE
47 #  users_email_idx                   (email) UNIQUE
48 #  users_email_lower_idx             (lower((email)::text))
49 #  users_home_idx                    (home_tile)
50 #
51
52 class User < ApplicationRecord
53   include AASM
54
55   has_many :traces, -> { where(:visible => true) }
56   has_many :diary_entries, -> { order(:created_at => :desc) }, :inverse_of => :user
57   has_many :diary_comments, -> { order(:created_at => :desc) }, :inverse_of => :user
58   has_many :diary_entry_subscriptions, :class_name => "DiaryEntrySubscription"
59   has_many :diary_subscriptions, :through => :diary_entry_subscriptions, :source => :diary_entry
60   has_many :messages, -> { where(:to_user_visible => true, :muted => false).order(:sent_on => :desc).preload(:sender, :recipient) }, :foreign_key => :to_user_id
61   has_many :new_messages, -> { where(:to_user_visible => true, :muted => false, :message_read => false).order(:sent_on => :desc) }, :class_name => "Message", :foreign_key => :to_user_id
62   has_many :sent_messages, -> { where(:from_user_visible => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :class_name => "Message", :foreign_key => :from_user_id
63   has_many :muted_messages, -> { where(:to_user_visible => true, :muted => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :class_name => "Message", :foreign_key => :to_user_id
64   has_many :follows, -> { joins(:following).where(:users => { :status => %w[active confirmed] }) }
65   has_many :followings, :through => :follows, :source => :following
66   has_many :preferences, :class_name => "UserPreference"
67   has_many :changesets, -> { order(:created_at => :desc) }, :inverse_of => :user
68   has_many :changeset_comments, :foreign_key => :author_id, :inverse_of => :author
69   has_many :changeset_subscriptions, :foreign_key => :subscriber_id
70   has_many :note_comments, :foreign_key => :author_id, :inverse_of => :author
71   has_many :notes, :through => :note_comments
72   has_many :note_subscriptions, :class_name => "NoteSubscription"
73   has_many :subscribed_notes, :through => :note_subscriptions, :source => :note
74
75   has_many :oauth2_applications, :class_name => Doorkeeper.config.application_model.name, :as => :owner
76   has_many :access_grants, :class_name => Doorkeeper.config.access_grant_model.name, :foreign_key => :resource_owner_id
77   has_many :access_tokens, :class_name => Doorkeeper.config.access_token_model.name, :foreign_key => :resource_owner_id
78
79   has_many :blocks, :class_name => "UserBlock"
80   has_many :blocks_created, :class_name => "UserBlock", :foreign_key => :creator_id, :inverse_of => :creator
81   has_many :blocks_revoked, :class_name => "UserBlock", :foreign_key => :revoker_id, :inverse_of => :revoker
82
83   has_many :mutes, -> { order(:created_at => :desc) }, :class_name => "UserMute", :foreign_key => :owner_id, :inverse_of => :owner
84   has_many :muted_users, :through => :mutes, :source => :subject
85
86   has_many :roles, :class_name => "UserRole"
87
88   has_many :issues, :class_name => "Issue", :foreign_key => :reported_user_id, :inverse_of => :reported_user
89   has_many :issue_comments
90
91   has_many :reports
92
93   has_many :social_links
94   accepts_nested_attributes_for :social_links, :allow_destroy => true
95
96   scope :visible, -> { where(:status => %w[pending active confirmed]) }
97   scope :active, -> { where(:status => %w[active confirmed]) }
98   scope :identifiable, -> { where(:data_public => true) }
99
100   has_one_attached :avatar, :service => Settings.avatar_storage
101
102   validates :display_name, :presence => true, :length => 3..255,
103                            :exclusion => %w[new terms save confirm confirm-email go_public reset-password forgot-password suspended]
104   validates :display_name, :if => proc { |u| u.display_name_changed? },
105                            :normalized_uniqueness => { :case_sensitive => false }
106   validates :display_name, :if => proc { |u| u.display_name_changed? },
107                            :characters => { :url_safe => true },
108                            :whitespace => { :leading => false, :trailing => false },
109                            :width => { :minimum => 3 }
110   validate :display_name_cannot_be_user_id_with_other_id, :if => proc { |u| u.display_name_changed? }
111   validates :email, :presence => true, :characters => true
112   validates :email, :if => proc { |u| u.email_changed? },
113                     :uniqueness => { :case_sensitive => false }
114   validates :email, :if => proc { |u| u.email_changed? },
115                     :whitespace => { :leading => false, :trailing => false }
116   validates :pass_crypt, :confirmation => true, :length => 8..255
117   validates :home_lat, :allow_nil => true, :numericality => true, :inclusion => { :in => -90..90 }
118   validates :home_lon, :allow_nil => true, :numericality => true, :inclusion => { :in => -180..180 }
119   validates :home_zoom, :allow_nil => true, :numericality => { :only_integer => true }
120   validates :preferred_editor, :inclusion => Editors::ALL_EDITORS, :allow_nil => true
121   validates :auth_uid, :unless => proc { |u| u.auth_provider.nil? },
122                        :uniqueness => { :scope => :auth_provider }
123   validates :avatar, :if => proc { |u| u.attachment_changes["avatar"] },
124                      :image => true
125   validates :description, :length => 0..65536
126
127   validates_email_format_of :email, :if => proc { |u| u.email_changed? }
128   validates_email_format_of :new_email, :allow_blank => true, :if => proc { |u| u.new_email_changed? }
129
130   alias_attribute :created_at, :creation_time
131
132   before_save :encrypt_password
133   before_save :update_tile
134   after_save :spam_check
135
136   generates_token_for :new_user, :expires_in => 1.week do
137     fingerprint
138   end
139
140   generates_token_for :new_email, :expires_in => 1.week do
141     fingerprint
142   end
143
144   generates_token_for :password_reset, :expires_in => 1.week do
145     fingerprint
146   end
147
148   def display_name_cannot_be_user_id_with_other_id
149     display_name&.match(/^user_(\d+)$/i) do |m|
150       errors.add :display_name, I18n.t("activerecord.errors.messages.display_name_is_user_n") unless m[1].to_i == id
151     end
152   end
153
154   def to_param
155     display_name
156   end
157
158   def self.authenticate(options)
159     if options[:username] && options[:password]
160       user = find_by("email = ? OR display_name = ?", options[:username].strip, options[:username])
161
162       if user.nil?
163         users = where("LOWER(email) = LOWER(?) OR LOWER(NORMALIZE(display_name, NFKC)) = LOWER(NORMALIZE(?, NFKC))", options[:username].strip, options[:username])
164
165         user = users.first if users.one?
166       end
167
168       if user && PasswordHash.check(user.pass_crypt, user.pass_salt, options[:password])
169         if PasswordHash.upgrade?(user.pass_crypt, user.pass_salt)
170           user.pass_crypt, user.pass_salt = PasswordHash.create(options[:password])
171           user.save
172         end
173       else
174         user = nil
175       end
176     end
177
178     if user &&
179        (user.status == "deleted" ||
180          (user.status == "pending" && !options[:pending]) ||
181          (user.status == "suspended" && !options[:suspended]))
182       user = nil
183     end
184
185     user
186   end
187
188   aasm :column => :status, :no_direct_assignment => true do
189     state :pending, :initial => true
190     state :active
191     state :confirmed
192     state :suspended
193     state :deleted
194
195     # A normal account is active
196     event :activate do
197       transitions :from => :pending, :to => :active
198     end
199
200     # Used in test suite, not something that we would normally need to do.
201     if Rails.env.test?
202       event :deactivate do
203         transitions :from => :active, :to => :pending
204       end
205     end
206
207     # To confirm an account is used to override the spam scoring
208     event :confirm do
209       transitions :from => [:pending, :active, :suspended], :to => :confirmed
210     end
211
212     # To unconfirm an account is to make it subject to future spam scoring again
213     event :unconfirm do
214       transitions :from => :confirmed, :to => :active
215     end
216
217     # Accounts can be automatically suspended by spam_check
218     event :suspend do
219       transitions :from => [:pending, :active], :to => :suspended
220     end
221
222     # Unsuspending an account moves it back to active without overriding the spam scoring
223     event :unsuspend do
224       transitions :from => :suspended, :to => :active
225     end
226
227     # Mark the account as deleted but keep all data intact
228     event :hide do
229       transitions :from => [:pending, :active, :confirmed, :suspended], :to => :deleted
230     end
231
232     event :unhide do
233       transitions :from => [:deleted], :to => :active
234     end
235
236     # Mark the account as deleted and remove personal data
237     event :soft_destroy do
238       before do
239         revoke_authentication_tokens
240         remove_personal_data
241       end
242
243       transitions :from => [:pending, :active, :confirmed, :suspended], :to => :deleted
244     end
245   end
246
247   def description
248     RichText.new(self[:description_format], self[:description])
249   end
250
251   def languages
252     attribute_present?(:languages) ? self[:languages].split(/ *[, ] */) : []
253   end
254
255   def languages=(languages)
256     self[:languages] = languages.join(",")
257   end
258
259   def preferred_languages
260     @preferred_languages ||= Locale.list(languages)
261   end
262
263   def default_diary_language
264     diary_language_preference = preferences.find_by(:k => "diary.default_language")
265     if diary_language_preference
266       diary_language_preference.v
267     else
268       languages.find { |l| Language.exists?(:code => l) }
269     end
270   end
271
272   def default_diary_language=(language)
273     preference = preferences.find_or_create_by(:k => "diary.default_language")
274     preference.update!(:v => language)
275   end
276
277   def home_location?
278     home_lat && home_lon
279   end
280
281   def nearby(radius = Settings.nearby_radius, num = Settings.nearby_users)
282     if home_location?
283       gc = OSM::GreatCircle.new(home_lat, home_lon)
284       sql_for_area = QuadTile.sql_for_area(gc.bounds(radius), "home_")
285       sql_for_distance = gc.sql_for_distance("home_lat", "home_lon")
286       nearby = User.active.identifiable
287                    .where.not(:id => id)
288                    .where(sql_for_area)
289                    .where("#{sql_for_distance} <= ?", radius)
290                    .order(Arel.sql(sql_for_distance))
291                    .limit(num)
292     else
293       nearby = []
294     end
295     nearby
296   end
297
298   def distance(nearby_user)
299     OSM::GreatCircle.new(home_lat, home_lon).distance(nearby_user.home_lat, nearby_user.home_lon)
300   end
301
302   def follows?(user)
303     follows.exists?(:following => user)
304   end
305
306   ##
307   # returns true if a user is visible
308   def visible?
309     %w[pending active confirmed].include? status
310   end
311
312   ##
313   # returns true if a user is active
314   def active?
315     %w[active confirmed].include? status
316   end
317
318   ##
319   # returns true if the user has the moderator role, false otherwise
320   def moderator?
321     role? "moderator"
322   end
323
324   ##
325   # returns true if the user has the administrator role, false otherwise
326   def administrator?
327     role? "administrator"
328   end
329
330   ##
331   # returns true if the user has the importer role, false otherwise
332   def importer?
333     role? "importer"
334   end
335
336   ##
337   # returns true if the user has the requested role
338   def role?(role)
339     roles.any? { |r| r.role == role }
340   end
341
342   ##
343   # returns the first active block which would require users to view
344   # a message, or nil if there are none.
345   def blocked_on_view
346     blocks.active.detect(&:needs_view?)
347   end
348
349   ##
350   # revoke any authentication tokens
351   def revoke_authentication_tokens
352     access_tokens.not_expired.each(&:revoke)
353   end
354
355   ##
356   # remove personal data - leave the account but purge most personal data
357   def remove_personal_data
358     avatar.purge_later
359
360     self.display_name = "user_#{id}"
361     self.description = ""
362     self.home_lat = nil
363     self.home_lon = nil
364     self.email_valid = false
365     self.new_email = nil
366     self.auth_provider = nil
367     self.auth_uid = nil
368
369     save
370   end
371
372   ##
373   # return a spam score for a user
374   def spam_score
375     changeset_score = changesets.size * 50
376     trace_score = traces.size * 50
377     diary_entry_score = diary_entries.visible.inject(0) { |acc, elem| acc + elem.body.spam_score }
378     diary_comment_score = diary_comments.visible.inject(0) { |acc, elem| acc + elem.body.spam_score }
379     report_score = Report.where(:category => "spam", :issue => issues.with_status("open")).distinct.count(:user_id) * 20
380
381     score = description.spam_score / 4.0
382     score += diary_entries.visible.where("created_at > ?", 1.day.ago).count * 10
383     score += diary_entry_score / diary_entries.visible.length unless diary_entries.visible.empty?
384     score += diary_comment_score / diary_comments.visible.length unless diary_comments.visible.empty?
385     score += report_score
386     score -= changeset_score
387     score -= trace_score
388
389     score.to_i
390   end
391
392   ##
393   # perform a spam check on a user
394   def spam_check
395     suspend! if may_suspend? && spam_score > Settings.spam_threshold
396   end
397
398   ##
399   # return an oauth 2 access token for a specified application
400   def oauth_token(application_id)
401     application = Doorkeeper.config.application_model.find_by(:uid => application_id)
402
403     Doorkeeper.config.access_token_model.find_or_create_for(
404       :application => application,
405       :resource_owner => self,
406       :scopes => application.scopes
407     )
408   end
409
410   def fingerprint
411     digest = Digest::SHA256.new
412     digest.update(email)
413     digest.update(pass_crypt)
414     digest.hexdigest
415   end
416
417   def active_reports
418     issues
419       .with_status(:open)
420       .joins(:reports)
421       .where("reports.updated_at >= COALESCE(issues.resolved_at, '1970-01-01')")
422       .count
423   end
424
425   def max_messages_per_hour
426     account_age_in_seconds = Time.now.utc - created_at
427     account_age_in_hours = account_age_in_seconds / 3600
428     recent_messages = messages.where(:sent_on => (Time.now.utc - 3600)..).count
429     max_messages = account_age_in_hours.ceil + recent_messages - (active_reports * 10)
430     max_messages.clamp(0, Settings.max_messages_per_hour)
431   end
432
433   def max_follows_per_hour
434     account_age_in_seconds = Time.now.utc - created_at
435     account_age_in_hours = account_age_in_seconds / 3600
436     recent_follows = Follow.where(:following => self).where(:created_at => (Time.now.utc - 3600)..).count
437     max_follows = account_age_in_hours.ceil + recent_follows - (active_reports * 10)
438     max_follows.clamp(0, Settings.max_follows_per_hour)
439   end
440
441   def max_changeset_comments_per_hour
442     if moderator?
443       Settings.moderator_changeset_comments_per_hour
444     else
445       previous_comments = changeset_comments.limit(Settings.comments_to_max_changeset_comments).count
446       max_comments = previous_comments / Settings.comments_to_max_changeset_comments.to_f * Settings.max_changeset_comments_per_hour
447       max_comments = max_comments.floor.clamp(Settings.initial_changeset_comments_per_hour, Settings.max_changeset_comments_per_hour)
448       max_comments /= 2**active_reports
449       max_comments.floor.clamp(Settings.min_changeset_comments_per_hour, Settings.max_changeset_comments_per_hour)
450     end
451   end
452
453   def deletion_allowed_at
454     unless Settings.user_account_deletion_delay.nil?
455       last_changeset = changesets.reorder(:closed_at => :desc).first
456       return last_changeset.closed_at.utc + Settings.user_account_deletion_delay.hours if last_changeset
457     end
458     creation_time.utc
459   end
460
461   def deletion_allowed?
462     deletion_allowed_at <= Time.now.utc
463   end
464
465   ##
466   # check if this user has a gravatar and set the user pref is true
467   def gravatar_enable!
468     # code from example https://en.gravatar.com/site/implement/images/ruby/
469     return false if avatar.attached?
470
471     begin
472       hash = Digest::MD5.hexdigest(email.downcase)
473       url = "https://www.gravatar.com/avatar/#{hash}?d=404" # without d=404 we will always get an image back
474       response = OSM.http_client.get(URI.parse(url))
475       available = response.success?
476     rescue StandardError
477       available = false
478     end
479
480     oldsetting = image_use_gravatar
481     self.image_use_gravatar = available
482     oldsetting != image_use_gravatar
483   end
484
485   private
486
487   def encrypt_password
488     if pass_crypt_confirmation
489       self.pass_crypt, self.pass_salt = PasswordHash.create(pass_crypt)
490       self.pass_crypt_confirmation = nil
491     end
492   end
493
494   def update_tile
495     self.home_tile = QuadTile.tile_for_point(home_lat, home_lon) if home_location?
496   end
497 end