]> git.openstreetmap.org Git - rails.git/blob - app/models/user.rb
Convert OpenID authentication to generic third party authentication
[rails.git] / app / models / user.rb
1 class User < ActiveRecord::Base
2   require "xml/libxml"
3
4   has_many :traces, -> { where(:visible => true) }
5   has_many :diary_entries, -> { order(:created_at => :desc) }
6   has_many :diary_comments, -> { order(:created_at => :desc) }
7   has_many :messages, -> { where(:to_user_visible => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :foreign_key => :to_user_id
8   has_many :new_messages, -> { where(:to_user_visible => true, :message_read => false).order(:sent_on => :desc) }, :class_name => "Message", :foreign_key => :to_user_id
9   has_many :sent_messages, -> { where(:from_user_visible => true).order(:sent_on => :desc).preload(:sender, :recipient) }, :class_name => "Message", :foreign_key => :from_user_id
10   has_many :friends, -> { joins(:befriendee).where(:users => { :status => %w(active confirmed) }) }
11   has_many :friend_users, :through => :friends, :source => :befriendee
12   has_many :tokens, :class_name => "UserToken"
13   has_many :preferences, :class_name => "UserPreference"
14   has_many :changesets, -> { order(:created_at => :desc) }
15   has_many :changeset_comments, :foreign_key =>  :author_id
16   has_and_belongs_to_many :changeset_subscriptions, :class_name => "Changeset", :join_table => "changesets_subscribers", :foreign_key => "subscriber_id"
17   has_many :note_comments, :foreign_key => :author_id
18   has_many :notes, :through => :note_comments
19
20   has_many :client_applications
21   has_many :oauth_tokens, -> { order(:authorized_at => :desc).preload(:client_application) }, :class_name => "OauthToken"
22
23   has_many :blocks, :class_name => "UserBlock"
24   has_many :blocks_created, :class_name => "UserBlock", :foreign_key => :creator_id
25   has_many :blocks_revoked, :class_name => "UserBlock", :foreign_key => :revoker_id
26
27   has_many :roles, :class_name => "UserRole"
28
29   scope :visible, -> { where(:status => %w(pending active confirmed)) }
30   scope :active, -> { where(:status => %w(active confirmed)) }
31   scope :identifiable, -> { where(:data_public => true) }
32
33   has_attached_file :image,
34                     :default_url => "/assets/:class/:attachment/:style.png",
35                     :styles => { :large => "100x100>", :small => "50x50>" }
36
37   validates_presence_of :email, :display_name
38   validates_confirmation_of :email # , :message => ' addresses must match'
39   validates_confirmation_of :pass_crypt # , :message => ' must match the confirmation password'
40   validates_uniqueness_of :display_name, :allow_nil => true, :case_sensitive => false, :if => proc { |u| u.display_name_changed? }
41   validates_uniqueness_of :email, :case_sensitive => false, :if => proc { |u| u.email_changed? }
42   validates_length_of :pass_crypt, :within => 8..255
43   validates_length_of :display_name, :within => 3..255, :allow_nil => true
44   validates_email_format_of :email, :if => proc { |u| u.email_changed? }
45   validates_email_format_of :new_email, :allow_blank => true, :if => proc { |u| u.new_email_changed? }
46   validates_format_of :display_name, :with => /\A[^\x00-\x1f\x7f\ufffe\uffff\/;.,?%#]*\z/, :if => proc { |u| u.display_name_changed? }
47   validates_format_of :display_name, :with => /\A\S/, :message => "has leading whitespace", :if => proc { |u| u.display_name_changed? }
48   validates_format_of :display_name, :with => /\S\z/, :message => "has trailing whitespace", :if => proc { |u| u.display_name_changed? }
49   validates_exclusion_of :display_name, :in => %w(new terms save confirm confirm-email go_public reset-password forgot-password suspended)
50   validates_numericality_of :home_lat, :allow_nil => true
51   validates_numericality_of :home_lon, :allow_nil => true
52   validates_numericality_of :home_zoom, :only_integer => true, :allow_nil => true
53   validates_inclusion_of :preferred_editor, :in => Editors::ALL_EDITORS, :allow_nil => true
54   validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
55
56   after_initialize :set_defaults
57   before_save :encrypt_password
58   after_save :spam_check
59
60   def self.authenticate(options)
61     if options[:username] && options[:password]
62       user = where("email = ? OR display_name = ?", options[:username], options[:username]).first
63
64       if user.nil?
65         users = where("LOWER(email) = LOWER(?) OR LOWER(display_name) = LOWER(?)", options[:username], options[:username])
66
67         user = users.first if users.count == 1
68       end
69
70       if user && PasswordHash.check(user.pass_crypt, user.pass_salt, options[:password])
71         if PasswordHash.upgrade?(user.pass_crypt, user.pass_salt)
72           user.pass_crypt, user.pass_salt = PasswordHash.create(options[:password])
73           user.save
74         end
75       else
76         user = nil
77       end
78     elsif options[:token]
79       token = UserToken.find_by_token(options[:token])
80       user = token.user if token
81     end
82
83     if user &&
84        (user.status == "deleted" ||
85          (user.status == "pending" && !options[:pending]) ||
86          (user.status == "suspended" && !options[:suspended]))
87       user = nil
88     end
89
90     token.update_column(:expiry, 1.week.from_now) if token && user
91
92     user
93   end
94
95   def to_xml
96     doc = OSM::API.new.get_xml_doc
97     doc.root << to_xml_node
98     doc
99   end
100
101   def to_xml_node
102     el1 = XML::Node.new "user"
103     el1["display_name"] = display_name.to_s
104     el1["account_created"] = creation_time.xmlschema
105     if home_lat && home_lon
106       home = XML::Node.new "home"
107       home["lat"] = home_lat.to_s
108       home["lon"] = home_lon.to_s
109       home["zoom"] = home_zoom.to_s
110       el1 << home
111     end
112     el1
113   end
114
115   def description
116     RichText.new(read_attribute(:description_format), read_attribute(:description))
117   end
118
119   def languages
120     attribute_present?(:languages) ? read_attribute(:languages).split(/ *, */) : []
121   end
122
123   def languages=(languages)
124     write_attribute(:languages, languages.join(","))
125   end
126
127   def preferred_language
128     languages.find { |l| Language.exists?(:code => l) }
129   end
130
131   def preferred_language_from(array)
132     (languages & array.collect(&:to_s)).first
133   end
134
135   def nearby(radius = NEARBY_RADIUS, num = NEARBY_USERS)
136     if home_lon && home_lat
137       gc = OSM::GreatCircle.new(home_lat, home_lon)
138       sql_for_distance = gc.sql_for_distance("home_lat", "home_lon")
139       nearby = User.where("id != ? AND status IN (\'active\', \'confirmed\') AND data_public = ? AND #{sql_for_distance} <= ?", id, true, radius).order(sql_for_distance).limit(num)
140     else
141       nearby = []
142     end
143     nearby
144   end
145
146   def distance(nearby_user)
147     OSM::GreatCircle.new(home_lat, home_lon).distance(nearby_user.home_lat, nearby_user.home_lon)
148   end
149
150   def is_friends_with?(new_friend)
151     friends.where(:friend_user_id => new_friend.id).exists?
152   end
153
154   ##
155   # returns true if a user is visible
156   def visible?
157     %w(pending active confirmed).include? status
158   end
159
160   ##
161   # returns true if a user is active
162   def active?
163     %w(active confirmed).include? status
164   end
165
166   ##
167   # returns true if the user has the moderator role, false otherwise
168   def moderator?
169     has_role? "moderator"
170   end
171
172   ##
173   # returns true if the user has the administrator role, false otherwise
174   def administrator?
175     has_role? "administrator"
176   end
177
178   ##
179   # returns true if the user has the requested role
180   def has_role?(role)
181     roles.any? { |r| r.role == role }
182   end
183
184   ##
185   # returns the first active block which would require users to view
186   # a message, or nil if there are none.
187   def blocked_on_view
188     blocks.active.detect(&:needs_view?)
189   end
190
191   ##
192   # delete a user - leave the account but purge most personal data
193   def delete
194     self.display_name = "user_#{id}"
195     self.description = ""
196     self.home_lat = nil
197     self.home_lon = nil
198     self.image = nil
199     self.email_valid = false
200     self.new_email = nil
201     self.auth_provider = nil
202     self.auth_uid = nil
203     self.status = "deleted"
204     save
205   end
206
207   ##
208   # return a spam score for a user
209   def spam_score
210     changeset_score = changesets.size * 50
211     trace_score = traces.size * 50
212     diary_entry_score = diary_entries.inject(0) { |a, e| a + e.body.spam_score }
213     diary_comment_score = diary_comments.inject(0) { |a, e| a + e.body.spam_score }
214
215     score = description.spam_score / 4.0
216     score += diary_entries.where("created_at > ?", 1.day.ago).count * 10
217     score += diary_entry_score / diary_entries.length if diary_entries.length > 0
218     score += diary_comment_score / diary_comments.length if diary_comments.length > 0
219     score -= changeset_score
220     score -= trace_score
221
222     score.to_i
223   end
224
225   ##
226   # perform a spam check on a user
227   def spam_check
228     if status == "active" && spam_score > SPAM_THRESHOLD
229       update_column(:status, "suspended")
230     end
231   end
232
233   ##
234   # return an oauth access token for a specified application
235   def access_token(application_key)
236     ClientApplication.find_by_key(application_key).access_token_for_user(self)
237   end
238
239   private
240
241   def set_defaults
242     self.creation_time = Time.now.getutc unless self.attribute_present?(:creation_time)
243   end
244
245   def encrypt_password
246     if pass_crypt_confirmation
247       self.pass_crypt, self.pass_salt = PasswordHash.create(pass_crypt)
248       self.pass_crypt_confirmation = nil
249     end
250   end
251 end