Class: User

Inherits:
Principal show all
Includes:
Redmine::SafeAttributes
Defined in:
app/models/user.rb

Direct Known Subclasses

AnonymousUser

Constant Summary collapse

USER_FORMATS =

Different ways of displaying/sorting users

{
  :firstname_lastname => {
      :string => '#{firstname} #{lastname}',
      :order => %w(firstname lastname id),
      :setting_order => 1
    },
  :firstname_lastinitial => {
      :string => '#{firstname} #{lastname.to_s.chars.first}.',
      :order => %w(firstname lastname id),
      :setting_order => 2
    },
  :firstinitial_lastname => {
      :string => '#{firstname.to_s.gsub(/(([[:alpha:]])[[:alpha:]]*\.?)/, \'\2.\')} #{lastname}',
      :order => %w(firstname lastname id),
      :setting_order => 2
    },
  :firstname => {
      :string => '#{firstname}',
      :order => %w(firstname id),
      :setting_order => 3
    },
  :lastname_firstname => {
      :string => '#{lastname} #{firstname}',
      :order => %w(lastname firstname id),
      :setting_order => 4
    },
  :lastname_coma_firstname => {
      :string => '#{lastname}, #{firstname}',
      :order => %w(lastname firstname id),
      :setting_order => 5
    },
  :lastname => {
      :string => '#{lastname}',
      :order => %w(lastname id),
      :setting_order => 6
    },
  :username => {
      :string => '#{login}',
      :order => %w(login id),
      :setting_order => 7
    },
}
MAIL_NOTIFICATION_OPTIONS =
[
  ['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]
]
LOGIN_LENGTH_LIMIT =
60
MAIL_LENGTH_LIMIT =
60
CSS_CLASS_BY_STATUS =
{
  STATUS_ANONYMOUS  => 'anon',
  STATUS_ACTIVE     => 'active',
  STATUS_REGISTERED => 'registered',
  STATUS_LOCKED     => 'locked'
}

Constants inherited from Principal

Principal::STATUS_ACTIVE, Principal::STATUS_ANONYMOUS, Principal::STATUS_LOCKED, Principal::STATUS_REGISTERED

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Redmine::SafeAttributes

#delete_unsafe_attributes, included, #safe_attribute?, #safe_attribute_names, #safe_attributes=

Methods inherited from Principal

#<=>, #member_of?, #visible?

Instance Attribute Details

#generate_passwordObject

Returns the value of attribute generate_password


91
92
93
# File 'app/models/user.rb', line 91

def generate_password
  @generate_password
end

#last_before_login_onObject

Returns the value of attribute last_before_login_on


92
93
94
# File 'app/models/user.rb', line 92

def 
  @last_before_login_on
end

#passwordObject

Returns the value of attribute password


91
92
93
# File 'app/models/user.rb', line 91

def password
  @password
end

#password_confirmationObject

Returns the value of attribute password_confirmation


91
92
93
# File 'app/models/user.rb', line 91

def password_confirmation
  @password_confirmation
end

Class Method Details

.anonymousObject

Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only one anonymous user per database.


669
670
671
672
673
674
675
676
# File 'app/models/user.rb', line 669

def self.anonymous
  anonymous_user = AnonymousUser.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
  anonymous_user
end

.currentObject


663
664
665
# File 'app/models/user.rb', line 663

def self.current
  RequestStore.store[:current_user] ||= User.anonymous
end

.current=(user) ⇒ Object


659
660
661
# File 'app/models/user.rb', line 659

def self.current=(user)
  RequestStore.store[:current_user] = user
end

.default_admin_account_changed?Boolean

Returns true if the default admin account can no longer be used

Returns:

  • (Boolean)

428
429
430
# File 'app/models/user.rb', line 428

def self.
  !User.active.("admin").try(:check_password?, "admin")
end

.fields_for_order_statement(table = nil) ⇒ Object

Returns an array of fields names than can be used to make an order statement for users according to how user names are displayed Examples:

User.fields_for_order_statement              => ['users.login', 'users.id']
User.fields_for_order_statement('authors')   => ['authors.login', 'authors.id']

231
232
233
234
# File 'app/models/user.rb', line 231

def self.fields_for_order_statement(table=nil)
  table ||= table_name
  name_formatter[:order].map {|field| "#{table}.#{field}"}
end

.find_by_api_key(key) ⇒ Object


418
419
420
# File 'app/models/user.rb', line 418

def self.find_by_api_key(key)
  Token.find_active_user('api', key)
end

.find_by_login(login) ⇒ Object

Find a user account by matching the exact login and then a case-insensitive version. Exact matches will be given priority.


401
402
403
404
405
406
407
408
409
410
411
412
# File 'app/models/user.rb', line 401

def self.()
   = Redmine::CodesetUtil.replace_invalid_utf8(.to_s)
  if .present?
    # First look for an exact match
    user = where(:login => ).detect {|u| u. == }
    unless user
      # Fail over to case-insensitive if none was found
      user = where("LOWER(login) = ?", .downcase).first
    end
    user
  end
end

.find_by_mail(mail) ⇒ Object

Makes find_by_mail case-insensitive


423
424
425
# File 'app/models/user.rb', line 423

def self.find_by_mail(mail)
  where("LOWER(mail) = ?", mail.to_s.downcase).first
end

.find_by_rss_key(key) ⇒ Object


414
415
416
# File 'app/models/user.rb', line 414

def self.find_by_rss_key(key)
  Token.find_active_user('feeds', key)
end

.find_or_initialize_by_identity_url(url) ⇒ Object


159
160
161
162
163
164
165
166
# File 'app/models/user.rb', line 159

def self.find_or_initialize_by_identity_url(url)
  user = where(:identity_url => url).first
  unless user
    user = User.new
    user.identity_url = url
  end
  user
end

.name_formatter(formatter = nil) ⇒ Object


221
222
223
# File 'app/models/user.rb', line 221

def self.name_formatter(formatter = nil)
  USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
end

.salt_unsalted_passwords!Object

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


681
682
683
684
685
686
687
688
689
690
# File 'app/models/user.rb', line 681

def self.salt_unsalted_passwords!
  transaction do
    User.where("salt IS NULL OR salt = ''").find_each do |user|
      next if user.hashed_password.blank?
      salt = User.generate_salt
      hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
      User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
    end
  end
end

.try_to_autologin(key) ⇒ Object

Returns the user who matches the given autologin key or nil


213
214
215
216
217
218
219
# File 'app/models/user.rb', line 213

def self.try_to_autologin(key)
  user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
  if user
    user.update_column(:last_login_on, Time.now)
    user
  end
end

.try_to_login(login, password, active_only = true) ⇒ Object

Returns the user that matches provided login and password, or nil


182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'app/models/user.rb', line 182

def self.(, password, active_only=true)
   = .to_s
  password = password.to_s

  # Make sure no one can sign in with an empty login or password
  return nil if .empty? || password.empty?
  user = ()
  if user
    # user is already in local database
    return nil unless user.check_password?(password)
    return nil if !user.active? && active_only
  else
    # user is not yet registered, try to authenticate with available sources
    attrs = AuthSource.authenticate(, password)
    if attrs
      user = new(attrs)
      user. = 
      user.language = Setting.default_language
      if user.save
        user.reload
        logger.info("User '#{user.}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
      end
    end
  end
  user.update_column(:last_login_on, Time.now) if user && !user.new_record? && user.active?
  user
rescue => text
  raise text
end

.valid_notification_options(user = nil) ⇒ Object

Only users that belong to more than 1 project can select projects for which they are notified


389
390
391
392
393
394
395
396
397
# File 'app/models/user.rb', line 389

def self.valid_notification_options(user=nil)
  # Note that @user.membership.size would fail since AR ignores
  # :include association option when doing a count
  if user.nil? || user.memberships.length < 1
    MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
  else
    MAIL_NOTIFICATION_OPTIONS
  end
end

Instance Method Details

#activateObject


258
259
260
# File 'app/models/user.rb', line 258

def activate
  self.status = STATUS_ACTIVE
end

#activate!Object


270
271
272
# File 'app/models/user.rb', line 270

def activate!
  update_attribute(:status, STATUS_ACTIVE)
end

#active?Boolean

Returns:

  • (Boolean)

246
247
248
# File 'app/models/user.rb', line 246

def active?
  self.status == STATUS_ACTIVE
end

#allowed_to?(action, context, options = {}, &block) ⇒ Boolean

Return true if the user is allowed to do the specified action on a specific context Action can be:

  • a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')

  • a permission Symbol (eg. :edit_project)

Context can be:

  • a project : returns true if user is allowed to do the specified action on this project

  • an array of projects : returns true if user is allowed on every project

  • nil with options set : check if user has at least one role allowed for this action, or falls back to Non Member / Anonymous permissions depending if the user is logged

Returns:

  • (Boolean)

557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
# File 'app/models/user.rb', line 557

def allowed_to?(action, context, options={}, &block)
  if context && context.is_a?(Project)
    return false unless context.allows_to?(action)
    # Admin users are authorized for anything else
    return true if admin?

    roles = roles_for_project(context)
    return false unless roles
    roles.any? {|role|
      (context.is_public? || role.member?) &&
      role.allowed_to?(action) &&
      (block_given? ? yield(role, self) : true)
    }
  elsif context && context.is_a?(Array)
    if context.empty?
      false
    else
      # Authorize if user is authorized on every element of the array
      context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
    end
  elsif context
    raise ArgumentError.new("#allowed_to? context argument must be a Project, an Array of projects or nil")
  elsif options[:global]
    # Admin users are always authorized
    return true if admin?

    # authorize if user has at least one role that has this permission
    roles = memberships.collect {|m| m.roles}.flatten.uniq
    roles << (self.logged? ? Role.non_member : Role.anonymous)
    roles.any? {|role|
      role.allowed_to?(action) &&
      (block_given? ? yield(role, self) : true)
    }
  else
    false
  end
end

#allowed_to_globally?(action, options = {}, &block) ⇒ Boolean

Is the user allowed to do the specified action on any project? See allowed_to? for the actions and valid options.

NB: this method is not used anywhere in the core codebase as of 2.5.2, but it's used by many plugins so if we ever want to remove it it has to be carefully deprecated for a version or two.

Returns:

  • (Boolean)

601
602
603
# File 'app/models/user.rb', line 601

def allowed_to_globally?(action, options={}, &block)
  allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
end

#anonymous?Boolean

Returns:

  • (Boolean)

469
470
471
# File 'app/models/user.rb', line 469

def anonymous?
  !logged?
end

#api_keyObject

Return user's API key (a 40 chars long string), used to access the API


357
358
359
360
361
362
# File 'app/models/user.rb', line 357

def api_key
  if api_token.nil?
    create_api_token(:action => 'api')
  end
  api_token.value
end

#base_reloadObject


143
# File 'app/models/user.rb', line 143

alias :base_reload :reload

#builtin_roleObject

Returns the user's bult-in role


485
486
487
# File 'app/models/user.rb', line 485

def builtin_role
  @builtin_role ||= Role.non_member
end

#change_password_allowed?Boolean

Does the backend storage allow this user to change their password?

Returns:

  • (Boolean)

300
301
302
303
# File 'app/models/user.rb', line 300

def change_password_allowed?
  return true if auth_source.nil?
  return auth_source.allow_password_changes?
end

#check_password?(clear_password) ⇒ Boolean

Returns true if clear_password is the correct user's password, otherwise false

Returns:

  • (Boolean)

283
284
285
286
287
288
289
# File 'app/models/user.rb', line 283

def check_password?(clear_password)
  if auth_source_id.present?
    auth_source.authenticate(self., clear_password)
  else
    User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
  end
end

#css_classesObject


443
444
445
# File 'app/models/user.rb', line 443

def css_classes
  "user #{CSS_CLASS_BY_STATUS[status]}"
end

#force_default_language?Boolean

Returns:

  • (Boolean)

332
333
334
# File 'app/models/user.rb', line 332

def force_default_language?
  Setting.force_default_language_for_loggedin?
end

#generate_password?Boolean

Returns:

  • (Boolean)

309
310
311
# File 'app/models/user.rb', line 309

def generate_password?
  generate_password == '1' || generate_password == true
end

#identity_url=(url) ⇒ Object


168
169
170
171
172
173
174
175
176
177
178
179
# File 'app/models/user.rb', line 168

def identity_url=(url)
  if url.blank?
    write_attribute(:identity_url, '')
  else
    begin
      write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
    rescue OpenIdAuthentication::InvalidOpenId
      # Invalid url, don't save
    end
  end
  self.read_attribute(:identity_url)
end

#is_or_belongs_to?(arg) ⇒ Boolean

Returns true if user is arg or belongs to arg

Returns:

  • (Boolean)

538
539
540
541
542
543
544
545
546
# File 'app/models/user.rb', line 538

def is_or_belongs_to?(arg)
  if arg.is_a?(User)
    self == arg
  elsif arg.is_a?(Group)
    arg.users.include?(self)
  else
    false
  end
end

#languageObject


336
337
338
339
340
341
342
# File 'app/models/user.rb', line 336

def language
  if force_default_language?
    Setting.default_language
  else
    super
  end
end

#lockObject


266
267
268
# File 'app/models/user.rb', line 266

def lock
  self.status = STATUS_LOCKED
end

#lock!Object


278
279
280
# File 'app/models/user.rb', line 278

def lock!
  update_attribute(:status, STATUS_LOCKED)
end

#locked?Boolean

Returns:

  • (Boolean)

254
255
256
# File 'app/models/user.rb', line 254

def locked?
  self.status == STATUS_LOCKED
end

#logged?Boolean

Returns:

  • (Boolean)

465
466
467
# File 'app/models/user.rb', line 465

def logged?
  true
end

#mail=(arg) ⇒ Object


155
156
157
# File 'app/models/user.rb', line 155

def mail=(arg)
  write_attribute(:mail, arg.to_s.strip)
end

#membership(project) ⇒ Object

Returns user's membership for the given project or nil if the user is not a member of project


475
476
477
478
479
480
481
482
# File 'app/models/user.rb', line 475

def membership(project)
  project_id = project.is_a?(Project) ? project.id : project

  @membership_by_project_id ||= Hash.new {|h, project_id|
    h[project_id] = memberships.where(:project_id => project_id).first
  }
  @membership_by_project_id[project_id]
end

#must_change_password?Boolean

Returns:

  • (Boolean)

305
306
307
# File 'app/models/user.rb', line 305

def must_change_password?
  must_change_passwd? && change_password_allowed?
end

#name(formatter = nil) ⇒ Object

Return user's full name for display


237
238
239
240
241
242
243
244
# File 'app/models/user.rb', line 237

def name(formatter = nil)
  f = self.class.name_formatter(formatter)
  if formatter
    eval('"' + f[:string] + '"')
  else
    @name ||= eval('"' + f[:string] + '"')
  end
end

#notified_project_ids=(ids) ⇒ Object


369
370
371
372
# File 'app/models/user.rb', line 369

def notified_project_ids=(ids)
  @notified_projects_ids_changed = true
  @notified_projects_ids = ids.map(&:to_i).uniq.select {|n| n > 0}
end

#notified_projects_idsObject

Return an array of project ids for which the user has explicitly turned mail notifications on


365
366
367
# File 'app/models/user.rb', line 365

def notified_projects_ids
  @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
end

#notify_about?(object) ⇒ Boolean

Utility method to help check if a user should be notified about an event.

TODO: only supports Issue events currently

Returns:

  • (Boolean)

635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'app/models/user.rb', line 635

def notify_about?(object)
  if mail_notification == 'all'
    true
  elsif mail_notification.blank? || mail_notification == 'none'
    false
  else
    case object
    when Issue
      case mail_notification
      when 'selected', 'only_my_events'
        # user receives notifications for created/assigned issues on unselected projects
        object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
      when 'only_assigned'
        is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
      when 'only_owner'
        object.author == self
      end
    when News
      # always send to project members except when mail_notification is set to 'none'
      true
    end
  end
end

#own_account_deletable?Boolean

Returns true if the user is allowed to delete the user's own account

Returns:

  • (Boolean)

606
607
608
609
# File 'app/models/user.rb', line 606

def 
  Setting.unsubscribe? &&
    (!admin? || User.active.where("admin = ? AND id <> ?", true, id).exists?)
end

#prefObject


324
325
326
# File 'app/models/user.rb', line 324

def pref
  self.preference ||= UserPreference.new(:user => self)
end

#projects_by_roleObject

Returns a hash of user's projects grouped by roles


503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'app/models/user.rb', line 503

def projects_by_role
  return @projects_by_role if @projects_by_role

  hash = Hash.new([])

  group_class = anonymous? ? GroupAnonymous : GroupNonMember
  members = Member.joins(:project, :principal).
    where("#{Project.table_name}.status <> 9").
    where("#{Member.table_name}.user_id = ? OR (#{Project.table_name}.is_public = ? AND #{Principal.table_name}.type = ?)", self.id, true, group_class.name).
    preload(:project, :roles).
    to_a

  members.reject! {|member| member.user_id != id && project_ids.include?(member.project_id)}
  members.each do |member|
    if member.project
      member.roles.each do |role|
        hash[role] = [] unless hash.key?(role)
        hash[role] << member.project
      end
    end
  end
  
  hash.each do |role, projects|
    projects.uniq!
  end

  @projects_by_role = hash
end

#random_password(length = 40) ⇒ Object

Generate and set a random password on given length


314
315
316
317
318
319
320
321
322
# File 'app/models/user.rb', line 314

def random_password(length=40)
  chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
  chars -= %w(0 O 1 l)
  password = ''
  length.times {|i| password << chars[SecureRandom.random_number(chars.size)] }
  self.password = password
  self.password_confirmation = password
  self
end

#registerObject


262
263
264
# File 'app/models/user.rb', line 262

def register
  self.status = STATUS_REGISTERED
end

#register!Object


274
275
276
# File 'app/models/user.rb', line 274

def register!
  update_attribute(:status, STATUS_REGISTERED)
end

#registered?Boolean

Returns:

  • (Boolean)

250
251
252
# File 'app/models/user.rb', line 250

def registered?
  self.status == STATUS_REGISTERED
end

#reload(*args) ⇒ Object


144
145
146
147
148
149
150
151
152
153
# File 'app/models/user.rb', line 144

def reload(*args)
  @name = nil
  @projects_by_role = nil
  @membership_by_project_id = nil
  @notified_projects_ids = nil
  @notified_projects_ids_changed = false
  @builtin_role = nil
  @visible_project_ids = nil
  base_reload(*args)
end

#roles_for_project(project) ⇒ Object

Return user's roles for project


490
491
492
493
494
495
496
497
498
499
500
# File 'app/models/user.rb', line 490

def roles_for_project(project)
  # No role on archived projects
  return [] if project.nil? || project.archived?
  if membership = membership(project)
    membership.roles.dup
  elsif project.is_public?
    project.override_roles(builtin_role)
  else
    []
  end
end

#rss_keyObject

Return user's RSS key (a 40 chars long string), used to access feeds


349
350
351
352
353
354
# File 'app/models/user.rb', line 349

def rss_key
  if rss_token.nil?
    create_rss_token(:action => 'feeds')
  end
  rss_token.value
end

#salt_password(clear_password) ⇒ Object

Generates a random salt and computes hashed_password for clear_password The hashed password is stored in the following form: SHA1(salt + SHA1(password))


293
294
295
296
297
# File 'app/models/user.rb', line 293

def salt_password(clear_password)
  self.salt = User.generate_salt
  self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
  self.passwd_changed_on = Time.now
end

#set_mail_notificationObject


131
132
133
134
# File 'app/models/user.rb', line 131

def set_mail_notification
  self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
  true
end

#time_to_date(time) ⇒ Object

Returns the day of time according to user's time zone


457
458
459
460
461
462
463
# File 'app/models/user.rb', line 457

def time_to_date(time)
  if time_zone.nil?
    time.to_date
  else
    time.in_time_zone(time_zone).to_date
  end
end

#time_zoneObject


328
329
330
# File 'app/models/user.rb', line 328

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

#to_sObject


432
433
434
# File 'app/models/user.rb', line 432

def to_s
  name
end

#todayObject

Returns the current day according to user's time zone


448
449
450
451
452
453
454
# File 'app/models/user.rb', line 448

def today
  if time_zone.nil?
    Date.today
  else
    Time.now.in_time_zone(time_zone).to_date
  end
end

#update_hashed_passwordObject


136
137
138
139
140
141
# File 'app/models/user.rb', line 136

def update_hashed_password
  # update hashed_password if password was set
  if self.password && self.auth_source_id.blank?
    salt_password(password)
  end
end

#valid_notification_optionsObject


384
385
386
# File 'app/models/user.rb', line 384

def valid_notification_options
  self.class.valid_notification_options(self)
end

#visible_project_idsObject

Returns the ids of visible projects


533
534
535
# File 'app/models/user.rb', line 533

def visible_project_ids
  @visible_project_ids ||= Project.visible(self).pluck(:id)
end

#wants_comments_in_reverse_order?Boolean

Returns:

  • (Boolean)

344
345
346
# File 'app/models/user.rb', line 344

def wants_comments_in_reverse_order?
  self.pref[:comments_sorting] == 'desc'
end