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 @ 913:b502ad91d302

History | View | Annotate | Download (21.3 KB)

1
# Redmine - project management software
2
# Copyright (C) 2006-2011  Jean-Philippe Lang
3
#
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
#
9
# 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
#
14
# 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
  include Redmine::SafeAttributes
22

    
23
  # Account statuses
24
  STATUS_ANONYMOUS  = 0
25
  STATUS_ACTIVE     = 1
26
  STATUS_REGISTERED = 2
27
  STATUS_LOCKED     = 3
28

    
29
  # Different ways of displaying/sorting users
30
  USER_FORMATS = {
31
    :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
  }
37

    
38
  MAIL_NOTIFICATION_OPTIONS = [
39
    ['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

    
47
  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
  has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'"
52
  has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
53
  belongs_to :auth_source
54

    
55
  has_one :ssamr_user_detail, :dependent => :destroy, :class_name => 'SsamrUserDetail'
56
  accepts_nested_attributes_for :ssamr_user_detail
57
  
58
  has_one :author
59

    
60
  # Active non-anonymous users scope
61
  named_scope :active, :conditions => "#{User.table_name}.status = #{STATUS_ACTIVE}"
62

    
63
  acts_as_customizable
64

    
65
  attr_accessor :password, :password_confirmation
66
  attr_accessor :last_before_login_on
67
  # Prevents unauthorized assignments
68
  attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
69
        
70
  validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
71
  
72
  # TODO: is this validation correct validates_presence_of :ssamr_user_detail
73
  
74
  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
  validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_blank => true
81
  validates_length_of :mail, :maximum => 60, :allow_nil => true
82
  validates_confirmation_of :password, :allow_nil => true
83
  validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
84
  validate :validate_password_length
85

    
86
  before_create :set_mail_notification
87
  before_save   :update_hashed_password
88
  before_destroy :remove_references_before_destroy
89

    
90
  validates_acceptance_of :terms_and_conditions, :on => :create, :message => :must_accept_terms_and_conditions
91

    
92
  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

    
101
  def set_mail_notification
102
    self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
103
    true
104
  end
105

    
106
  def update_hashed_password
107
    # update hashed_password if password was set
108
    if self.password && self.auth_source_id.blank?
109
      salt_password(password)
110
    end
111
  end
112

    
113
  def reload(*args)
114
    @name = nil
115
    @projects_by_role = nil
116
    super
117
  end
118

    
119
  def mail=(arg)
120
    write_attribute(:mail, arg.to_s.strip)
121
  end
122

    
123
  def description=(arg)
124
    write_attribute(:description, arg.to_s.strip)
125
  end
126
    
127
  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

    
140
  # 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
        return nil unless user.check_password?(password)
154
      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
    end
168
    user.update_attribute(:last_login_on, Time.now) if user && !user.new_record?
169
    user
170
  rescue => text
171
    raise text
172
  end
173

    
174
  # 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

    
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
  # Return user's full name for display
203
  def name(formatter = nil)
204
    f = self.class.name_formatter(formatter)
205
    if formatter
206
      eval('"' + f[:string] + '"')
207
    else
208
      @name ||= eval('"' + f[:string] + '"')
209
    end
210
  end
211

    
212
  def active?
213
    self.status == STATUS_ACTIVE
214
  end
215

    
216
  def registered?
217
    self.status == STATUS_REGISTERED
218
  end
219

    
220
  def locked?
221
    self.status == STATUS_LOCKED
222
  end
223

    
224
  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
  # Returns true if +clear_password+ is the correct user's password, otherwise false
249
  def check_password?(clear_password)
250
    if auth_source_id.present?
251
      auth_source.authenticate(self.login, clear_password)
252
    else
253
      User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
254
    end
255
  end
256

    
257
  # 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

    
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

    
282
  def pref
283
    self.preference ||= UserPreference.new(:user => self)
284
  end
285

    
286
  def time_zone
287
    @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
288
  end
289

    
290
  def wants_comments_in_reverse_order?
291
    self.pref[:comments_sorting] == 'desc'
292
  end
293

    
294
  # 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

    
306
  # 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

    
311
  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
  def valid_notification_options
319
    self.class.valid_notification_options(self)
320
  end
321

    
322
  # Only users that belong to more than 1 project can select projects for which they are notified
323
  def self.valid_notification_options(user=nil)
324
    # Note that @user.membership.size would fail since AR ignores
325
    # :include association option when doing a count
326
    if user.nil? || user.memberships.length < 1
327
      MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
328
    else
329
      MAIL_NOTIFICATION_OPTIONS
330
    end
331
  end
332

    
333
  # 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

    
339
    # 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

    
350
  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

    
355
  # 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

    
360
  def to_s
361
    name
362
  end
363

    
364
  # 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

    
373
  def logged?
374
    true
375
  end
376

    
377
  def anonymous?
378
    !logged?
379
  end
380

    
381
  # 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

    
402
  # 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

    
407
  # 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

    
411
    @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

    
421
    @projects_by_role
422
  end
423

    
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
  # Return true if the user is allowed to do the specified action on a specific context
436
  # Action can be:
437
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
438
  # * a permission Symbol (eg. :edit_project)
439
  # Context can be:
440
  # * a project : returns true if user is allowed to do the specified action on this project
441
  # * an array of projects : returns true if user is allowed on every project
442
  # * nil with options[:global] set : check if user has at least one role allowed for this action,
443
  #   or falls back to Non Member / Anonymous permissions depending if the user is logged
444
  def allowed_to?(action, context, options={}, &block)
445
    if context && context.is_a?(Project)
446
      # No action allowed on archived projects
447
      return false unless context.active?
448
      # No action allowed on disabled modules
449
      return false unless context.allows_to?(action)
450
      # Admin users are authorized for anything else
451
      return true if admin?
452

    
453
      roles = roles_for_project(context)
454
      return false unless roles
455
      roles.detect {|role|
456
        (context.is_public? || role.member?) &&
457
        role.allowed_to?(action) &&
458
        (block_given? ? yield(role, self) : true)
459
      }
460
    elsif context && context.is_a?(Array)
461
      # Authorize if user is authorized on every element of the array
462
      context.map do |project|
463
        allowed_to?(action, project, options, &block)
464
      end.inject do |memo,allowed|
465
        memo && allowed
466
      end
467
    elsif options[:global]
468
      # Admin users are always authorized
469
      return true if admin?
470

    
471
      # authorize if user has at least one role that has this permission
472
      roles = memberships.collect {|m| m.roles}.flatten.uniq
473
      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
    else
479
      false
480
    end
481
  end
482

    
483
  # Is the user allowed to do the specified action on any project?
484
  # See allowed_to? for the actions and valid options.
485
  def allowed_to_globally?(action, options, &block)
486
    allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
487
  end
488

    
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

    
499
  safe_attributes 'status',
500
    'auth_source_id',
501
    :if => lambda {|user, current_user| current_user.admin?}
502

    
503
  safe_attributes 'group_ids',
504
    :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
505

    
506
  # 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
    case mail_notification
512
    when 'all'
513
      true
514
    when 'selected'
515
      # user receives notifications for created/assigned issues on unselected projects
516
      if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to))
517
        true
518
      else
519
        false
520
      end
521
    when 'none'
522
      false
523
    when 'only_my_events'
524
      if object.is_a?(Issue) && (object.author == self || is_or_belongs_to?(object.assigned_to))
525
        true
526
      else
527
        false
528
      end
529
    when 'only_assigned'
530
      if object.is_a?(Issue) && is_or_belongs_to?(object.assigned_to)
531
        true
532
      else
533
        false
534
      end
535
    when 'only_owner'
536
      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

    
546
  def self.current=(user)
547
    @current_user = user
548
  end
549

    
550
  def self.current
551
    @current_user ||= User.anonymous
552
  end
553

    
554
  # 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

    
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

    
579
  protected
580

    
581
  def validate_password_length
582
    # 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

    
588
  private
589

    
590
  # 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

    
595
    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

    
615
  # Return password digest
616
  def self.hash_password(clear_password)
617
    Digest::SHA1.hexdigest(clear_password || "")
618
  end
619

    
620
  # 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

    
625
end
626

    
627
class AnonymousUser < User
628

    
629
  def validate_on_create
630
    # There should be only one AnonymousUser in the database
631
    errors.add :base, 'An anonymous user already exists.' if AnonymousUser.find(:first)
632
  end
633

    
634
  def available_custom_fields
635
    []
636
  end
637

    
638
  # 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

    
646
  # Anonymous user can not be destroyed
647
  def destroy
648
    false
649
  end
650
end