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