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 @ 912:5e80956cc792

History | View | Annotate | Download (21.3 KB)

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