annotate .svn/pristine/c0/c0d36c34eac79fa2295c3fdedaa72256c805d292.svn-base @ 1524:82fac3dcf466 redmine-2.5-integration

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