annotate app/models/user.rb @ 1517:dffacf8a6908 redmine-2.5

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