To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Tag: | Revision:

root / app / models / user.rb @ 1566:ac2e4a54a6a6

History | View | Annotate | Download (24.2 KB)

1 0:513646585e45 Chris
# Redmine - project management software
2 1494:e248c7af89ec Chris
# Copyright (C) 2006-2014  Jean-Philippe Lang
3 0:513646585e45 Chris
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8 909:cbb26bc654de Chris
#
9 0:513646585e45 Chris
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13 909:cbb26bc654de Chris
#
14 0:513646585e45 Chris
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17
18
require "digest/sha1"
19
20
class User < Principal
21 119:8661b858af72 Chris
  include Redmine::SafeAttributes
22 909:cbb26bc654de Chris
23
  # Different ways of displaying/sorting users
24 0:513646585e45 Chris
  USER_FORMATS = {
25 1115:433d4f72a19b Chris
    :firstname_lastname => {
26
        :string => '#{firstname} #{lastname}',
27
        :order => %w(firstname lastname id),
28
        :setting_order => 1
29
      },
30
    :firstname_lastinitial => {
31
        :string => '#{firstname} #{lastname.to_s.chars.first}.',
32
        :order => %w(firstname lastname id),
33
        :setting_order => 2
34
      },
35 1517:dffacf8a6908 Chris
    :firstinitial_lastname => {
36
        :string => '#{firstname.to_s.gsub(/(([[:alpha:]])[[:alpha:]]*\.?)/, \'\2.\')} #{lastname}',
37
        :order => %w(firstname lastname id),
38
        :setting_order => 2
39
      },
40 1115:433d4f72a19b Chris
    :firstname => {
41
        :string => '#{firstname}',
42
        :order => %w(firstname id),
43
        :setting_order => 3
44
      },
45
    :lastname_firstname => {
46
        :string => '#{lastname} #{firstname}',
47
        :order => %w(lastname firstname id),
48
        :setting_order => 4
49
      },
50
    :lastname_coma_firstname => {
51
        :string => '#{lastname}, #{firstname}',
52
        :order => %w(lastname firstname id),
53
        :setting_order => 5
54
      },
55
    :lastname => {
56
        :string => '#{lastname}',
57
        :order => %w(lastname id),
58
        :setting_order => 6
59
      },
60
    :username => {
61
        :string => '#{login}',
62
        :order => %w(login id),
63
        :setting_order => 7
64
      },
65 0:513646585e45 Chris
  }
66
67 37:94944d00e43c chris
  MAIL_NOTIFICATION_OPTIONS = [
68 119:8661b858af72 Chris
    ['all', :label_user_mail_option_all],
69
    ['selected', :label_user_mail_option_selected],
70
    ['only_my_events', :label_user_mail_option_only_my_events],
71
    ['only_assigned', :label_user_mail_option_only_assigned],
72
    ['only_owner', :label_user_mail_option_only_owner],
73
    ['none', :label_user_mail_option_none]
74
  ]
75 37:94944d00e43c chris
76 1517:dffacf8a6908 Chris
  has_and_belongs_to_many :groups,
77
                          :join_table   => "#{table_name_prefix}groups_users#{table_name_suffix}",
78
                          :after_add    => Proc.new {|user, group| group.user_added(user)},
79
                          :after_remove => Proc.new {|user, group| group.user_removed(user)}
80 0:513646585e45 Chris
  has_many :changesets, :dependent => :nullify
81
  has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
82 128:07fa8a8b56a8 Chris
  has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'"
83
  has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
84 0:513646585e45 Chris
  belongs_to :auth_source
85 909:cbb26bc654de Chris
86 1464:261b3d9a4903 Chris
  scope :logged, lambda { where("#{User.table_name}.status <> #{STATUS_ANONYMOUS}") }
87
  scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
88 909:cbb26bc654de Chris
89 55:bbb139d5ca95 luisf
  has_one :ssamr_user_detail, :dependent => :destroy, :class_name => 'SsamrUserDetail'
90 65:69ee2e406f71 luisf
  accepts_nested_attributes_for :ssamr_user_detail
91 403:b15397a5341c luis
92
  has_one :author
93 64:9d42bcda8cea luisf
94 0:513646585e45 Chris
  acts_as_customizable
95 909:cbb26bc654de Chris
96 1464:261b3d9a4903 Chris
  attr_accessor :password, :password_confirmation, :generate_password
97 0:513646585e45 Chris
  attr_accessor :last_before_login_on
98
  # Prevents unauthorized assignments
99 119:8661b858af72 Chris
  attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
100 1115:433d4f72a19b Chris
101
  LOGIN_LENGTH_LIMIT = 60
102
  MAIL_LENGTH_LIMIT = 60
103
104 0:513646585e45 Chris
  validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
105 1115:433d4f72a19b Chris
  validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
106
  validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false
107 1484:51364c0cd58f Chris
108 1464:261b3d9a4903 Chris
  # Login must contain letters, numbers, underscores only
109
  validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i
110 1115:433d4f72a19b Chris
  validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
111 0:513646585e45 Chris
  validates_length_of :firstname, :lastname, :maximum => 30
112 1464:261b3d9a4903 Chris
  validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :allow_blank => true
113 1115:433d4f72a19b Chris
  validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true
114 0:513646585e45 Chris
  validates_confirmation_of :password, :allow_nil => true
115 119:8661b858af72 Chris
  validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
116 909:cbb26bc654de Chris
  validate :validate_password_length
117 0:513646585e45 Chris
118 909:cbb26bc654de Chris
  before_create :set_mail_notification
119 1464:261b3d9a4903 Chris
  before_save   :generate_password_if_needed, :update_hashed_password
120 128:07fa8a8b56a8 Chris
  before_destroy :remove_references_before_destroy
121 1464:261b3d9a4903 Chris
  after_save :update_notified_project_ids
122 909:cbb26bc654de Chris
123 190:440c4f4bf2d6 luisf
  validates_acceptance_of :terms_and_conditions, :on => :create, :message => :must_accept_terms_and_conditions
124
125 1115:433d4f72a19b Chris
  scope :in_group, lambda {|group|
126 441:cbce1fd3b1b7 Chris
    group_id = group.is_a?(Group) ? group.id : group.to_i
127 1115:433d4f72a19b Chris
    where("#{User.table_name}.id IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id)
128 441:cbce1fd3b1b7 Chris
  }
129 1115:433d4f72a19b Chris
  scope :not_in_group, lambda {|group|
130 441:cbce1fd3b1b7 Chris
    group_id = group.is_a?(Group) ? group.id : group.to_i
131 1115:433d4f72a19b Chris
    where("#{User.table_name}.id NOT IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id)
132 441:cbce1fd3b1b7 Chris
  }
133 1464:261b3d9a4903 Chris
  scope :sorted, lambda { order(*User.fields_for_order_statement)}
134 909:cbb26bc654de Chris
135
  def set_mail_notification
136 37:94944d00e43c chris
    self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
137 0:513646585e45 Chris
    true
138
  end
139 909:cbb26bc654de Chris
140
  def update_hashed_password
141 0:513646585e45 Chris
    # update hashed_password if password was set
142 245:051f544170fe Chris
    if self.password && self.auth_source_id.blank?
143
      salt_password(password)
144
    end
145 0:513646585e45 Chris
  end
146 909:cbb26bc654de Chris
147 1464:261b3d9a4903 Chris
  alias :base_reload :reload
148 0:513646585e45 Chris
  def reload(*args)
149
    @name = nil
150 441:cbce1fd3b1b7 Chris
    @projects_by_role = nil
151 1464:261b3d9a4903 Chris
    @membership_by_project_id = nil
152
    @notified_projects_ids = nil
153
    @notified_projects_ids_changed = false
154
    @builtin_role = nil
155
    base_reload(*args)
156 0:513646585e45 Chris
  end
157 909:cbb26bc654de Chris
158 1:cca12e1c1fd4 Chris
  def mail=(arg)
159
    write_attribute(:mail, arg.to_s.strip)
160
  end
161 909:cbb26bc654de Chris
162 59:7ff14a13f48a luisf
  def description=(arg)
163
    write_attribute(:description, arg.to_s.strip)
164
  end
165
166 0:513646585e45 Chris
  def identity_url=(url)
167
    if url.blank?
168
      write_attribute(:identity_url, '')
169
    else
170
      begin
171
        write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
172
      rescue OpenIdAuthentication::InvalidOpenId
173 1464:261b3d9a4903 Chris
        # Invalid url, don't save
174 0:513646585e45 Chris
      end
175
    end
176
    self.read_attribute(:identity_url)
177
  end
178 909:cbb26bc654de Chris
179 0:513646585e45 Chris
  # Returns the user that matches provided login and password, or nil
180 1464:261b3d9a4903 Chris
  def self.try_to_login(login, password, active_only=true)
181 1115:433d4f72a19b Chris
    login = login.to_s
182
    password = password.to_s
183
184 1464:261b3d9a4903 Chris
    # Make sure no one can sign in with an empty login or password
185
    return nil if login.empty? || password.empty?
186 0:513646585e45 Chris
    user = find_by_login(login)
187
    if user
188
      # user is already in local database
189 1464:261b3d9a4903 Chris
      return nil unless user.check_password?(password)
190
      return nil if !user.active? && active_only
191 0:513646585e45 Chris
    else
192
      # user is not yet registered, try to authenticate with available sources
193
      attrs = AuthSource.authenticate(login, password)
194
      if attrs
195
        user = new(attrs)
196
        user.login = login
197
        user.language = Setting.default_language
198
        if user.save
199
          user.reload
200
          logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
201
        end
202
      end
203 909:cbb26bc654de Chris
    end
204 1464:261b3d9a4903 Chris
    user.update_column(:last_login_on, Time.now) if user && !user.new_record? && user.active?
205 0:513646585e45 Chris
    user
206
  rescue => text
207
    raise text
208
  end
209 909:cbb26bc654de Chris
210 0:513646585e45 Chris
  # Returns the user who matches the given autologin +key+ or nil
211
  def self.try_to_autologin(key)
212 1464:261b3d9a4903 Chris
    user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
213
    if user
214
      user.update_column(:last_login_on, Time.now)
215
      user
216 0:513646585e45 Chris
    end
217
  end
218 909:cbb26bc654de Chris
219
  def self.name_formatter(formatter = nil)
220
    USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
221
  end
222
223
  # Returns an array of fields names than can be used to make an order statement for users
224
  # according to how user names are displayed
225
  # Examples:
226
  #
227
  #   User.fields_for_order_statement              => ['users.login', 'users.id']
228
  #   User.fields_for_order_statement('authors')   => ['authors.login', 'authors.id']
229
  def self.fields_for_order_statement(table=nil)
230
    table ||= table_name
231
    name_formatter[:order].map {|field| "#{table}.#{field}"}
232
  end
233
234 0:513646585e45 Chris
  # Return user's full name for display
235
  def name(formatter = nil)
236 909:cbb26bc654de Chris
    f = self.class.name_formatter(formatter)
237 0:513646585e45 Chris
    if formatter
238 909:cbb26bc654de Chris
      eval('"' + f[:string] + '"')
239 0:513646585e45 Chris
    else
240 909:cbb26bc654de Chris
      @name ||= eval('"' + f[:string] + '"')
241 0:513646585e45 Chris
    end
242
  end
243 909:cbb26bc654de Chris
244 0:513646585e45 Chris
  def active?
245
    self.status == STATUS_ACTIVE
246
  end
247
248
  def registered?
249
    self.status == STATUS_REGISTERED
250
  end
251 909:cbb26bc654de Chris
252 0:513646585e45 Chris
  def locked?
253
    self.status == STATUS_LOCKED
254
  end
255
256 14:1d32c0a0efbf Chris
  def activate
257
    self.status = STATUS_ACTIVE
258
  end
259
260
  def register
261
    self.status = STATUS_REGISTERED
262
  end
263
264
  def lock
265
    self.status = STATUS_LOCKED
266
  end
267
268
  def activate!
269
    update_attribute(:status, STATUS_ACTIVE)
270
  end
271
272
  def register!
273
    update_attribute(:status, STATUS_REGISTERED)
274
  end
275
276
  def lock!
277
    update_attribute(:status, STATUS_LOCKED)
278
  end
279
280 245:051f544170fe Chris
  # Returns true if +clear_password+ is the correct user's password, otherwise false
281 0:513646585e45 Chris
  def check_password?(clear_password)
282
    if auth_source_id.present?
283
      auth_source.authenticate(self.login, clear_password)
284
    else
285 245:051f544170fe Chris
      User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
286 0:513646585e45 Chris
    end
287
  end
288 909:cbb26bc654de Chris
289 245:051f544170fe Chris
  # Generates a random salt and computes hashed_password for +clear_password+
290
  # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
291
  def salt_password(clear_password)
292
    self.salt = User.generate_salt
293
    self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
294
  end
295 0:513646585e45 Chris
296
  # Does the backend storage allow this user to change their password?
297
  def change_password_allowed?
298 1115:433d4f72a19b Chris
    return true if auth_source.nil?
299 0:513646585e45 Chris
    return auth_source.allow_password_changes?
300
  end
301
302 1464:261b3d9a4903 Chris
  def must_change_password?
303
    must_change_passwd? && change_password_allowed?
304
  end
305
306
  def generate_password?
307
    generate_password == '1' || generate_password == true
308
  end
309
310
  # Generate and set a random password on given length
311
  def random_password(length=40)
312 0:513646585e45 Chris
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
313 1464:261b3d9a4903 Chris
    chars -= %w(0 O 1 l)
314 0:513646585e45 Chris
    password = ''
315 1464:261b3d9a4903 Chris
    length.times {|i| password << chars[SecureRandom.random_number(chars.size)] }
316 0:513646585e45 Chris
    self.password = password
317
    self.password_confirmation = password
318
    self
319
  end
320 909:cbb26bc654de Chris
321 0:513646585e45 Chris
  def pref
322
    self.preference ||= UserPreference.new(:user => self)
323
  end
324 909:cbb26bc654de Chris
325 0:513646585e45 Chris
  def time_zone
326
    @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
327
  end
328 909:cbb26bc654de Chris
329 1517:dffacf8a6908 Chris
  def force_default_language?
330
    Setting.force_default_language_for_loggedin?
331
  end
332
333
  def language
334
    if force_default_language?
335
      Setting.default_language
336
    else
337
      super
338
    end
339
  end
340
341 0:513646585e45 Chris
  def wants_comments_in_reverse_order?
342
    self.pref[:comments_sorting] == 'desc'
343
  end
344 909:cbb26bc654de Chris
345 0:513646585e45 Chris
  # Return user's RSS key (a 40 chars long string), used to access feeds
346
  def rss_key
347 1115:433d4f72a19b Chris
    if rss_token.nil?
348
      create_rss_token(:action => 'feeds')
349
    end
350
    rss_token.value
351 0:513646585e45 Chris
  end
352
353
  # Return user's API key (a 40 chars long string), used to access the API
354
  def api_key
355 1115:433d4f72a19b Chris
    if api_token.nil?
356
      create_api_token(:action => 'api')
357
    end
358
    api_token.value
359 0:513646585e45 Chris
  end
360 909:cbb26bc654de Chris
361 0:513646585e45 Chris
  # Return an array of project ids for which the user has explicitly turned mail notifications on
362
  def notified_projects_ids
363
    @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
364
  end
365 909:cbb26bc654de Chris
366 0:513646585e45 Chris
  def notified_project_ids=(ids)
367 1464:261b3d9a4903 Chris
    @notified_projects_ids_changed = true
368
    @notified_projects_ids = ids
369 0:513646585e45 Chris
  end
370
371 1464:261b3d9a4903 Chris
  # Updates per project notifications (after_save callback)
372
  def update_notified_project_ids
373
    if @notified_projects_ids_changed
374
      ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
375
      members.update_all(:mail_notification => false)
376
      members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
377
    end
378
  end
379
  private :update_notified_project_ids
380
381 128:07fa8a8b56a8 Chris
  def valid_notification_options
382
    self.class.valid_notification_options(self)
383
  end
384
385 37:94944d00e43c chris
  # Only users that belong to more than 1 project can select projects for which they are notified
386 128:07fa8a8b56a8 Chris
  def self.valid_notification_options(user=nil)
387 37:94944d00e43c chris
    # Note that @user.membership.size would fail since AR ignores
388
    # :include association option when doing a count
389 128:07fa8a8b56a8 Chris
    if user.nil? || user.memberships.length < 1
390
      MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
391 37:94944d00e43c chris
    else
392
      MAIL_NOTIFICATION_OPTIONS
393
    end
394
  end
395
396 0:513646585e45 Chris
  # Find a user account by matching the exact login and then a case-insensitive
397
  # version.  Exact matches will be given priority.
398
  def self.find_by_login(login)
399 1517:dffacf8a6908 Chris
    login = Redmine::CodesetUtil.replace_invalid_utf8(login.to_s)
400 1464:261b3d9a4903 Chris
    if login.present?
401
      # First look for an exact match
402 1517:dffacf8a6908 Chris
      user = where(:login => login).detect {|u| u.login == login}
403 1464:261b3d9a4903 Chris
      unless user
404
        # Fail over to case-insensitive if none was found
405
        user = where("LOWER(login) = ?", login.downcase).first
406
      end
407
      user
408 1115:433d4f72a19b Chris
    end
409 0:513646585e45 Chris
  end
410
411
  def self.find_by_rss_key(key)
412 1464:261b3d9a4903 Chris
    Token.find_active_user('feeds', key)
413 0:513646585e45 Chris
  end
414 909:cbb26bc654de Chris
415 0:513646585e45 Chris
  def self.find_by_api_key(key)
416 1464:261b3d9a4903 Chris
    Token.find_active_user('api', key)
417 0:513646585e45 Chris
  end
418 909:cbb26bc654de Chris
419 0:513646585e45 Chris
  # Makes find_by_mail case-insensitive
420
  def self.find_by_mail(mail)
421 1115:433d4f72a19b Chris
    where("LOWER(mail) = ?", mail.to_s.downcase).first
422 0:513646585e45 Chris
  end
423 909:cbb26bc654de Chris
424 929:5f33065ddc4b Chris
  # Returns true if the default admin account can no longer be used
425
  def self.default_admin_account_changed?
426
    !User.active.find_by_login("admin").try(:check_password?, "admin")
427
  end
428
429 0:513646585e45 Chris
  def to_s
430
    name
431
  end
432 909:cbb26bc654de Chris
433 1115:433d4f72a19b Chris
  CSS_CLASS_BY_STATUS = {
434
    STATUS_ANONYMOUS  => 'anon',
435
    STATUS_ACTIVE     => 'active',
436
    STATUS_REGISTERED => 'registered',
437
    STATUS_LOCKED     => 'locked'
438
  }
439
440
  def css_classes
441
    "user #{CSS_CLASS_BY_STATUS[status]}"
442
  end
443
444 0:513646585e45 Chris
  # Returns the current day according to user's time zone
445
  def today
446
    if time_zone.nil?
447
      Date.today
448
    else
449
      Time.now.in_time_zone(time_zone).to_date
450
    end
451
  end
452 909:cbb26bc654de Chris
453 1115:433d4f72a19b Chris
  # Returns the day of +time+ according to user's time zone
454
  def time_to_date(time)
455
    if time_zone.nil?
456
      time.to_date
457
    else
458
      time.in_time_zone(time_zone).to_date
459
    end
460
  end
461
462 0:513646585e45 Chris
  def logged?
463
    true
464
  end
465 909:cbb26bc654de Chris
466 0:513646585e45 Chris
  def anonymous?
467
    !logged?
468
  end
469 909:cbb26bc654de Chris
470 1464:261b3d9a4903 Chris
  # Returns user's membership for the given project
471
  # or nil if the user is not a member of project
472
  def membership(project)
473
    project_id = project.is_a?(Project) ? project.id : project
474
475
    @membership_by_project_id ||= Hash.new {|h, project_id|
476
      h[project_id] = memberships.where(:project_id => project_id).first
477
    }
478
    @membership_by_project_id[project_id]
479
  end
480
481
  # Returns the user's bult-in role
482
  def builtin_role
483
    @builtin_role ||= Role.non_member
484
  end
485
486 0:513646585e45 Chris
  # Return user's roles for project
487
  def roles_for_project(project)
488
    roles = []
489
    # No role on archived projects
490 1115:433d4f72a19b Chris
    return roles if project.nil? || project.archived?
491 1464:261b3d9a4903 Chris
    if membership = membership(project)
492
      roles = membership.roles
493 0:513646585e45 Chris
    else
494 1464:261b3d9a4903 Chris
      roles << builtin_role
495 0:513646585e45 Chris
    end
496
    roles
497
  end
498 909:cbb26bc654de Chris
499 0:513646585e45 Chris
  # Return true if the user is a member of project
500
  def member_of?(project)
501 1464:261b3d9a4903 Chris
    projects.to_a.include?(project)
502 0:513646585e45 Chris
  end
503 909:cbb26bc654de Chris
504 441:cbce1fd3b1b7 Chris
  # Returns a hash of user's projects grouped by roles
505
  def projects_by_role
506
    return @projects_by_role if @projects_by_role
507 909:cbb26bc654de Chris
508 1115:433d4f72a19b Chris
    @projects_by_role = Hash.new([])
509 441:cbce1fd3b1b7 Chris
    memberships.each do |membership|
510 1115:433d4f72a19b Chris
      if membership.project
511
        membership.roles.each do |role|
512
          @projects_by_role[role] = [] unless @projects_by_role.key?(role)
513
          @projects_by_role[role] << membership.project
514
        end
515 441:cbce1fd3b1b7 Chris
      end
516
    end
517
    @projects_by_role.each do |role, projects|
518
      projects.uniq!
519
    end
520 909:cbb26bc654de Chris
521 441:cbce1fd3b1b7 Chris
    @projects_by_role
522
  end
523 909:cbb26bc654de Chris
524
  # Returns true if user is arg or belongs to arg
525
  def is_or_belongs_to?(arg)
526
    if arg.is_a?(User)
527
      self == arg
528
    elsif arg.is_a?(Group)
529
      arg.users.include?(self)
530
    else
531
      false
532
    end
533
  end
534
535 37:94944d00e43c chris
  # Return true if the user is allowed to do the specified action on a specific context
536
  # Action can be:
537 0:513646585e45 Chris
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
538
  # * a permission Symbol (eg. :edit_project)
539 37:94944d00e43c chris
  # Context can be:
540
  # * a project : returns true if user is allowed to do the specified action on this project
541 441:cbce1fd3b1b7 Chris
  # * an array of projects : returns true if user is allowed on every project
542 909:cbb26bc654de Chris
  # * nil with options[:global] set : check if user has at least one role allowed for this action,
543 37:94944d00e43c chris
  #   or falls back to Non Member / Anonymous permissions depending if the user is logged
544 441:cbce1fd3b1b7 Chris
  def allowed_to?(action, context, options={}, &block)
545 37:94944d00e43c chris
    if context && context.is_a?(Project)
546
      return false unless context.allows_to?(action)
547 0:513646585e45 Chris
      # Admin users are authorized for anything else
548
      return true if admin?
549 909:cbb26bc654de Chris
550 37:94944d00e43c chris
      roles = roles_for_project(context)
551 0:513646585e45 Chris
      return false unless roles
552 1115:433d4f72a19b Chris
      roles.any? {|role|
553 441:cbce1fd3b1b7 Chris
        (context.is_public? || role.member?) &&
554
        role.allowed_to?(action) &&
555
        (block_given? ? yield(role, self) : true)
556
      }
557 37:94944d00e43c chris
    elsif context && context.is_a?(Array)
558 1115:433d4f72a19b Chris
      if context.empty?
559
        false
560
      else
561
        # Authorize if user is authorized on every element of the array
562
        context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
563 37:94944d00e43c chris
      end
564 0:513646585e45 Chris
    elsif options[:global]
565
      # Admin users are always authorized
566
      return true if admin?
567 909:cbb26bc654de Chris
568 0:513646585e45 Chris
      # authorize if user has at least one role that has this permission
569
      roles = memberships.collect {|m| m.roles}.flatten.uniq
570 441:cbce1fd3b1b7 Chris
      roles << (self.logged? ? Role.non_member : Role.anonymous)
571 1115:433d4f72a19b Chris
      roles.any? {|role|
572 441:cbce1fd3b1b7 Chris
        role.allowed_to?(action) &&
573
        (block_given? ? yield(role, self) : true)
574
      }
575 0:513646585e45 Chris
    else
576
      false
577
    end
578
  end
579 22:40f7cfd4df19 chris
580
  # Is the user allowed to do the specified action on any project?
581
  # See allowed_to? for the actions and valid options.
582 441:cbce1fd3b1b7 Chris
  def allowed_to_globally?(action, options, &block)
583
    allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
584 22:40f7cfd4df19 chris
  end
585 119:8661b858af72 Chris
586 1464:261b3d9a4903 Chris
  # Returns true if the user is allowed to delete the user's own account
587 1115:433d4f72a19b Chris
  def own_account_deletable?
588
    Setting.unsubscribe? &&
589
      (!admin? || User.active.where("admin = ? AND id <> ?", true, id).exists?)
590
  end
591
592 119:8661b858af72 Chris
  safe_attributes 'login',
593
    'firstname',
594
    'lastname',
595
    'mail',
596
    'mail_notification',
597 1464:261b3d9a4903 Chris
    'notified_project_ids',
598 119:8661b858af72 Chris
    'language',
599
    'custom_field_values',
600
    'custom_fields',
601
    'identity_url'
602 909:cbb26bc654de Chris
603 119:8661b858af72 Chris
  safe_attributes 'status',
604
    'auth_source_id',
605 1464:261b3d9a4903 Chris
    'generate_password',
606
    'must_change_passwd',
607 119:8661b858af72 Chris
    :if => lambda {|user, current_user| current_user.admin?}
608 909:cbb26bc654de Chris
609 119:8661b858af72 Chris
  safe_attributes 'group_ids',
610
    :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
611 909:cbb26bc654de Chris
612 37:94944d00e43c chris
  # Utility method to help check if a user should be notified about an
613
  # event.
614
  #
615
  # TODO: only supports Issue events currently
616
  def notify_about?(object)
617 1464:261b3d9a4903 Chris
    if mail_notification == 'all'
618 37:94944d00e43c chris
      true
619 1464:261b3d9a4903 Chris
    elsif mail_notification.blank? || mail_notification == 'none'
620
      false
621
    else
622
      case object
623
      when Issue
624
        case mail_notification
625
        when 'selected', 'only_my_events'
626
          # user receives notifications for created/assigned issues on unselected projects
627
          object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
628
        when 'only_assigned'
629
          is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
630
        when 'only_owner'
631
          object.author == self
632
        end
633
      when News
634
        # always send to project members except when mail_notification is set to 'none'
635 210:0579821a129a Chris
        true
636
      end
637 37:94944d00e43c chris
    end
638
  end
639 909:cbb26bc654de Chris
640 0:513646585e45 Chris
  def self.current=(user)
641 1464:261b3d9a4903 Chris
    Thread.current[:current_user] = user
642 0:513646585e45 Chris
  end
643 909:cbb26bc654de Chris
644 0:513646585e45 Chris
  def self.current
645 1464:261b3d9a4903 Chris
    Thread.current[:current_user] ||= User.anonymous
646 0:513646585e45 Chris
  end
647 909:cbb26bc654de Chris
648 0:513646585e45 Chris
  # Returns the anonymous user.  If the anonymous user does not exist, it is created.  There can be only
649
  # one anonymous user per database.
650
  def self.anonymous
651 1115:433d4f72a19b Chris
    anonymous_user = AnonymousUser.first
652 0:513646585e45 Chris
    if anonymous_user.nil?
653
      anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
654
      raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
655
    end
656
    anonymous_user
657
  end
658 245:051f544170fe Chris
659
  # Salts all existing unsalted passwords
660
  # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
661
  # This method is used in the SaltPasswords migration and is to be kept as is
662
  def self.salt_unsalted_passwords!
663
    transaction do
664 1115:433d4f72a19b Chris
      User.where("salt IS NULL OR salt = ''").find_each do |user|
665 245:051f544170fe Chris
        next if user.hashed_password.blank?
666
        salt = User.generate_salt
667
        hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
668 1115:433d4f72a19b Chris
        User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
669 245:051f544170fe Chris
      end
670
    end
671
  end
672 909:cbb26bc654de Chris
673 0:513646585e45 Chris
  protected
674 909:cbb26bc654de Chris
675
  def validate_password_length
676 1464:261b3d9a4903 Chris
    return if password.blank? && generate_password?
677 0:513646585e45 Chris
    # Password length validation based on setting
678
    if !password.nil? && password.size < Setting.password_min_length.to_i
679
      errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
680
    end
681
  end
682 909:cbb26bc654de Chris
683 0:513646585e45 Chris
  private
684 909:cbb26bc654de Chris
685 1464:261b3d9a4903 Chris
  def generate_password_if_needed
686
    if generate_password? && auth_source.nil?
687
      length = [Setting.password_min_length.to_i + 2, 10].max
688
      random_password(length)
689
    end
690
  end
691
692 128:07fa8a8b56a8 Chris
  # Removes references that are not handled by associations
693
  # Things that are not deleted are reassociated with the anonymous user
694
  def remove_references_before_destroy
695
    return if self.id.nil?
696 909:cbb26bc654de Chris
697 128:07fa8a8b56a8 Chris
    substitute = User.anonymous
698 1517:dffacf8a6908 Chris
    Attachment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
699
    Comment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
700
    Issue.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
701
    Issue.where(['assigned_to_id = ?', id]).update_all('assigned_to_id = NULL')
702
    Journal.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
703
    JournalDetail.
704
      where(["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]).
705
      update_all(['old_value = ?', substitute.id.to_s])
706
    JournalDetail.
707
      where(["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]).
708
      update_all(['value = ?', substitute.id.to_s])
709
    Message.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
710
    News.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
711 128:07fa8a8b56a8 Chris
    # Remove private queries and keep public ones
712 1464:261b3d9a4903 Chris
    ::Query.delete_all ['user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE]
713 1517:dffacf8a6908 Chris
    ::Query.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
714
    TimeEntry.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
715 128:07fa8a8b56a8 Chris
    Token.delete_all ['user_id = ?', id]
716
    Watcher.delete_all ['user_id = ?', id]
717 1517:dffacf8a6908 Chris
    WikiContent.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
718
    WikiContent::Version.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
719 128:07fa8a8b56a8 Chris
  end
720 909:cbb26bc654de Chris
721 0:513646585e45 Chris
  # Return password digest
722
  def self.hash_password(clear_password)
723
    Digest::SHA1.hexdigest(clear_password || "")
724
  end
725 909:cbb26bc654de Chris
726 245:051f544170fe Chris
  # Returns a 128bits random salt as a hex string (32 chars long)
727
  def self.generate_salt
728 1115:433d4f72a19b Chris
    Redmine::Utils.random_hex(16)
729 245:051f544170fe Chris
  end
730 909:cbb26bc654de Chris
731 0:513646585e45 Chris
end
732
733
class AnonymousUser < User
734 1115:433d4f72a19b Chris
  validate :validate_anonymous_uniqueness, :on => :create
735 909:cbb26bc654de Chris
736 1115:433d4f72a19b Chris
  def validate_anonymous_uniqueness
737 0:513646585e45 Chris
    # There should be only one AnonymousUser in the database
738 1464:261b3d9a4903 Chris
    errors.add :base, 'An anonymous user already exists.' if AnonymousUser.exists?
739 0:513646585e45 Chris
  end
740 909:cbb26bc654de Chris
741 0:513646585e45 Chris
  def available_custom_fields
742
    []
743
  end
744 909:cbb26bc654de Chris
745 0:513646585e45 Chris
  # Overrides a few properties
746
  def logged?; false end
747
  def admin; false end
748
  def name(*args); I18n.t(:label_user_anonymous) end
749
  def mail; nil end
750
  def time_zone; nil end
751
  def rss_key; nil end
752 909:cbb26bc654de Chris
753 1115:433d4f72a19b Chris
  def pref
754
    UserPreference.new(:user => self)
755
  end
756
757 1464:261b3d9a4903 Chris
  # Returns the user's bult-in role
758
  def builtin_role
759
    @builtin_role ||= Role.anonymous
760
  end
761
762
  def membership(*args)
763
    nil
764
  end
765
766
  def member_of?(*args)
767
    false
768
  end
769
770 128:07fa8a8b56a8 Chris
  # Anonymous user can not be destroyed
771
  def destroy
772
    false
773
  end
774 0:513646585e45 Chris
end