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 @ 1298:4f746d8966dd

History | View | Annotate | Download (22.5 KB)

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