user.rb 18.2 KB
Newer Older
1
#-- encoding: UTF-8
2 3
#-- copyright
# ChiliProject is a project management system.
4
#
Holger Just's avatar
Holger Just committed
5
# Copyright (C) 2010-2013 the ChiliProject Team
6
#
7 8 9 10
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
11
#
12 13 14
# See doc/COPYRIGHT.rdoc for more details.
#++

15 16
require "digest/sha1"

17
class User < Principal
18
  include Redmine::SafeAttributes
19

20
  # Account statuses
21
  STATUS_ANONYMOUS  = 0
22 23 24
  STATUS_ACTIVE     = 1
  STATUS_REGISTERED = 2
  STATUS_LOCKED     = 3
25

26 27 28 29 30 31 32
  USER_FORMATS = {
    :firstname_lastname => '#{firstname} #{lastname}',
    :firstname => '#{firstname}',
    :lastname_firstname => '#{lastname} #{firstname}',
    :lastname_coma_firstname => '#{lastname}, #{firstname}',
    :username => '#{login}'
  }
33

34
  MAIL_NOTIFICATION_OPTIONS = [
35 36 37 38 39 40 41
    ['all', :label_user_mail_option_all],
    ['selected', :label_user_mail_option_selected],
    ['only_my_events', :label_user_mail_option_only_my_events],
    ['only_assigned', :label_user_mail_option_only_assigned],
    ['only_owner', :label_user_mail_option_only_owner],
    ['none', :label_user_mail_option_none]
  ]
42

43 44
  has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)},
                                   :after_remove => Proc.new {|user, group| group.user_removed(user)}
45
  has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
46
  has_many :changesets, :dependent => :nullify
47
  has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
48
  has_one :rss_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='feeds'"
49
  has_one :api_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='api'"
50
  belongs_to :auth_source
51

52 53
  # Active non-anonymous users scope
  named_scope :active, :conditions => "#{User.table_name}.status = #{STATUS_ACTIVE}"
54

55
  acts_as_customizable
56

57 58 59
  attr_accessor :password, :password_confirmation
  attr_accessor :last_before_login_on
  # Prevents unauthorized assignments
60
  attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
61

62
  validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
63
  validates_uniqueness_of :login, :if => Proc.new { |user| !user.login.blank? }, :case_sensitive => false
64
  validates_uniqueness_of :mail, :if => Proc.new { |user| !user.mail.blank? }, :case_sensitive => false
65
  # Login must contain lettres, numbers, underscores only
66
  validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
67 68
  validates_length_of :login, :maximum => 30
  validates_length_of :firstname, :lastname, :maximum => 30
69 70
  validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
  validates_length_of :mail, :maximum => 60, :allow_nil => true
71
  validates_confirmation_of :password, :allow_nil => true
72
  validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
73
  validates_inclusion_of :status, :in => [STATUS_ANONYMOUS, STATUS_ACTIVE, STATUS_REGISTERED, STATUS_LOCKED]
74

75 76 77 78
  named_scope :in_group, lambda {|group|
    group_id = group.is_a?(Group) ? group.id : group.to_i
    { :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] }
  }
79 80 81 82
  named_scope :not_in_group, lambda {|group|
    group_id = group.is_a?(Group) ? group.id : group.to_i
    { :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] }
  }
83

84
  def before_create
85
    self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
86 87
    true
  end
88

89 90
  def before_save
    # update hashed_password if password was set
91 92 93
    if self.password && self.auth_source_id.blank?
      salt_password(password)
    end
94
  end
95

96 97
  def reload(*args)
    @name = nil
98
    @projects_by_role = nil
99 100
    super
  end
101

102 103 104
  def mail=(arg)
    write_attribute(:mail, arg.to_s.strip)
  end
105

106
  def identity_url=(url)
107 108 109 110 111 112 113 114
    if url.blank?
      write_attribute(:identity_url, '')
    else
      begin
        write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
      rescue OpenIdAuthentication::InvalidOpenId
        # Invlaid url, don't save
      end
115 116 117
    end
    self.read_attribute(:identity_url)
  end
118

119 120
  # Returns the user that matches provided login and password, or nil
  def self.try_to_login(login, password)
121 122
    # Make sure no one can sign in with an empty password
    return nil if password.to_s.empty?
123
    user = find_by_login(login)
124 125 126 127 128 129 130 131
    if user
      # user is already in local database
      return nil if !user.active?
      if user.auth_source
        # user has an external authentication method
        return nil unless user.auth_source.authenticate(login, password)
      else
        # authentication with local password
132
        return nil unless user.check_password?(password)
133 134 135 136 137
      end
    else
      # user is not yet registered, try to authenticate with available sources
      attrs = AuthSource.authenticate(login, password)
      if attrs
138
        user = new(attrs)
139 140 141 142
        user.login = login
        user.language = Setting.default_language
        if user.save
          user.reload
143
          logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
144 145
        end
      end
146
    end
147
    user.update_attribute(:last_login_on, Time.now) if user && !user.new_record?
148
    user
149 150
  rescue => text
    raise text
151
  end
152

153 154
  # Returns the user who matches the given autologin +key+ or nil
  def self.try_to_autologin(key)
155 156 157 158 159 160 161 162
    tokens = Token.find_all_by_action_and_value('autologin', key)
    # Make sure there's only 1 token that matches the key
    if tokens.size == 1
      token = tokens.first
      if (token.created_on > Setting.autologin.to_i.day.ago) && token.user && token.user.active?
        token.user.update_attribute(:last_login_on, Time.now)
        token.user
      end
163 164
    end
  end
165

166
  # Return user's full name for display
167
  def name(formatter = nil)
168 169 170 171 172
    if formatter
      eval('"' + (USER_FORMATS[formatter] || USER_FORMATS[:firstname_lastname]) + '"')
    else
      @name ||= eval('"' + (USER_FORMATS[Setting.user_format] || USER_FORMATS[:firstname_lastname]) + '"')
    end
173
  end
174

175 176 177 178 179 180 181
  def active?
    self.status == STATUS_ACTIVE
  end

  def registered?
    self.status == STATUS_REGISTERED
  end
182

183 184 185 186
  def locked?
    self.status == STATUS_LOCKED
  end

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  def activate
    self.status = STATUS_ACTIVE
  end

  def register
    self.status = STATUS_REGISTERED
  end

  def lock
    self.status = STATUS_LOCKED
  end

  def activate!
    update_attribute(:status, STATUS_ACTIVE)
  end

  def register!
    update_attribute(:status, STATUS_REGISTERED)
  end

  def lock!
    update_attribute(:status, STATUS_LOCKED)
  end

211 212 213 214 215
  def deletable?
    registered? && last_login_on.nil?
  end


216
  # Returns true if +clear_password+ is the correct user's password, otherwise false
217
  def check_password?(clear_password)
218 219 220
    if auth_source_id.present?
      auth_source.authenticate(self.login, clear_password)
    else
221
      User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
222 223
    end
  end
224

225 226 227 228 229 230
  # Generates a random salt and computes hashed_password for +clear_password+
  # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
  def salt_password(clear_password)
    self.salt = User.generate_salt
    self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
  end
231 232 233 234 235

  # Does the backend storage allow this user to change their password?
  def change_password_allowed?
    return true if auth_source_id.blank?
    return auth_source.allow_password_changes?
236
  end
237 238 239 240 241 242 243 244 245 246 247 248

  # Generate and set a random password.  Useful for automated user creation
  # Based on Token#generate_token_value
  #
  def random_password
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    password = ''
    40.times { |i| password << chars[rand(chars.size-1)] }
    self.password = password
    self.password_confirmation = password
    self
  end
249

250 251 252
  def pref
    self.preference ||= UserPreference.new(:user => self)
  end
253

254
  def time_zone
255
    @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
256
  end
257

258 259 260
  def wants_comments_in_reverse_order?
    self.pref[:comments_sorting] == 'desc'
  end
261

262 263 264 265
  # Return user's RSS key (a 40 chars long string), used to access feeds
  def rss_key
    token = self.rss_token || Token.create(:user => self, :action => 'feeds')
    token.value
266
  end
267 268 269

  # Return user's API key (a 40 chars long string), used to access the API
  def api_key
270
    token = self.api_token || self.create_api_token(:action => 'api')
271 272
    token.value
  end
273

274 275 276 277
  # Return an array of project ids for which the user has explicitly turned mail notifications on
  def notified_projects_ids
    @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
  end
278

279 280 281 282 283 284
  def notified_project_ids=(ids)
    Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
    Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
    @notified_projects_ids = nil
    notified_projects_ids
  end
285

286
  def valid_notification_options
287 288 289 290 291
    self.class.valid_notification_options(self)
  end

  # Only users that belong to more than 1 project can select projects for which they are notified
  def self.valid_notification_options(user=nil)
292 293
    # Note that @user.membership.size would fail since AR ignores
    # :include association option when doing a count
294
    if user.nil? || user.memberships.length < 1
295
      MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
296 297 298 299 300
    else
      MAIL_NOTIFICATION_OPTIONS
    end
  end

301 302
  # Find a user account by matching the exact login and then a case-insensitive
  # version.  Exact matches will be given priority.
303
  def self.find_by_login(login)
304
    # force string comparison to be case sensitive on MySQL
305
    type_cast = (ChiliProject::Database.mysql?) ? 'BINARY' : ''
306
    # First look for an exact match
307
    user = first(:conditions => ["#{type_cast} login = ?", login])
308
    # Fail over to case-insensitive if none was found
309
    user ||= first(:conditions => ["#{type_cast} LOWER(login) = ?", login.to_s.downcase])
310 311
  end

312 313 314 315
  def self.find_by_rss_key(key)
    token = Token.find_by_value(key)
    token && token.user.active? ? token.user : nil
  end
316

317 318 319 320
  def self.find_by_api_key(key)
    token = Token.find_by_action_and_value('api', key)
    token && token.user.active? ? token.user : nil
  end
321

322 323 324 325
  # Makes find_by_mail case-insensitive
  def self.find_by_mail(mail)
    find(:first, :conditions => ["LOWER(mail) = ?", mail.to_s.downcase])
  end
326

327 328 329
  def to_s
    name
  end
330

331 332 333 334 335 336 337 338
  # Returns the current day according to user's time zone
  def today
    if time_zone.nil?
      Date.today
    else
      Time.now.in_time_zone(time_zone).to_date
    end
  end
339

340 341 342
  def logged?
    true
  end
343

344 345 346
  def anonymous?
    !logged?
  end
347

348 349 350
  # Return user's roles for project
  def roles_for_project(project)
    roles = []
351
    # No role on archived projects
352
    return roles unless project && project.active?
353 354 355 356
    if logged?
      # Find project membership
      membership = memberships.detect {|m| m.project_id == project.id}
      if membership
357
        roles = membership.roles
358 359
      else
        @role_non_member ||= Role.non_member
360
        roles << @role_non_member
361
      end
362
    else
363
      @role_anonymous ||= Role.anonymous
364
      roles << @role_anonymous
365
    end
366
    roles
367
  end
368

369 370
  # Return true if the user is a member of project
  def member_of?(project)
371
    !roles_for_project(project).detect {|role| role.member?}.nil?
372
  end
373

374 375 376
  # Returns a hash of user's projects grouped by roles
  def projects_by_role
    return @projects_by_role if @projects_by_role
377

378 379 380 381 382 383 384 385 386
    @projects_by_role = Hash.new {|h,k| h[k]=[]}
    memberships.each do |membership|
      membership.roles.each do |role|
        @projects_by_role[role] << membership.project if membership.project
      end
    end
    @projects_by_role.each do |role, projects|
      projects.uniq!
    end
387

388 389
    @projects_by_role
  end
390

391 392
  # Return true if the user is allowed to do the specified action on a specific context
  # Action can be:
393 394
  # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
  # * a permission Symbol (eg. :edit_project)
395 396 397
  # Context can be:
  # * a project : returns true if user is allowed to do the specified action on this project
  # * a group of projects : returns true if user is allowed on every project
398
  # * nil with options[:global] set : check if user has at least one role allowed for this action,
399
  #   or falls back to Non Member / Anonymous permissions depending if the user is logged
400 401
  def allowed_to?(action, context, options={})
    if context && context.is_a?(Project)
402
      # No action allowed on archived projects
403
      return false unless context.active?
404
      # No action allowed on disabled modules
405
      return false unless context.allows_to?(action)
406 407
      # Admin users are authorized for anything else
      return true if admin?
408

409
      roles = roles_for_project(context)
410
      return false unless roles
411
      roles.detect {|role| (context.is_public? || role.member?) && role.allowed_to?(action)}
412

413
    elsif context && context.is_a?(Array)
414
      # Authorize if user is authorized on every element of the array
415 416 417 418
      context.map do |project|
        allowed_to?(action,project,options)
      end.inject do |memo,allowed|
        memo && allowed
419
      end
420
    elsif options[:global]
421 422
      # Admin users are always authorized
      return true if admin?
423

424
      # authorize if user has at least one role that has this permission
425
      roles = memberships.collect {|m| m.roles}.flatten.uniq
426
      roles.detect {|r| r.allowed_to?(action)} || (self.logged? ? Role.non_member.allowed_to?(action) : Role.anonymous.allowed_to?(action))
427 428 429
    else
      false
    end
430
  end
431 432 433 434 435 436

  # Is the user allowed to do the specified action on any project?
  # See allowed_to? for the actions and valid options.
  def allowed_to_globally?(action, options)
    allowed_to?(action, nil, options.reverse_merge(:global => true))
  end
437 438 439 440 441 442 443 444 445 446

  safe_attributes 'login',
    'firstname',
    'lastname',
    'mail',
    'mail_notification',
    'language',
    'custom_field_values',
    'custom_fields',
    'identity_url'
447

448 449 450
  safe_attributes 'status',
    'auth_source_id',
    :if => lambda {|user, current_user| current_user.admin?}
451

452 453
  safe_attributes 'group_ids',
    :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
454

455 456 457 458 459
  # Utility method to help check if a user should be notified about an
  # event.
  #
  # TODO: only supports Issue events currently
  def notify_about?(object)
460 461
    case mail_notification
    when 'all'
462
      true
463
    when 'selected'
464 465 466 467 468 469
      # user receives notifications for created/assigned issues on unselected projects
      if object.is_a?(Issue) && (object.author == self || object.assigned_to == self)
        true
      else
        false
      end
470
    when 'none'
471
      false
472
    when 'only_my_events'
473 474 475 476 477
      if object.is_a?(Issue) && (object.author == self || object.assigned_to == self)
        true
      else
        false
      end
478
    when 'only_assigned'
479 480 481 482 483
      if object.is_a?(Issue) && object.assigned_to == self
        true
      else
        false
      end
484
    when 'only_owner'
485 486 487 488 489 490 491 492 493
      if object.is_a?(Issue) && object.author == self
        true
      else
        false
      end
    else
      false
    end
  end
494

495 496 497
  def self.current=(user)
    @current_user = user
  end
498

499
  def self.current
500
    @current_user ||= User.anonymous
501
  end
502

503 504
  # Returns the anonymous user.  If the anonymous user does not exist, it is created.  There can be only
  # one anonymous user per database.
505
  def self.anonymous
506 507 508 509 510
    anonymous_user = AnonymousUser.find(:first)
    if anonymous_user.nil?
      anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
      raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
    end
511
    anonymous_user
512
  end
513 514 515 516 517 518 519 520 521 522 523 524 525 526

  # Salts all existing unsalted passwords
  # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
  # This method is used in the SaltPasswords migration and is to be kept as is
  def self.salt_unsalted_passwords!
    transaction do
      User.find_each(:conditions => "salt IS NULL OR salt = ''") do |user|
        next if user.hashed_password.blank?
        salt = User.generate_salt
        hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
        User.update_all("salt = '#{salt}', hashed_password = '#{hashed_password}'", ["id = ?", user.id] )
      end
    end
  end
527

528
  protected
529

530 531 532 533 534
  def validate
    # Password length validation based on setting
    if !password.nil? && password.size < Setting.password_min_length.to_i
      errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
    end
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

    # Status
    if !new_record? && status_changed?
      case status_was
      when nil
        # initial setting is always save
        true
      when STATUS_ANONYMOUS
        # never allow a state change of the anonymous user
        false
      when STATUS_REGISTERED
        [STATUS_ACTIVE, STATUS_LOCKED].include? status
      when STATUS_ACTIVE
        [STATUS_LOCKED].include? status
      when STATUS_LOCKED
        [STATUS_ACTIVE].include? status
      end || errors.add(:status, :inclusion)
    end
553
  end
554

555
  private
556

557 558 559
  # Return password digest
  def self.hash_password(clear_password)
    Digest::SHA1.hexdigest(clear_password || "")
Jean-Philippe Lang's avatar
Jean-Philippe Lang committed
560
  end
561

562 563 564 565
  # Returns a 128bits random salt as a hex string (32 chars long)
  def self.generate_salt
    ActiveSupport::SecureRandom.hex(16)
  end
566

Jean-Philippe Lang's avatar
Jean-Philippe Lang committed
567
end
568 569

class AnonymousUser < User
570

571 572 573
  def validate_on_create
    # There should be only one AnonymousUser in the database
    errors.add_to_base 'An anonymous user already exists.' if AnonymousUser.find(:first)
574
  end
575

576 577 578
  def available_custom_fields
    []
  end
579

580 581 582
  # Overrides a few properties
  def logged?; false end
  def admin; false end
583
  def name(*args); I18n.t(:label_user_anonymous) end
584 585 586
  def mail; nil end
  def time_zone; nil end
  def rss_key; nil end
587
end