annotate app/models/user.rb @ 1295:622f24f53b42 redmine-2.3

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